A class for manipulating an open ProgressDialog.
      public async void ShowProgressDialog()
      {
          
          MetroDialogSettings settings = new MetroDialogSettings() { NegativeButtonText = "Cancel", AnimateShow = true, AnimateHide=true };
          _controller = await _dialogCoordinator.ShowProgressAsync(this, "Screen8ViewModel is working on something", "", true, settings);
 
      }
		private async void BtnLogin_Click(object sender, RoutedEventArgs e)
		{
			var email = TextBoxEmail.Text;
			if(string.IsNullOrEmpty(email) || !Regex.IsMatch(email, @".*@.*\..*"))
			{
				DisplayLoginError("Please enter an valid email address");
				return;
			}
			if(string.IsNullOrEmpty(TextBoxPassword.Password))
			{
				DisplayLoginError("Please enter a password");
				return;
			}
			IsEnabled = false;
			_controller = await this.ShowProgressAsync("Logging in...", "");
			var result = await HearthStatsAPI.LoginAsync(TextBoxEmail.Text, TextBoxPassword.Password);
			TextBoxPassword.Clear();
			if(result.Success)
			{
				LoginResult = LoginType.Login;
				Close();
			}
			else if(result.Message.Contains("401"))
				DisplayLoginError("Invalid email or password");
			else
				DisplayLoginError(result.Message);
		}
        /// <summary>
        ///     Runs CanEnable asynchronously multiple times until successful, cancelled or max tries reached
        /// </summary>
        /// <param name="dialog"></param>
        /// <returns></returns>
        public Task<bool> CanEnableAsync(ProgressDialogController dialog)
        {
            return Task.Run(() =>
            {
                for (var tries = 1; tries <= 10; tries++)
                {
                    // Dialog interaction
                    if (dialog != null)
                    {
                        // Stop if cancelled by user
                        if (dialog.IsCanceled)
                        {
                            dialog.SetIndeterminate();
                            return false;
                        }
                        // Updated progress to indicate how much tries are left
                        dialog.SetProgress(0.1*tries);
                    }

                    if (CanEnable())
                    {
                        dialog?.SetIndeterminate();
                        return true;
                    }
                    Thread.Sleep(2000);
                }
                dialog?.SetIndeterminate();
                return false;
            });
        }
        public async void ShowProgress(string location, bool isSvn, string autoInstallName = null)
        {
            controller = await this.ShowProgressAsync("Updating...", "Downloading the required data.");
            controller.SetIndeterminate();

            ListAssemblies(location, isSvn, autoInstallName);
        }
        public string CreateXmlDb(List<MagicCard> listOfCards, ProgressDialogController dialogController)
        {
            var curCard = 0;
            var totalCards = listOfCards.Count;

            foreach (var distinctSet in listOfCards.DistinctBy(o => o.Set))
            {
                var enumerable = listOfCards.Where(op => op.Set == distinctSet.Set && op.PathOfCardImage.Contains("original")).DistinctBy(o => o.Name);
                foreach (var distinctCard in enumerable)
                {
                    var cardElement = _xmlfile.CreateElement("card");
                    AddChildElementAndValue(cardElement, _util.GetVariableName(() => distinctCard.Name), distinctCard.Name);
                    AddChildElementAndValue(cardElement, _util.GetVariableName(() => distinctCard.Set), distinctCard.Set);
                    AddChildElementAndValue(cardElement, _util.GetVariableName(() => distinctCard.PathOfCardImage), distinctCard.PathOfCardImage);

                    var phashesElement = _xmlfile.CreateElement("phashes");
                    foreach (var magicCard in listOfCards.Where(o => o.Name == distinctCard.Name && o.Set == distinctSet.Set))
                    {
                        foreach (var phash in magicCard.PHashes)
                        {
                            AddChildElementAndValue(phashesElement, "phash", phash.ToString());
                        }
                    }
                    cardElement.AppendChild(phashesElement);
                    _rootNode.AppendChild(cardElement);
                    curCard++;
                    dialogController.SetProgress((double)curCard / totalCards);
                    dialogController.SetMessage("Creating a Simple Database of all those pHashes: " + curCard + "/" + totalCards);
                }
            }

            SaveXmlFile();
            return Path.GetFullPath(XmlDbPath);
        }
 public async void ShowProgress(string location, bool isSvn, string autoInstallName = null)
 {
     controller =
         await
             this.ShowProgressAsync(
                 Utility.GetMultiLanguageText("Updating"), Utility.GetMultiLanguageText("DownloadingData"));
     controller.SetIndeterminate();
     controller.SetCancelable(true);
     ListAssemblies(location, isSvn, autoInstallName);
 }
        public async Task ShowProgressDialog(string title, string message)
        {
            var dictionary = new ResourceDictionary();
            dictionary.Source = new Uri("pack://application:,,,/MaterialDesignThemes.MahApps;component/Themes/MaterialDesignTheme.MahApps.Dialogs.xaml");

            MetroDialogSettings settings = new MetroDialogSettings();
            settings.CustomResourceDictionary = dictionary;
            settings.SuppressDefaultResources = true;

            _progressDialogController = await this.ShowProgressAsync(title, message, false, settings);
        }
        public async Task CloseProgressDialog()
        {
            if (_progressDialogController == null)
                return;

            if (_progressDialogController.IsOpen)
            {
                await _progressDialogController.CloseAsync();
            }

            _progressDialogController = null;
        }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            TestRunWorker testRunWorker = (TestRunWorker)faultModel.TestRunWorker;
            testRunWorker.InitialDesired = (double)InitialValueNumUpDown.Value;
            testRunWorker.FinalDesired = (double)FinalValueNumUpDown.Value;
            testRunWorker.RunWorkerCompleted += TestRunWorker_RunWorkerCompleted;

            progressController = await this.ShowProgressAsync("Please wait...", "Model simulation running");
            progressController.SetIndeterminate();
            testRunWorker.RunWorkerAsync(faultModel);

            log("Step Fault Model - Ran model with initial desired value " + testRunWorker.InitialDesired + " and final desired value " + testRunWorker.FinalDesired);

        }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            TestRunWorker testRunWorker = (TestRunWorker)faultModel.TestRunWorker;
            testRunWorker.Desired = (double)DesiredValueNumUpDown.Value;
            testRunWorker.TestCase = TestCaseComboBox.SelectedIndex + 1;
            testRunWorker.RunWorkerCompleted += TestRunWorker_RunWorkerCompleted;
                        
            progressController = await this.ShowProgressAsync("Please wait...", "Model simulation running");
            progressController.SetIndeterminate();

            testRunWorker.RunWorkerAsync(faultModel);

            log("Allowed Oscillation Fault Model - Ran the model with desired value " + testRunWorker.Desired + " and test case" + testRunWorker.TestCase);
        }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            TestRunWorker testRunWorker = (TestRunWorker)faultModel.TestRunWorker;
            testRunWorker.Desired = (double)DesiredValueNumUpDown.Value;
            testRunWorker.Frequency = (double)FrequencyNumUpDown.Value;
            testRunWorker.RunWorkerCompleted += TestRunWorker_RunWorkerCompleted;

            progressController = await this.ShowProgressAsync("Please wait...", "Model simulation running");
            progressController.SetIndeterminate();
            testRunWorker.RunWorkerAsync(faultModel);

            log("Disturbance Fault Model - Ran model with desired value " + testRunWorker.Desired + " and frequency " + testRunWorker.Frequency);

        }
