Exemple #1
0
        /// <summary>
        /// Exit de app
        /// </summary>
        public async void ExitButton()
        {
            Response connection = await networkService.CheckConnection();

            if (!connection.IsSucess)
            {
                Application.Current.Shutdown();
            }
            else
            {
                DataAccess.BackupDB();
                Application.Current.Shutdown();
            }
        }
Exemple #2
0
        private async void LoadRates()
        {
            bool load;

            lbl_resultado.Text = "A atualizar taxas...";

            var connection = networkService.CheckConnection();

            if (!connection.IsSuccess)
            {
                LoadLocalRates();
                load = false;
            }
            else
            {
                await LoadApiRates();

                load = true;
            }

            if (Rates.Count == 0)
            {
                lbl_resultado.Text = "Não há ligação à Internet" + Environment.NewLine +
                                     "e não foram previamente carregadas as taxas." + Environment.NewLine +
                                     "Por favor tente mais tarde";


                lbl_status.Text = "Primeira inicialização deverá ter à internet";

                return;
            }


            cb_origem.DataSource    = Rates;
            cb_origem.DisplayMember = "Name";

            //corrige bug da Microsoft
            cb_destino.BindingContext = new BindingContext();

            cb_destino.DataSource    = Rates;
            cb_destino.DisplayMember = "Name";

            lbl_resultado.Text = "Taxas atualizadas...";

            if (load)
            {
                lbl_status.Text = string.Format("Taxas carregadas da internet em {0:F}", DateTime.Now);
            }
            else
            {
                lbl_status.Text = string.Format("Taxas carregadas da Base da Dados");
            }

            progressBar1.Value = 100;

            btn_convert.Enabled = true;
            btn_troca.Enabled   = true;
        }
Exemple #3
0
        private async void LoadRates()
        {
            bool load;

            LabelResultado.Text = "A atualizar taxas...";

            var connection = networkService.CheckConnection();

            if (!connection.IsSuccess)
            {
                LoadLocalRates();
                load = false;
            }
            else
            {
                await LoadApiRates();

                load = true;
            }

            if (Rates.Count == 0)
            {
                LabelResultado.Text = "Não há ligação á Internet" + Environment.NewLine +
                                      "e não foram previamente carregadas as taxas." + Environment.NewLine +
                                      "Tente mais tarde!";

                LabelStatus.Text = "Primeira inicialização deverá ter ligação á Internet";

                return;
            }

            ComboBoxOrigem.DataSource    = Rates;
            ComboBoxOrigem.DisplayMember = "Name";

            //Corrige bug da microsoft
            ComboBoxDestino.BindingContext = new BindingContext();

            ComboBoxDestino.DataSource = Rates;

            ComboBoxDestino.DisplayMember = "Name";

            LabelResultado.Text = "Taxas atualizadas...";

            if (load)
            {
                LabelStatus.Text = string.Format("Taxas carregadas da Internet em {0:F}", DateTime.Now);
            }
            else
            {
                LabelStatus.Text = string.Format("Taxas carregadas da Base de Dados");
            }

            ProgressBar1.Value = 100;

            ButtonConverter.Enabled = true;
            ButtonTroca.Enabled     = true;
        }
Exemple #4
0
        private async void LoadRates()
        {
            bool load;

            LabelResultado.Text = "A atualizar taxas...";

            var connection = networkService.CheckConnection();

            if (!connection.IsSuccess)
            {
                LoadLocalRates();
                load = false;
            }
            else
            {
                //Carrega os dados da api
                await LoadApiRates();

                load = true;
            }

            if (Rates.Count == 0)
            {
                LabelResultado.ForeColor = Color.Red;
                LabelStatus.ForeColor    = Color.Red;
                LabelResultado.Text      = "Não há ligação á Internet" + Environment.NewLine +
                                           "e não foram prévimente carregadas as taxas." + Environment.NewLine +
                                           "Tente mais tarde! ";
                LabelStatus.Text = "Primeira inicialização deverá ter a ligação á Internet.";
                return;
            }
            ComboBoxOrigem.DataSource    = Rates;
            ComboBoxOrigem.DisplayMember = "Name";

            //BindingContext é a Classe que nos liga os objetos do interface ao codigo
            //Corrige bug da microsoft -- faz o binding de duas combobox diferentes
            ComboBoxDestino.BindingContext = new BindingContext();
            ComboBoxDestino.DataSource     = Rates;
            ComboBoxDestino.DisplayMember  = "Name";


            ButtonConverter.Enabled = true;
            ButtonTroca.Enabled     = true;
            LabelResultado.Text     = "Taxas Atualizadas...";

            if (load)
            {
                LabelStatus.Text = string.Format("Taxas carregadas da internet em {0:F}", DateTime.Now);
            }
            else
            {
                LabelStatus.Text = string.Format("Taxas carregadas da Base de Dados ");
            }
            ProgressBar1.Value = 100;
        }