Exemple #12
0
        private async void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            var email = txtEMail.Text;
            var pwd = txtPwd.Password;

            if (string.IsNullOrEmpty(email) && string.IsNullOrEmpty(pwd))
            {
                txtError.Text = "Please enter a EMail and a Password!";
                return;
            }
            else if (string.IsNullOrEmpty(pwd))
            {
                txtError.Text = "Please enter a Password";
                return;
            }
            else if (string.IsNullOrEmpty(email))
            {
                txtError.Text = "Please enter a EMail";
                return;
            }
            txtError.Text = "";

            IsEnabled = false;
            _controller = await this.ShowProgressAsync("Logging in...", "Authenticating...");
            _controller.SetIndeterminate();

            var result = await Task.Factory.StartNew(() =>
            {
                return commander.AuthenticateUser(email, pwd);
            });

            txtPwd.Password = "";

            await _controller.CloseAsync();

            IsEnabled = true;
            if (result == true)
            {
                await this.ShowMessageAsync("Authenticated", "Login success!");
                MainWindow mainWindow = new MainWindow();
                mainWindow.Show();
                Close();
            }
            else
            {
                txtError.Text = "Combination of EMail and Password is incorrect!";
            }
            _controller.SetProgress(1);
        }
Exemple #13
0
        private void ParseStatement(XElement xml, ProgressDialogController progress, DBContext context, bool skipLastDateCheck)
        {
            const int totalActions = 12;

            progress.SetProgress(1.0 / totalActions);
            ParseSecuritiesInfo(xml, context);

            string accountId = xml.Attribute("accountId").Value;
            Account account = context.Accounts.First(x => x.AccountId == accountId);

            DateTime lastDate =
                context.CashTransactions.Any(x => x.AccountID == account.ID)
                ? context.CashTransactions.Max(x => x.TransactionDate)
                : new DateTime(1, 1, 1);

            progress.SetProgress(2.0 / totalActions);
            ParseCashTransactions(xml, context, skipLastDateCheck, lastDate, account);

            progress.SetProgress(3.0 / totalActions);
            ParseCFDCharges(xml, context, skipLastDateCheck, lastDate, account);

            progress.SetProgress(4.0 / totalActions);
            ParseOrders(xml, context, skipLastDateCheck, account);

            progress.SetProgress(5.0 / totalActions);
            ParseExecutions(xml, context, skipLastDateCheck, account);

            progress.SetProgress(6.0 / totalActions);
            ParseEquitySummaries(xml, context, account);

            progress.SetProgress(7.0 / totalActions);
            ParseOpenPositions(xml, context, account);

            progress.SetProgress(8.0 / totalActions);
            ParseFXRates(xml, context);

            progress.SetProgress(9.0 / totalActions);
            ParsePriorPeriodPositions(xml, context, skipLastDateCheck, account);

            progress.SetProgress(10.0 / totalActions);
            ParseOpenDividendAccruals(xml, context, account);

            progress.SetProgress(11.0 / totalActions);
            ParseFXPositions(xml, context, account);

            progress.SetProgress(12.0 / totalActions);
            ParseFXTransactions(xml, context, skipLastDateCheck, account);
        }
		private static async Task CleanUpGameFiles(ProgressDialogController controller)
		{
			var count = 0;
			int gamesCount;
			var lockMe = new object();
			var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount };
			await Task.Run(() =>
			{
				var games = DeckStatsList.Instance.DeckStats.SelectMany(x => x.Games).Concat(DefaultDeckStats.Instance.DeckStats.SelectMany(x => x.Games)).ToList();
				gamesCount = games.Count;
				Parallel.ForEach(games, options, (game, loopState) =>
				{
					if(controller.IsCanceled)
					{
						loopState.Stop();
						return;
					}
					if(game.OpponentCards.Any())
						return;
					var oppCards = GetOpponentDeck(game);
					if(oppCards.Any())
						game.SetOpponentCards(oppCards);
					game.DeleteGameFile();
					lock(lockMe)
					{
						controller.SetProgress(1.0 * ++count / gamesCount);
					}
				});
			});
			DeckStatsList.Save();
			DefaultDeckStats.Save();
			if(!controller.IsCanceled)
			{
				try
				{
					Directory.Delete(GamesDir, true);
				}
				catch(Exception e)
				{
					Log.Error(e);
				}
			}
		}
 public async Task<List<PlayableBase>> GetTracks(ProgressDialogController controller)
 {
     var alltracks = SearchTotalResults.Number;
     
     var resultList = new List<PlayableBase>();
     var counter = 0;
     for (int i = 0; i < (int)Math.Ceiling((double)alltracks / 50); i++)
     {
         var tracks = YouTubeApi.GetPlaylistTracks(await YouTubeApi.GetPlaylist(PlaylistId.Text, counter, 50));
         for (int j = 0; j < tracks.Count; j++)
         {
             var track = tracks[j];
             if (LoadingTracksProcessChanged != null)
                 LoadingTracksProcessChanged(this, new LoadingTracksEventArgs(counter + j, alltracks, track.Title));
             resultList.Add(track.ToPlayable());
             if (controller.IsCanceled) return null;
         }
         counter += 50;
     }
     return resultList;
 }
Exemple #16
0
        public void Parse(string flexXML, ProgressDialogController progress)
        {
            progress.SetMessage("Parsing Flex File");
            var context = new DBContext();
            context.Configuration.AutoDetectChangesEnabled = false;

            bool skipLastDateCheck = !Properties.Settings.Default.preventDuplicateImports;

            XDocument xml = XDocument.Parse(flexXML);

            ParseAccounts(xml, context);

            IEnumerable<XElement> flexStatements = xml.Descendants("FlexStatement");

            foreach(XElement flexStatement in flexStatements)
            {
                ParseStatement(flexStatement, progress, context, skipLastDateCheck);
            }

            context.Configuration.AutoDetectChangesEnabled = true;
            context.Dispose();
        }
        private async void PerformanceDay_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!initialized)
                return;
            else {
                if (PerformanceDay.SelectedItem != null)
                {
                    var selectedItem = (DateTime)PerformanceDay.SelectedItem;
                    IsEnabled = false;
                    _controller = await mainWindow.ShowProgressAsync("Performances", "Loading...");
                    _controller.SetIndeterminate();

                    await Task.Factory.StartNew(() =>
                    {
                        ufoVM.LoadPerformancesOfDay(selectedItem);
                    });

                    await _controller.CloseAsync();

                    IsEnabled = true;
                    _controller.SetProgress(1);
                }
            }
        }
 public void ComputePHashes(string selectedPath, ProgressDialogController dialogController)
 {
     ListOfMagicCards.Clear();
     //read images in resources
     Util.TraverseTree(@"H:\Compy Sci\MTG-Scanner\MTG-Scanner\Resources\Card Images", ListOfMagicCards);
     //Util.TraverseTree(selectedPath, ListOfMagicCards);
     //Util.TraverseTree(selectedPath, ListOfMagicCards);
     //compute hashes
     var curCard = 0;
     var totalCards = ListOfMagicCards.Count;
     Parallel.ForEach(ListOfMagicCards, card =>
     {
         var hash = Util.ComputePHash(card);
         card.PHashes.Add(hash);
         curCard++;
         dialogController.SetProgress((double)curCard / totalCards);
         dialogController.SetMessage("pHashing real hard! Finished: " + curCard + "/" + totalCards);
     });
 }
		private async void BtnRegister_Click(object sender, RoutedEventArgs e)
		{
			if(!CheckBoxPrivacyPolicy.IsChecked == true)
				return;

			var email = TextBoxRegisterEmail.Text;
			if(string.IsNullOrEmpty(email) || !Regex.IsMatch(email, @".*@.*\..*"))
			{
				DisplayLoginError("Please enter an valid email address");
				return;
			}
			if(string.IsNullOrEmpty(TextBoxRegisterPassword.Password))
			{
				DisplayLoginError("Please enter a password");
				return;
			}
			if(TextBoxRegisterPassword.Password.Length < 6)
			{
				DisplayLoginError("Your password needs to be at least 6 characters");
				return;
			}
			if(string.IsNullOrEmpty(TextBoxRegisterPasswordConfirm.Password))
			{
				DisplayLoginError("Please confirm your password");
				return;
			}
			if(!TextBoxRegisterPassword.Password.Equals(TextBoxRegisterPasswordConfirm.Password))
			{
				DisplayLoginError("Entered passwords do not match");
				return;
			}
			IsEnabled = false;
			_controller = await this.ShowProgressAsync("Registering account...", "");
			var result = await HearthStatsAPI.RegisterAsync(email, TextBoxRegisterPassword.Password);
			if(result.Success)
			{
				_controller.SetTitle("Logging in...");
				result = await HearthStatsAPI.LoginAsync(email, TextBoxRegisterPassword.Password);
			}
			else if(result.Message.Contains("422"))
				DisplayLoginError("Email already registered");
			else
				DisplayLoginError(result.Message);
			TextBoxRegisterPassword.Clear();
			TextBoxRegisterPasswordConfirm.Clear();
			if(result.Success)
			{
				var mw = new MainWindow();
				mw.Show();
				Close();
			}
		}
 private async void UpdateBtn_Click(object sender, RoutedEventArgs e)
 {
     _controller2 = await this.ShowProgressAsync("Updating...", "Updating the WebConfig File..." );
     _controller2.SetCancelable(false);
     _controller2.SetIndeterminate();
     config.webConfig_News = txt_News.Text;
     config.Software = txt_Software.Text;
     config.LatestVersion = txt_LatestVersion.Text;
     config.Language = txt_Language.Text;
     config.notAvailableMsg = txt_notAvailableMsg.Text;
     config.MasterIP = txt_MasterIP.Text;
     config.MasterIPDNS = txt_MasterIPDNS.Text;
     Core.JsonUpdate.Create.File();
     Core.JsonUpdate.Upload.File();
     pause(5);
     await _controller2.CloseAsync();
 }
        async void jsonwb_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            _9GUSLauncher.MainWindow.config = JsonConvert.DeserializeObject<Config.Config>(e.Result);

            pause(1);
            StandardLog("SoftwareID " + Convert.ToString(config.SoftwareID) + " authenticated");
            mainForm.Title += " - ID " + Convert.ToString(config.SoftwareID);

            //Check for Updates

            StandardLog("Checking for Updates...");
            CheckForUpdates();
              //Create Update dir

                if (!Directory.Exists(workingDir + "\\Update"))
                {
                    Directory.CreateDirectory(workingDir + "\\Update");
                }
                else
                {
                    Directory.Delete(workingDir + "\\Update", true);
                    Directory.CreateDirectory(workingDir + "\\Update");
                }

                WebClient wb = new WebClient();

                if (result > 0)
                {
                    try
                    {
                        StandardLog("Version " + config.LatestVersion + " is available. Downloading...");
                        _controller = await this.ShowProgressAsync("Please wait...", "Downloading the update " + config.LatestVersion);
                        _controller.SetCancelable(false);
                        _controller.SetIndeterminate();
                        wb.DownloadFileAsync(new Uri(softwareCfg.updateFile), workingDir + "\\Update\\9GUSLauncher.exe");
                        wb.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloadProgress);
                        wb.DownloadFileCompleted += new AsyncCompletedEventHandler(completedDownload);
                    }
                    catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); }


                }
                else if (result < 0)
                {
                    StandardLog("You are running a Beta Version. No Updates will be done."); // the update system isn't in the freeze problem
                    //No Update, version is more than latest
                }
                else
                {
                    StandardLog("Version Stable. No Updates needed.");
                    //Version Stable
                    LeftToRightMarquee();
                    login_button.IsEnabled = true;
                }


        }
        private async void eventMod_Click(object sender, RoutedEventArgs e)
        {
            if (!config.Administrators.Contains(txt_User.Text))
            {
                MsgBox("Error", "You MUST be and Administrator to complete this action!");
                return;
            }

            if (string.IsNullOrEmpty(txtmissionNameMod.Text) ||
               string.IsNullOrEmpty(comboMapMod.SelectedItem.ToString()) ||
               string.IsNullOrEmpty(Convert.ToString(nudPlayersMod.Value)) ||
               string.IsNullOrEmpty(txtmissionDescriptionMod.Text))
            {
                MsgBox("Error", "Please compile all field before create the event!");
                return;
            }

            BackgroundWorker bgWorker = new BackgroundWorker() { WorkerReportsProgress = true };
            bgWorker.DoWork += (s, ee) =>
            {
                try
                {
                    Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(async () =>
                    {
                        _eventVar = new eventVar();
                        List<string> _modList = new List<string>();
                        foreach (string item in modListMod.SelectedItems)
                        {
                            _modList.Add(item);
                        }
                        _eventVar.eventName = txtmissionNameMod.Text;
                        _eventVar.eventDate = Convert.ToDateTime(eventCalendarMod.SelectedDate);
                        _eventVar.eventMap = comboMapMod.SelectedItem.ToString();
                        _eventVar.eventType = comboTypeMod.SelectedItem.ToString();
                        _eventVar.eventMinPlayers = Convert.ToInt16(nudPlayersMod.Value);
                        _eventVar.eventDescription = txtmissionDescriptionMod.Text;
                        _eventVar.eventMods = _modList.ToArray();
                        List<string> subs = new List<string>();
                        string[] _subs = null;
                        foreach (string sub in eventListViewSubs.Items)
                        {
                            subs.Add(sub);
                        }

                        _subs = subs.ToArray();

                        _eventVar.eventSubscribers = _subs;

                        string eventFileName = txtmissionNameMod.Text.Replace(" ", "_") + "_" + Convert.ToString(_eventVar.eventDate).Replace(" 00:00:00", "").Replace("/", "-") + "_" + _eventVar.eventMap;

                        if (System.IO.File.Exists(workingDir + "\\Config\\" + _eventFileName))
                        {
                            System.IO.File.Delete(workingDir + "\\Config\\" + _eventFileName);
                        }
                        Core.Events.MissionFile.Create.File(eventFileName, _eventVar);
                        Core.Events.MissionFile.Upload.File(eventFileName);
                        List<string> eventsList = new List<string>();
                        if (config.events != null)
                        {
                            foreach (string item in config.events)
                            {
                                eventsList.Add(item);
                            }
                            if (config.events.Contains(_eventFileName))
                            {
                                eventsList.Remove(_eventFileName);

                            }
                        }
                        eventsList.Add(eventFileName);
                        config.events = eventsList.ToArray();
                        Core.JsonUpdate.Create.File();
                        Core.JsonUpdate.Upload.File();


                    }));

                }
                catch (Exception ex)
                { System.Windows.MessageBox.Show(ex.ToString()); }
            };
            bgWorker.RunWorkerCompleted += async (s, ee) =>
            {
                pause(5);
                await _controller.CloseAsync();
                eventUpdating = true;
                this.eventListView.Items.Clear();
                this.eventListView.Items.Refresh();

                eventloadBase();
                eventUpdating = false;
            };

            bgWorker.RunWorkerAsync();
            _controller = await this.ShowProgressAsync("Please wait...", "Creating Online Event...");
            _controller.SetCancelable(false);
            _controller.SetIndeterminate();
        }
        private async void btnUnsub_Click(object sender, RoutedEventArgs e)
        {
            if (!eventListViewSubs.Items.Contains(txt_User.Text))
                MsgBox("Error", "You are not subscribed to this event!");
            else
            {
                BackgroundWorker bgWorker = new BackgroundWorker() { WorkerReportsProgress = true };
                bgWorker.DoWork += (s, ee) =>
                {
                    try
                    {
                        Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(async () =>
                        {
                            eventUpdating = true;
                            string eventSelected = this.eventListView.SelectedItem.ToString().Replace(" ", "_");
                            string encryptedJson = System.IO.File.ReadAllText(workingDir + "\\Config\\" + eventSelected);
                            string decryptedJson = CryptoService.Load.Decrypt(encryptedJson, softwareCfg.cipherKey);
                            eventVar _event = JsonConvert.DeserializeObject<eventVar>(decryptedJson);


                            eventListViewSubs.Items.Remove(txt_User.Text);
                            List<string> subs = new List<string>();
                            if (_event.eventSubscribers != null)
                            {
                                foreach (string sub in _event.eventSubscribers)
                                {
                                    subs.Add(sub);
                                }
                            }
                            subs.Remove(txt_User.Text);
                            _event.eventSubscribers = subs.ToArray();
                            string eventFileName = eventSelected;
                            System.IO.File.Delete(workingDir + "\\Config\\" + eventFileName);
                            Core.Events.MissionFile.Create.File(eventFileName, _event);
                            Core.Events.MissionFile.Upload.File(eventFileName);
                            eventUpdating = false;

                        }));

                    }
                    catch (Exception ex)
                    { System.Windows.MessageBox.Show(ex.ToString()); }
                };
                bgWorker.RunWorkerCompleted += async (s, ee) =>
                {
                    pause(5);
                    await pdC.CloseAsync();


                };

                bgWorker.RunWorkerAsync();
                pdC = await this.ShowProgressAsync("Please wait...", "Unsubscribing to this Event...");
                pdC.SetCancelable(false);
                pdC.SetIndeterminate();
            }
        }
        public async void eventloadBase()
        {
            if(eventUpdating == false)
            {
                comboMap.Items.Add("Stratis");
                comboMap.Items.Add("Altis");
                comboMap.Items.Add("Takistan");
                comboMap.Items.Add("Chernarous");
                comboMap.Items.Add("Bukovina");
                comboMap.Items.Add("Kunduz");

                comboType.Items.Add("COOP");
                comboType.Items.Add("PvP Public");
                comboType.Items.Add("PvP Private");

                comboMapMod.Items.Add("Stratis");
                comboMapMod.Items.Add("Altis");
                comboMapMod.Items.Add("Takistan");
                comboMapMod.Items.Add("Chernarous");
                comboMapMod.Items.Add("Bukovina");
                comboMapMod.Items.Add("Kunduz");

                comboTypeMod.Items.Add("COOP");
                comboTypeMod.Items.Add("PvP Public");
                comboTypeMod.Items.Add("PvP Private");

                try
                {
                    Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(async () =>
                    {
                        _controller = await this.ShowProgressAsync("Please wait...", "Setting up Events & Configs...\r\n\r\nThis operation may take some minutes...");
                        _controller.SetCancelable(false);
                        if (!string.IsNullOrEmpty(modPath))
                        {
                            string[] folders = System.IO.Directory.GetDirectories(modPath, "@*", System.IO.SearchOption.AllDirectories);

                            foreach (string folder in folders)
                            {
                                string input = folder;
                                string output = input.Split('@').Last();
                                modList.Items.Add("@" + output);
                                modListMod.Items.Add("@" + output);
                            }
                        }
                        else
                        {
                            modList.Items.Add("Please Select the Mods Path and restart the Application!");
                            modListMod.Items.Add("Please Select the Mods Path and restart the Application!");
                            eventCreate.IsEnabled = false;
                            eventMod.IsEnabled = false;
                        }

                        if (!Directory.Exists(workingDir + "\\Config"))
                        {
                            Directory.CreateDirectory(workingDir + "\\Config");

                        }
                        else
                        {
                            Directory.Delete(workingDir + "\\Config", true);
                            Directory.CreateDirectory(workingDir + "\\Config");
                        }


                        if (config.events != null)
                        {
                            foreach (string files in config.events)
                            {
                                DownloadFiles(files);
                            }
                        }

                        //Read events files

                        foreach (string _event in config.events)
                        {
                            eventListView.Items.Add(_event.Replace("_", " "));
                        }



                        pause(5);
                        await _controller.CloseAsync();

                    }));
                }
                catch (Exception ex)
                { System.Windows.MessageBox.Show(ex.ToString()); }
            }
            else
            {
                try
                {
                    Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(async () =>
                    {
                        _controller = await this.ShowProgressAsync("Please wait...", "Updating Events & Configs...");
                        _controller.SetCancelable(false);
                        if (!string.IsNullOrEmpty(modPath))
                        {
                            string[] folders = System.IO.Directory.GetDirectories(modPath, "@*", System.IO.SearchOption.AllDirectories);
                            modList.Items.Clear();
                            modListMod.Items.Clear();
                            
                            foreach (string folder in folders)
                            {
                                string input = folder;
                                string output = input.Split('@').Last();
                                modList.Items.Add("@" + output);
                                modListMod.Items.Add("@" + output);
                            }
                        }
                        else
                        {
                            modList.Items.Add("Please Select the Mods Path and restart the Application!");
                            modListMod.Items.Add("Please Select the Mods Path and restart the Application!");
                            eventCreate.IsEnabled = false;
                            eventMod.IsEnabled = false;
                        }

                        while(true)
                        {
 
                            if (!Directory.Exists(workingDir + "\\Config"))
                            {
                                Directory.CreateDirectory(workingDir + "\\Config");
                                break;
                            }
                            else
                            {
                                Directory.Delete(workingDir + "\\Config", true);
                                Directory.CreateDirectory(workingDir + "\\Config");
                                break;
                            }
                            
                                
                        }
                        


                        if (config.events != null)
                        {
                            foreach (string files in config.events)
                            {
                                DownloadFiles(files);
                            }
                        }

                        //Read events files

                        foreach (string _event in config.events)
                        {
                            eventListView.Items.Add(_event.Replace("_", " "));
                        }

                        eventUpdating = false;
                        pause(5);
                        await _controller.CloseAsync();

                    }));
                }
                catch (Exception ex)
                { System.Windows.MessageBox.Show(ex.ToString()); }
            }
            

        }
        private async void updateBtnUs_Click(object sender, RoutedEventArgs e)
        {
            _controller2 = await this.ShowProgressAsync("Updating...", "Updating the WebConfig File...");
            _controller2.SetCancelable(false);
            _controller2.SetIndeterminate();

            Core.JsonUpdate.Create.File();
            Core.JsonUpdate.Upload.File();
            pause(5);
            await _controller2.CloseAsync();
        }
 public string SavePHashes(string selectedPath, ProgressDialogController dialogController)
 {
     //Create Basic XML DB of pHashes
     var path = XmlFileCreator.CreateXmlDb(ListOfMagicCards, dialogController);
     return path;
 }
        private static Task DownloadFile(string uri, string filename, MetroWindow window, ProgressDialogController controller)
        {
            return Task.Run(() =>
            {
                WebClient client = new WebClient();
                client.DownloadProgressChanged += async (sender, e) =>
                {
                    double bytesIn = double.Parse(e.BytesReceived.ToString());
                    double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
                    double percentage = bytesIn / totalBytes * 100;
                    try
                    {
                        await window.Dispatcher.InvokeAsync(() =>
                        {
                            controller.SetProgress(int.Parse(Math.Truncate(percentage).ToString()));
                        });
                    }
                    catch
                    {

                    }
                };
                client.DownloadFileCompleted += async (sender, e) =>
                {
                    await controller.CloseAsync();
                    client.Dispose();
                };
                client.DownloadFileAsync(new Uri(uri), Environment.CurrentDirectory + filename);
            });
        }
        public async void StartCheck(Manifest mani, Manager mana)
        {
            this.mani = mani;
            this.mana = mana;
            this.controller = await this.ShowProgressAsync("Please wait...", "Initialisation");
            this.controller.SetProgress(0.1);
            this.controller.SetMessage("Aquisition du Manifest");
            await Task.Delay(1000);
            mani.setManifestServer(mana.getManifestServer());
            this.controller.SetMessage("Vérification du contenu locale");
            this.controller.SetProgress(0.3);
            mani.parse();
            this.controller.SetMessage("Comparaison des Dossiers et Fichiers");
            this.controller.SetProgress(0.5);
            mani.check(false);
            this.controller.SetMessage("Chargement des Résultats");
            this.controller.SetProgress(0.8);

            foreach (var item in this.DataGrid.Items)
            {
                this.DataGrid.Items.Remove(item);
            }

            foreach (var item in mani.getDirsToDelete())
            {
                ItemEntry it = new ItemEntry { TypeValue = "DELETE DIR", PathValue = item, ProgressValue = 0, SizeValue = "inconnu" };
                this.DataGrid.Items.Add(it);
                this.populate.Add(item);
            }

            foreach (var item in mani.getDirsToCreate())
            {
                ItemEntry it = new ItemEntry { TypeValue = "CREATE DIR", PathValue = item, ProgressValue = 0, SizeValue = "inconnu" };
                this.DataGrid.Items.Add(it);
                this.populate.Add(item);
            }

            foreach (var item in mani.getFilesToDelete())
            {
                ItemEntry it = new ItemEntry { TypeValue = "DELETE FILE", PathValue = item, ProgressValue = 0, SizeValue = "inconnu" };
                this.DataGrid.Items.Add(it);
                this.populate.Add(item);
            }

            foreach (var item in mani.getFilesToUpdate())
            {
                ItemEntry it = new ItemEntry { TypeValue = "UPDATE FILE", PathValue = item, ProgressValue = 0, SizeValue = "inconnu" };
                this.DataGrid.Items.Add(it);
                this.populate.Add(item);
            }

            foreach (var item in mani.getFilesToDownload())
            {
                ItemEntry it = new ItemEntry { TypeValue = "DOWNLOAD FILE", PathValue = item, ProgressValue = 0, SizeValue = "inconnu" };
                this.DataGrid.Items.Add(it);
                this.populate.Add(item);
            }
            
            await this.controller.CloseAsync();

        }
 public ProgressControllerAdapter(Metro.ProgressDialogController ctrler)
 {
     _controller           = ctrler;
     _controller.Canceled += Canceled;
     _controller.Closed   += Closed;
 }