Exemple #5
0
        private async void LoadRates() //async para ser uma tarefa assincrona
        {
            bool load;

            labelResultado.Text = " A atualizar taxas...";

            var connection = networkService.CheckConnection();

            if (!connection.IsSucess)
            {
                LoadLocalRates();
                load = false;
            }
            else
            {
                await LoadApiRates();

                load = true;
            }

            if (Rates.Count == 0) //esta a dar erro pq rates esta null
            {
                labelResultado.Text = "Não há ligação á Internet" + Environment.NewLine + " e não foram " +
                                      "préviamente carregasdas as taxas." + Environment.NewLine + " Tente mais tarde!";

                labelStatus.Text = "Primeira inicialização deverá ter ligação à internet";
                return;
            }

            comboBoxOrigem.DataSource    = Rates;
            comboBoxOrigem.DisplayMember = "Name";

            //corrige bug da microsoft
            comboBoxDestino.BindingContext = new BindingContext();  //para ficarem com opções selecionadas diferentes

            comboBoxDestino.DataSource    = Rates;
            comboBoxDestino.DisplayMember = "Name";


            buttonConverter.Enabled = true;
            buttonTroca.Enabled     = true;

            labelResultado.Text = " Taxas atualizadas...";

            if (load)
            {
                labelStatus.Text = string.Format("Taxas carregadas da internet em {0:F}", DateTime.Now);
            }
            else
            {
                labelStatus.Text = string.Format("Taxas carregadas da base de dados");
            }

            progressBar1.Value = 100;
        }
Exemple #6
0
        private async void LoadRates()
        {
            bool load;

            lbl_Resultado.Text = "A atualizar taxas...";

            var connection = networkService.CheckConnection();

            if (!connection.IsSuccess)
            {
                LoadLocalRates();
                load = false;
            }
            else
            {
                await LoadApiRates();

                load = true;
            }

            if (Rates.Count == 0)
            {
                lbl_Resultado.Text = "Não há ligação á Internet" + Environment.NewLine +
                                     "e não foram prévimente carregadas as taxas." + Environment.NewLine +
                                     "Tente mais tarde!";

                lbl_Status.Text = "Primeira inicialização deverá ter ligação á Internet";
                return;
            }


            combo_Origem.DataSource    = Rates;
            combo_Origem.DisplayMember = "Name";

            combo_Destino.BindingContext = new BindingContext();

            combo_Destino.DataSource    = Rates;
            combo_Destino.DisplayMember = "Name";

            progressBar1.Value = 100;

            btn_Convert.Enabled = true;
            btn_Troca.Enabled   = true;

            lbl_Resultado.Text = "Taxas atualizadas...";

            if (load)
            {
                lbl_Status.Text = string.Format("Taxas carregadas da internet em {0:F}", DateTime.Now);
            }
            else
            {
                lbl_Status.Text = string.Format("Taxas carregadas da Base de Dados.");
            }
        }
Exemple #7
0
        private async void LoadRates()
        {
            bool load;

            lbl_resultado.Text = "A atualizar taxas...";

            var connection = networkService.CheckConnection();

            if (!connection.IsSuccess)
            {
                LoadLocarRates();
                load = false;
                return;
            }
            else
            {
                await LoadApiRates();

                load = true;
            }

            if (Rates.Count == 0)
            {
                lbl_resultado.Text = "Não há ligação á internet" + Environment.NewLine + "e não foram previamente carregadas as taxas." + Environment.NewLine + "Tente mais tarde";

                lbl_status.Text = "Primeira inicialização, deverá ter ligação á internet";
                return;
            }

            cb_origem.DataSource    = Rates;
            cb_origem.DisplayMember = "Name";

            cb_destino.BindingContext = new BindingContext();// Classe que nos liga o interface ao codigo. neste caso temos de dizer que as combo boxes têm destinos diferentes(Serve para corrigir bug da microsoft)

            cb_destino.DataSource    = Rates;
            cb_destino.DisplayMember = "Name";



            lbl_resultado.Text = "Taxas atualizadas";

            if (load)
            {
                lbl_status.Text = string.Format("Taxas carregadas da internet em {0:f}", DateTime.Now);
            }
            else
            {
                lbl_status.Text = string.Format("Taxas carregadas da dase de dados");
            }

            progressBar1.Value = 100;

            btn_converter.Enabled = true;
            btn_troca.Enabled     = true;
        }
Exemple #8
0
        private async void LoadRates()
        {
            bool load;

            lblResultado.Text = "A atualizar taxas...";

            var connection = networkService.CheckConnection(); //verificar se existe ligação à internet

            if (!connection.IsSuccess)                         //caso não exista ligação à internet
            {
                LoadLocalRates();
                load = false;
            }
            else//se existir ligação à internet
            {
                await LoadApiRates();

                load = true;
            }

            if (Rates.Count == 0)
            {
                lblResultado.Text = "Não há ligação à internet" + Environment.NewLine +
                                    "e não foram previamente carregadas taxas." + Environment.NewLine +
                                    "Tente mais tarde!";

                lblStatus.Text = "Primeira inicialização deverá ter ligação à internet";

                return;
            }

            cbOrigem.DataSource    = Rates;
            cbOrigem.DisplayMember = "Name";

            cbDestino.BindingContext = new BindingContext();//limpar o binding da comboBoxDestino

            cbDestino.DataSource    = Rates;
            cbDestino.DisplayMember = "Name";

            lblResultado.Text = "Taxas atualizadas...";

            if (load)
            {
                lblStatus.Text = string.Format($"Taxas carregadas da internet em {DateTime.Now:F}");
            }
            else
            {
                lblStatus.Text = string.Format("Taxas carregadas da base de dados.");
            }

            progressBar1.Value   = 100;
            btnConverter.Enabled = true;
            btnTroca.Enabled     = true;
        }
Exemple #9
0
        private async void LoadRates()
        {
            bool load; // Para saber se foi carregado ou não

            lbl_resultado.Text = "A atualizar taxas...";

            var connection = networkService.CheckConnection(); // Vai testar a conexão à internet

            if (!connection.IsSuccess)                         // Se a conexão não tiver sido feita com sucesso
            {
                LoadLocalRates();                              // Conecta-se à base de dados local
                load = false;
            }
            else // Se tiver conexão
            {
                await LoadApiRates(); // Conecta-se à Api que vai estabelecer ligação à base de dados online

                load = true;
            }

            if (rates.Count == 0) // Se a lista de rates não tiver sido carregada ou estiver vazia
            {
                lbl_resultado.Text = "Não há ligação à internet.\nNão foram previamente carregadas as taxas.\nTente novamente mais tarde.";
                lbl_status.Text    = "Primeira inicialização deverá ter ligação à Internet";
                return; // Termina a execução do método LoadRates()
            }

            cb_origem.DataSource    = rates;                  // Apresentar os valores da lista criada rates na comboBox origem
            cb_origem.DisplayMember = "Name";                 // Mostrar a propriedade Name nos items da comboBox

            cb_destino.BindingContext = new BindingContext(); // Permite que as comboBox deixem de estar ligadas/binding, permitindo escolher items diferentes

            cb_destino.DataSource    = rates;
            cb_destino.DisplayMember = "Name";

            lbl_resultado.Text = "Taxas carregadas com sucesso!";

            btn_converter.Enabled = true; // Ativa o botão para que seja possivel converter o valor inserido

            if (load)                     // Se a Api carregar
            {
                lbl_status.Text = string.Format("Taxas carregadas da internet em {0:F}", DateTime.Now);
            }
            else // Se for carregado através da base de dados local
            {
                lbl_status.Text = string.Format("Taxas carregadas da base de dados local.");
            }

            progressBar1.Value = 100;

            btn_converter.Enabled = true;
            btn_troca.Enabled     = true;
        }
Exemple #10
0
        /// <summary>
        /// Determines if the Program loads information from the API or the DB
        /// </summary>
        private async Task LoadCountries()
        {
            bool load;

            labelReport.Content = "Please wait while data is being loaded...";

            var connection = networkService.CheckConnection();

            if (!connection.IsSucess) //If there is no Internet Connection Available
            {
                await LoadLocalDataCountries();

                load = false;
            }
            else  //If there is Internet Connection
            {
                await LoadApiCountries();
                await LoadApiRates();
                await LoadApiWikipedia();
                await LoadApiHoliday();

                List <Country> listBoxList = ListOfCountries;
                listBoxCountries.ItemsSource = listBoxList;

                load = true;
            }

            if ((ListOfCountries == null) || (ListOfCountries.Count == 0))
            {
                labelReport.Content = "Please make sure you have a Internet Connection when you use the application for the first time. Try Again Later!";

                MessageBox.Show("Before using the App for the first time make sure there is a Internet Connection");

                return;
            }

            if (load)
            {
                await SaveCountryRates();
                await SaveCountryData();

                labelReport.Content = string.Format("(Data uploaded from the Internet, ({0:F})).", DateTime.Now.ToString("dddd, dd MMMM yyyy", new System.Globalization.CultureInfo("en-EN")));
            }
            else
            {
                labelReport.Content = string.Format("(Data uploaded from local Database, ({0:F})).", DateTime.Now.ToString("dddd, dd MMMM yyyy", new System.Globalization.CultureInfo("en-EN")));

                if ((ListOfCountries.Count > 0) || (ListOfCountries.Count < 250))
                {
                    MessageBox.Show("Your Database is incomplete. To prevent this, run your program while connected to the Internet. Try Again Later!");
                }
            }
        }