Exemple #30
0
        public async Task<bool> LoadLastUpdateAndFill(ProgressDialogController controller)
        {
            DateTime start = DateTime.Now;
            InitializationController init = new InitializationController();
            
            await Task.Delay(2000);
            init.OnLoadingUpdate += delegate(object sender, string mess) { controller.SetMessage(mess); };
            if ( init.LoadData())
            {
                this.Dispatcher.Invoke(() =>
                {
                    this.Title += " | Game version = " + init.Version;
                });

                List<BuildingViewModel> usmodels = new List<BuildingViewModel>();
                List<BuildingViewModel> carmodels = new List<BuildingViewModel>();
                List<BuildingViewModel> chimmodels = new List<BuildingViewModel>();
                //Fill the forms
                //US
                foreach (AoABuilding b in init.UsBuildings)
                {
                    BuildingViewModel buioding = new BuildingViewModel(b);
                    usmodels.Add(buioding);
                }
                
                this.Dispatcher.Invoke(() =>
                {
                    FactionBuildingListView Usview = new FactionBuildingListView(new FactionViewModel(usmodels));
                    UsGrid.Children.Clear();
                    UsGrid.Children.Add(Usview);
                });
                init.UsBuildings.Clear();
            
                

                //Cartel
                foreach (AoABuilding b in init.CartelBuildings)
                {
                    BuildingViewModel buioding = new BuildingViewModel(b);
                    carmodels.Add(buioding);
                }
                
                this.Dispatcher.Invoke(() =>
                {
                    FactionBuildingListView cartelview = new FactionBuildingListView(new FactionViewModel(carmodels));
                    CartelGrid.Children.Clear();
                    CartelGrid.Children.Add(cartelview);
                });
                init.CartelBuildings.Clear();
                    
                

                //Chimera
                foreach (AoABuilding b in init.ChimeraBuildings)
                {
                    BuildingViewModel buioding = new BuildingViewModel(b);
                    chimmodels.Add(buioding);
                }
                
                this.Dispatcher.Invoke(() =>
                {
                    FactionBuildingListView chimview = new FactionBuildingListView(new FactionViewModel(chimmodels));
                    ChimeraGrid.Children.Clear();
                    ChimeraGrid.Children.Add(chimview);
                });

                init.ChimeraBuildings.Clear();
                controller.SetMessage("finished, time taken : " + (DateTime.Now - start).TotalSeconds);
                await Task.Delay(2000);
                
                return true;
            }
            else
            {
                init.Clear(); Console.Out.WriteLine(DateTime.Now.ToShortDateString() + " : loading last update failed."); 
                controller.SetMessage("loading failed...");
                await Task.Delay(2000); 
                return false;
            }
        }
 private async void ShowLoggingInDialog(LoginDialogData loginData) {
     MainWindow MainWindow = App.Kernel.Get<MainWindow>();
     MetroDialogSettings settings = new MetroDialogSettings() {
         ColorScheme = MetroDialogColorScheme.Accented,
         NegativeButtonText = LanguageManager.Model.CancelButton
     };
     controller = await MainWindow.ShowProgressAsync(LanguageManager.Model.LoginLogIn, String.Empty, true, settings);
     Login(loginData.Username, loginData.Password, false);
 }