Exemple #11
0
        private async void LoadRates()
        {
            bool load;

            lbl_resultado.Text = "A atualizar taxas ...";

            //verifica connection a internet
            var connection = networkService.CheckConnection();

            //se connection nao teve sucesso
            if (!connection.IsSuccess)
            {
                LoadLocalRates();
                load = false;
            }
            else
            {
                await LoadApiRates();

                load = true;
            }
            if (Rates.Count == 0)
            {
                lbl_resultado.Text = "Não há ligação a Internet" + Environment.NewLine + "e não foram préviamente carregadas as taxas." + Environment.NewLine + "Tente mais tarde";
                lbl_Status.Text    = "1ª inicialização deverá ter ligação a internet";
                return;
            }

            cb_Origem.DataSource    = Rates;
            cb_Origem.DisplayMember = "Name";

            //corrige bug da microsoft
            cb_Destino.BindingContext = new BindingContext();

            cb_Destino.DataSource    = Rates;
            cb_Destino.DisplayMember = "Name";

            btn_Converter.Enabled = true;

            btn_trocar.Enabled = true;

            lbl_resultado.Text = "Taxas atualizadas ...";

            if (load)
            {
                lbl_Status.Text = string.Format("Taxas carregadas da internet em {0:F}", DateTime.Now);
            }
            else
            {
                lbl_Status.Text = string.Format("Taxas carregadas da Base de Dados.");
            }
            progressBar1.Value = 100;
        }
Exemple #12
0
        private async void LoadRates()
        {
            bool load;

            //verificar conecção à internet
            lbl_resultado.Text = "A atualizar taxas...";

            var connection = networkService.CheckConnection();

            if (!connection.IsSuccess)
            {
                LoadLocalRates();
                load = false;
            }
            else
            {
                await LoadApiRates();

                load = true;
            }

            if (Rates.Count == 0)
            {
                lbl_resultado.Text = "Não há ligação á Internet" + Environment.NewLine +
                                     "e não forma préviamente carregadas as taxas." + Environment.NewLine +
                                     "Tente novamente mais tarde!";

                lbl_status.Text = "Primeira inicialização deverá ter ligação á Internet";
                return;
            }
            comboBox_origem.DataSource    = Rates;
            comboBox_origem.DisplayMember = "Name";

            //corrige erro microsoft (combobox andam as duas "ligadas" uma à outra)
            comboBox_destino.BindingContext = new BindingContext();

            comboBox_destino.DataSource    = Rates;
            comboBox_destino.DisplayMember = "Name";

            ProgressBar1.Value   = 100;
            btnConverter.Enabled = true;
            lbl_resultado.Text   = "Taxas carregadas....";


            if (load)
            {
                lbl_status.Text = string.Format($"Taxas carregadas da internet a {DateTime.Now.ToString("dddd, dd MMMM yyyy")}");
            }
            else
            {
                lbl_status.Text = string.Format($"Taxas carregadas da Base de Dados");
            }
        }
        /// <summary>
        /// Show/Hide Map
        /// </summary>
        private async void Map()
        {
            Response con = await networkService.CheckConnection();

            if (!con.IsSucess)
            {
                Visible = "Hidden";
            }
            else
            {
                Visible = "Visible";
            }
        }
Exemple #14
0
        private async void LoadPaises()
        {
            bool load;

            var connection = networkService.CheckConnection();

            if (!connection.IsSuccess)
            {
                LoadLocalCountries();
                load = false;
            }
            else
            {
                await LoadApiCountries();

                load = true;
            }



            lbPaises.DataSource = paises;



            progressBarPaises.Value = 100;
            if (load)
            {
                lblStatus.Text = $"Países carregados com sucesso no dia {DateTime.Now.ToShortDateString()}";
            }
            else
            {
                lblStatus.Text = $"Países carregados com sucesso no dia {DateTime.Now.ToShortDateString()} da Base de Dados";
            }

            if (paises == null)
            {
                lblStatus.Text = "Não há conexão a interne e não há informação na base de dados";
            }
        }
Exemple #15
0
        private async void LoadRates()
        {
            bool load;

            lblResultado.Text = "A atualizar taxas...";

            var connection = networkService.CheckConnection();

            if (!connection.IsSuccess)
            {
                LoadLocalrates();
                load = false;
            }
            else
            {
                await LoadApiRates();

                load = true;
            }

            if (Rates.Count == 0)
            {
                lblResultado.Text = "Não há ligação à Internet\ne não foram previamente carregadas as taxas de conversão\nTente mais tarde.";
                return;
            }

            cbOrigem.DataSource    = Rates;
            cbOrigem.DisplayMember = "Name";

            //Correção bug microsoft de bindar as combo Boxes
            cbDestino.BindingContext = new BindingContext();

            cbDestino.DataSource    = Rates;
            cbDestino.DisplayMember = "Name";

            btnConverter.Enabled = true;
            btnTroca.Enabled     = true;

            lblResultado.Text = "Taxas atualizadas";

            if (load)
            {
                lblStatus.Text = string.Format($"Taxas carregadas da Internet em {DateTime.Now:F}");
            }
            else
            {
                lblStatus.Text = string.Format("Taxas carregadas da base de dados.");
            }

            pgStatus.Value = 100;
        }
        private async void LoadCountry()
        {
            var client = new HttpClient();

            var connection = networkService.CheckConnection();

            if (connection.IsSuccess)
            {
                await LoaApiCountry();
            }

            DowloadImage();
            ListBoxCountryList.ItemsSource = Countries;
        }
        public bool SetConnectionStatus()
        {
            NetworkService networkService = new NetworkService();

            var checkconnection = networkService.CheckConnection();

            if (checkconnection.IsSuccess)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        private async void LoadInfo()
        {
            bool load;

            tb_status.Text = "Retrieving countries... ";

            var connection = networkService.CheckConnection(); //verificar a conexão

            if (!connection.IsSucess)                          // se não houver conexão à internet
            {
                //LoadLocalCountries();  //Implementar BASE DE DADOS********
                load = false;
            }
            else      //se houver conexão à internet
            {
                await LoadApiCountries();

                AddLinetxt(tb_status, "Countries sucessfully loaded!");
                tb_status.ScrollToEnd();

                lb_countries.ItemsSource       = paises;
                lb_countries.DisplayMemberPath = "name";

                await SaveFlagASync(paises);

                AddLinetxt(tb_status, "Countries sucessfully saved!");
                tb_status.ScrollToEnd();

                GetContinent();

                //await LoadApiRates();
                await LoadApiLivingCosts();


                load = true;
            }


            if (load) //se o load for true é porque carregou da internet
            {
                AddLinetxt(tb_status, string.Format("Taxas carregadas da Internet em {0:F}", DateTime.Now));
                tb_status.ScrollToEnd();
            }
            else //senão carregou sem internet e teve de carregar da base de dados local
            {
                AddLinetxt(tb_status, string.Format("Taxas carregadas da Base de Dados."));
            }
        }
        /// <summary>
        /// Checks for internet connection and starts program in
        /// online or offline mode according to network conditions.
        /// </summary>
        private async void StartRoutine()
        {
            lblStatus.Content = "Checking connection.";
            var conn = _networkService.CheckConnection();
            Progress <ProgressReportModel> progress = new Progress <ProgressReportModel>();

            progress.ProgressChanged += ReportProgress;

            if (conn.IsSuccess)
            { // Connection Exists
                await LoadApiCountries(progress);

                await FetchFlags(progress);

                btnHideLoading.Visibility = Visibility.Visible;
                await ConvertFlags(progress);

                await Task.Run(() => _dataService.SaveData(progress, _countries));

                pBarStatus.Visibility = Visibility.Hidden;
            }
            else
            { // Connection Unavailable
                MessageBox.Show(conn.Message, "Could not connect");
                lblStatus.Content = "Connection not available." + Environment.NewLine +
                                    "Loading from local database.";
                LoadLocalCountries();
            }

            if (_countries.Count == 0)
            { // if 0, assume no countries were loaded
                lblStatus.Content = "Could not load data." + Environment.NewLine +
                                    "Please try again after" + Environment.NewLine +
                                    "connecting to the internet.";
                return;
            }

            if (gridLoading.Visibility == Visibility.Visible)
            {
                HideLoading();
                gridFinish.Visibility = Visibility.Visible;
                lblFinish.Content     = $"Successfully loaded {_countries.Count} countries.{Environment.NewLine}" +
                                        "Click a country from the list to check it's information.";
                pBarStatus.Visibility = Visibility.Hidden;
            }
        }
Exemple #20
0
        /// <summary>
        /// creates the tables for the various attributes
        /// if there is no internet, run the method that will retrieve the data,
        /// previously recorded, from BD
        /// if there is internet, run the method that will get the data from the API,
        /// and run the method downloadFlags;
        ///  fill the combobox with the names of the countries;
        /// if there is internet I give a message to the user informing him of it,
        /// if there is not, I inform him that it came from BD
        /// </summary>
        private async void LoadCountries()
        {
            DataService.CreateDataCountries();
            DataService.CreateDataCurrencies();
            DataService.CreateDataLanguages();
            DataService.CreateDataTranslations();

            bool load;

            var connection = NetworkService.CheckConnection();

            if (!connection.IsSuccess)
            {
                eSaving = true;
                LoadLocalCountries();
                load = false;
            }

            else
            {
                await LoadApiCountries();
                await DownloadFlags();

                load = true;
            }

            if (Countries.Count == 0)
            {
                InfoToUser();
                return;
            }

            cbCountry.ItemsSource       = Countries;
            cbCountry.DisplayMemberPath = "Name";

            lblResult.Content = "Countries updated!";

            if (load)
            {
                lblStatus.Content = string.Format($"Countries downloaded from the internet in {DateTime.Now}");
            }
            else
            {
                lblStatus.Content = "Countries downloaded from Database.";
            }
        }
Exemple #21
0
        /// <summary>
        /// creates the tables in the database,
        /// put the method, which tests if there is internet, inside the variable
        /// if there is no internet, run the method that will retrieve the data,
        /// previously recorded, from BD
        /// if there is internet, run asynchronously the method that will get the data from the API
        /// </summary>
        private void LoadCovid19Data()
        {
            DataService.CreateDataCovid19();

            var connection = NetworkService.CheckConnection();

            if (!connection.IsSuccess)
            {
                LoadLocalCovid19Data();

                if (Corona.Count == 0)
                {
                    InfoToUser();

                    return;
                }
            }
            else
            {
                Task task = Task.Run(() => LoadApiCountriesCovid19());
            }
        }
Exemple #22
0
        /// <summary>
        /// Main method for loading all countries, wether from the API of the offline database
        /// </summary>
        private async void LoadCountries()
        {
            var connection = networkService.CheckConnection();

            if (connection.IsSuccess)
            {
                await LoadApiCountries();
            }
            else
            {
                await LoadLocalCountries();

                Label_status.Visibility = Visibility.Visible;
                Label_status.Content    = "Countries loaded from the offline database";
            }

            ComboBox_countries.IsEnabled = true;
            Button_details.IsEnabled     = true;

            if (countries == null)
            {
                Label_status.Foreground      = new SolidColorBrush(Colors.Red);
                Label_status.Content         = "The countries couldn't be loaded\nbecause the program didn't finish saving\nbefore closing last time\nit connected to the internet";
                ComboBox_countries.IsEnabled = false;
                Button_details.IsEnabled     = false;
            }
            else if (countries.Count == 0)
            {
                Label_status.Foreground      = new SolidColorBrush(Colors.Red);
                Label_status.Content         = "For the initial setup\nan internet connection is needed\nPlease restart the program\nafter connecting to the internet";
                ComboBox_countries.IsEnabled = false;
                Button_details.IsEnabled     = false;
                return;
            }

            ComboBox_countries.ItemsSource       = countries;
            ComboBox_countries.DisplayMemberPath = "Name";
            ComboBox_countries.SelectedIndex     = 0;
        }
Exemple #23
0
        /// <summary>
        /// Load countries from API or Database in case the download from API doesnt't work, countries will be downloaded from Database
        /// </summary>
        private async void LoadCountriesAPI_DB()
        {
            bool load;

            var connetion = networkService.CheckConnection();

            if (!connetion.IsSuccess)
            {
                LoadLocalCountries();
                lbl_loadingInfo.Content       = "Countries loades from Data Base";
                progressBar.Visibility        = Visibility.Hidden;
                progressPercentage.Visibility = Visibility.Hidden;
                return;
            }
            else
            {
                await LoadCountriesAPI();

                load = true;
            }

            if (countries.Count == 0)
            {
                lbl_loadingInfo.Content = "There is no internet connection" + Environment.NewLine + "please try later";
                return;
            }

            lbl_loadingInfo.Content = "Countries updated";

            if (load)
            {
                lbl_status.Content = string.Format("Counties loaded from API in {0:f}", DateTime.Now);
            }
            else
            {
                lbl_status.Content = string.Format("Counties loaded from Data Base");
            }
        }
Exemple #24
0
        private async void LoadRetes() // await para que o sw continua a trabalhar enquanto carrega os no api deste modo usa-se async com await
        {
            bool load;

            //   lblEscolhe.Text = "Atualizar Taxas...";

            var connection = networkService.CheckConnection();

            if (!connection.IsSuccess)
            {
                LoadLocalRetes();

                load = false;
            }
            else
            {
                await LoaApiRates();

                load = true;
            }

            //no caso o basedados não está preenchido
            if (Rates.Count == 0)
            {
                lblEscolhe.Text = "Não há ligação a Internet" + Environment.NewLine +
                                  "e Não foram prévimente carregadas as taxas." + Environment.NewLine +
                                  "Tenta mais tarde!";

                lblDetalhes.Text = "Primeira Inicialização devera ter ligação a internet";

                return;
            }


            // progressBar1.Value = 0;

            /* var client = new HttpClient(); //cria um http para fazer ligacao de http
             * // client.BaseAddress = new Uri("https://cambiosrafa.azurewebsites.net"); //digo o endereco
             * var response =  await client.GetAsync("/api/Rates"); // digo onde esta o controlador de api
             * var result = await response.Content.ReadAsStringAsync();// carrego o result no formato String para od ou variavel result
             *
             */

            comboBoxOrigem.DataSource    = Rates;
            comboBoxOrigem.DisplayMember = "Name";

            //corrige bug da microsoft
            comboBoxDestino.BindingContext = new BindingContext(); //estou a dizer q combo de origeme difernte do destino, mas na verdade sao iguais

            comboBoxDestino.DataSource    = Rates;
            comboBoxDestino.DisplayMember = "Name";



            lblEscolhe.Text = "Taxas Atualizadas...";

            if (load)
            {
                lblDetalhes.Text = string.Format("Taxas Carregadas da Internet em {0:F}", DateTime.Now);
            }
            else
            {
                lblDetalhes.Text = string.Format("Taxas carregas da Base de Dados");
            }

            progressBar1.Value   = 100;
            btnConverter.Enabled = true;
            btnTroca.Enabled     = true;
        }
        /// <summary>
        /// Load ALL info in API if the connection exists else Load ALL inf in Local DB
        /// </summary>
        /// <returns></returns>
        private async Task LoadCountries()
        {
            LabelStatus.Content = string.Format("Data Upload from internet at {0:F}.", DateTime.Now);
            bool load;
            Progress <ProgressReport> progress = new Progress <ProgressReport>();

            progress.ProgressChanged += ReportProgress;

            var connection = _networkService.CheckConnection();

            if (connection.IsSuccess)
            {
                await LoadApiCountries();
                await LoadApiRates();
                await LoadApiCovid19();

                TreeViewCountries.ItemsSource = await Task.Run(() => GetContinents(Countries));
                await DownloadText(Countries);

                load = true;
            }
            else
            {
                await LoadLocalCountries();
                await LoadLocalRates();
                await LoadLocalInfoCovid19();

                DisplayAllPath();
                TreeViewCountries.ItemsSource = await Task.Run(() => GetContinents(Countries));

                load = false;
            }

            if (Countries.Count == 0)
            {
                LabelInfo.Content = "There is no Internet connection And The Database was not Loaded Correctly. Try later!" + Environment.NewLine + "First startup should have an Internet connection.";
                _savedata         = true;
                return;
            }

            if (Countries.Count > 0 && Countries.Count < 250)
            {
                LabelInfo.Content = $"The local database is incomplete. Please connect to the internet to update the data.{Environment.NewLine}There are only {Countries.Count} countries";
            }


            if (load)
            {
                LabelStatus1.Content = string.Format("Downloading Countries Information (Images) from internet at {0:F}.", DateTime.Now);
                await _dataService.SaveImageAsync(Countries, progress);

                LabelStatus1.Content = string.Format("Downloading Countries Information (Anthem) from internet at {0:F}.", DateTime.Now);
                await _dataService.CountryAnthemAsync(Countries, progress);

                LabelStatus1.Content = string.Format("Saving Countries Information into Database at {0:F}.", DateTime.Now);
                await _dataService.SaveDataCountriesAsync(Countries, progress);

                if (Rates.Count != 0)
                {
                    LabelStatus1.Content = string.Format("Saving Rates Information into Database at {0:F}.", DateTime.Now);
                    await _dataService.SaveDataRatesAsync(Rates, progress);
                }

                if (_rootCovid != null)
                {
                    LabelStatus1.Content = string.Format("Saving Covid19 Information into Database at {0:F}.", DateTime.Now);
                    await _dataService.SaveDataInfoCovidAsync(_rootCovid, progress);
                }
                LabelStatus1.Visibility = Visibility.Hidden;
                LabelStatus.Content     = string.Format("Last Upload from internet at {0:F}.", DateTime.Now);
            }
            else
            {
                var date = Countries.FindLast(x => x.LocalUpdate != null);
                LabelStatus.Content = string.Format("Last Upload from Local Data at {0:F}", date.LocalUpdate);
                _savedata           = true;
            }
            _savedata = true;
        }
Exemple #26
0
        private async void LoadCountries()
        {
            bool load;

            var connection = networkService.CheckConnection();

            if (!connection.IsSuccess)
            {
                LoadLocalCountries();
                load = false;
            }
            else
            {
                await LoadApiCountries();

                load = true;
            }

            if (Countries.Count == 0)
            {
                labelResultado.Text = "Without internet connection" + Environment.NewLine +
                                      "And no preload countries" + Environment.NewLine +
                                      "Try again later!";

                labelStatus.Text = "First initialization with Internet connection";

                return;
            }

            if (!Directory.Exists("Flags"))
            {
                Directory.CreateDirectory("Flags");
            }

            foreach (var donwloadFlag in Countries)
            {
                try
                {
                    string flagName = donwloadFlag.Flag.Split('/')[4].Split('.')[0];
                    var    path     = @"Flags\" + $"{flagName}.svg";

                    string svgFile = "http://restcountries.eu" + $"/data/{flagName}.svg";

                    using (WebClient webClient = new WebClient())
                    {
                        webClient.DownloadFile(svgFile, path);
                    }

                    string flag     = flagName;
                    var    pathFlag = @"Flags\" + $"{flagName}.jpg";

                    var svgDoc = SvgDocument.Open(path);
                    var bitMap = svgDoc.Draw(100, 100);

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

                    if (!File.Exists(pathFlag))
                    {
                        bitMap.Save(pathFlag, ImageFormat.Jpeg);
                    }
                }
                catch
                {
                    continue;
                }
            }

            listBox_Countries.DataSource     = Countries;
            listBox_Countries.DisplayMember  = "Name";
            listBox_Countries.BindingContext = new BindingContext();

            labelResultado.Text = "Updated Countries!";

            if (load)
            {
                labelStatus.Text = string.Format("loaded data from internet at {0:F}", DateTime.Now);
            }
            else
            {
                labelStatus.Text = string.Format("Loaded data from DataBase");
            }
            progressBar1.Value = 100;
        }
Exemple #27
0
        /// <summary>
        /// Tests the Internet Connection.
        /// If successful loads the information from the Web.
        /// If failed, loads the information from the saved Database.
        /// </summary>
        private async void LoadInfoAsync()
        {
            Progress <ProgressReport> progress = new Progress <ProgressReport>();

            progress.ProgressChanged += ReportProgress;

            bool load;

            var connection = networkService.CheckConnection();

            if (!connection.IsSuccess)
            {
                lbl_Status.Content  = "Loading...";
                btnUpdate.IsEnabled = false;
                await LoadLocalCountriesAsync();

                load = false;
                lbl_Status.Content  = "Loading Complete";
                btnUpdate.IsEnabled = true;
            }
            else
            {
                lbl_Status.Content  = "Loading...";
                btnUpdate.IsEnabled = false;
                await LoadApiCountriesAsync();
                await LoadApiRatesAsync();
                await LoadApiWikiTextAsync(Countries, progress);

                await dataService.GetFlagsAsync(Countries, progress);

                await dataService.GetMapsAsync(Countries, progress);

                await dataService.GetAudioAsync(Countries, progress);

                load = true;
                lbl_Status.Content  = "Loading Complete";
                btnUpdate.IsEnabled = true;
            }

            if (Countries.Count == 0)
            {
                lbl_Status.Content = "There is no Connection to the Internet" + Environment.NewLine + "Try again later!";
                lbl_Status.Content = "First initialization must have Internet Connection!";

                return;
            }

            listBoxCountries.ItemsSource = Countries;

            if (load)
            {
                lbl_Status.Content  = "Saving...";
                btnUpdate.IsEnabled = false;
                await dataService.SaveData(Countries, Rates, progress);

                lbl_Status.Content  = "Saving Complete";
                lbl_Status.Content  = "Loaded Successfully" + Environment.NewLine + "          Online";
                btnUpdate.IsEnabled = true;
            }
            else
            {
                lbl_Status.Content = "Loaded Successfully" + Environment.NewLine + "        Offline";
            }
        }