Exemplo n.º 1
0
        public async Task <IActionResult> GetFlag(string country)
        {
            _logger.LogInformation($"Buscando la bandera del pais {country}");

            byte[] bytes;

            try
            {
                var flag = (await RESTCountriesAPI.GetCountriesByNameContainsAsync(country)).Select(x => x.Flag).FirstOrDefault();

                using (WebClient client = new WebClient())
                {
                    client.DownloadFileAsync(new Uri(flag), @"c:\tmp\flag.svg");
                    var svgString = flag;
                    bytes = Encoding.UTF8.GetBytes(flag);
                    var svg = Encoding.UTF8.GetString(bytes);
                }

                return(Ok(bytes));
            }
            catch (Exception e)
            {
                _logger.LogWarning($"No se consiguio ninguna bandera, error {e}");
                return(NotFound());
            }
        }
        public async Task <IActionResult> Add([FromBody] Applicant applicant)
        {
            Boolean        t = false;
            List <Country> c = await RESTCountriesAPI.GetAllCountriesAsync();

            for (int i = 0; i < c.Count; i++)
            {
                if (c[i].Name.ToUpper() == applicant.CountryOfOrigin.ToUpper())
                {
                    t = true;

                    break;
                }
            }
            if (t == true)
            {
                await _repository.AddApplicant(applicant);

                return(CreatedAtAction(nameof(GetById), new { id = applicant.ApplicantId }, applicant));
            }
            else
            {
                return(BadRequest("Please Enter correct Country"));
            }
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Post([FromBody] string country)
        {
            try
            {
                var paisNombre = (await RESTCountriesAPI.GetCountriesByNameContainsAsync(country)).FirstOrDefault();

                Country paisPost = new()
                {
                    Name       = paisNombre.Name,
                    Alpha2Code = paisNombre.Alpha2Code,
                    Alpha3Code = paisNombre.Alpha3Code,
                    Capital    = paisNombre.Capital,
                    NativeName = paisNombre.NativeName,
                    Region     = paisNombre.Region
                };

                _context.Add(paisPost);
                await _context.SaveChangesAsync();

                return(Created("", paisPost));
            }
            catch (Exception e)
            {
                _logger.LogWarning($"No se consiguio ninguna pais {country}, error {e}");
                return(NotFound());
            }
        }
        public async Task <IActionResult> CreateAsync([FromBody] ApplicantDetails applicantDetails)
        {
            Boolean valid   = false;
            var     country = await RESTCountriesAPI.GetCountryByFullNameAsync(applicantDetails.CountryOfOrigin);

            logger.LogInformation(country.Name);
            if (country.Name.ToUpper() == applicantDetails.CountryOfOrigin.ToUpper())
            {
                valid = true;
            }

            if (valid)
            {
                logger.LogInformation("New applicant is added.");
                await _repository.AddApplicantDetailsAsync(applicantDetails);

                logger.LogInformation(nameof(GetById), new { id = applicantDetails.ID }, applicantDetails);
                return(CreatedAtAction(nameof(GetById), new { id = applicantDetails.ID }, applicantDetails));
            }
            else
            {
                logger.LogInformation($"{applicantDetails.CountryOfOrigin} is not a valid country");
                return(BadRequest());
            }
        }
Exemplo n.º 5
0
        public async Task <IActionResult> Index()
        {
            _logger.LogInformation("Obteniendo los paises");

            var listaPaises = (await RESTCountriesAPI.GetAllCountriesAsync()).Select(c => c.Name).ToList();


            return(Ok(listaPaises));
        }
Exemplo n.º 6
0
        public async Task <ActionResult> Index(string countryName)
        {
            var countries = await RESTCountriesAPI.GetAllCountriesAsync();

            if (countries.Any(x => x.Name == countryName))
            {
                return(RedirectToAction(nameof(Search), "Home", new { countryName }));
            }
            return(View());
        }
Exemplo n.º 7
0
        // Filter by country name
        public async Task <List <CountryShort> > GetCountries(string filter)
        {
            List <Country> countries = await RESTCountriesAPI.GetCountriesByNameContainsAsync(filter);

            var list = from item in countries
                       select new CountryShort
            {
                Name       = item.Name,
                Alpha2Code = item.Alpha2Code,
                Flag       = item.Flag
            };

            return(list.ToList());
        }
Exemplo n.º 8
0
        public async Task <IActionResult> Index(string busqueda)
        {
            _logger.LogInformation($"Buscando el pais {busqueda}");

            try
            {
                var pais = (await RESTCountriesAPI.GetCountriesByNameContainsAsync(busqueda)).FirstOrDefault();
                return(Ok(pais));
            }
            catch (Exception e)
            {
                _logger.LogWarning($"No se consiguio ningun pais con la palabra{busqueda}, error {e}");
                return(NotFound());
            }
        }
Exemplo n.º 9
0
        //Осуществляет вывод информации, при смене выбранной страны в ListBoxe-e
        private async void SelectedItem(object sender, EventArgs e)
        {
            label10.Text = listBox1.SelectedIndex.ToString();
            int index1 = Convert.ToInt32(label10.Text);

            List <Country> countries = await RESTCountriesAPI.GetAllCountriesAsync();

            ListBox.ObjectCollection collection = new ListBox.ObjectCollection(listBox1);


            foreach (Country country in countries)
            {
                label1.Text = collection.Count.ToString();
                collection.Add(country);
                //listBox1.DisplayMember = "Name";
                label1.Text = collection.Count.ToString();

                if (collection.IndexOf(country) == index1)
                {
                    Strana.Text    = country.Name; stran = Strana.Text;
                    KodStrani.Text = country.Alpha2Code;
                    Stolica.Text   = country.Capital;
                    try
                    {
                        double plosh    = (double)country.Area;
                        string newplosh = plosh.ToString("#,#", CultureInfo.InvariantCulture);
                        Ploshad.Text = String.Format(CultureInfo.InvariantCulture, "{0:#,#}", newplosh + " км. кв.");
                    }
                    catch (Exception)
                    {
                        Ploshad.Text = String.Format(CultureInfo.InvariantCulture, "Площадь не известна!");
                    }
                    int    Nasel    = (int)country.Population;
                    string newNasel = Nasel.ToString("#,#", CultureInfo.InvariantCulture);
                    Naselenie.Text = String.Format(CultureInfo.InvariantCulture, "{0:#,#}", newNasel + " человек");

                    RegionStrani.Text = country.Region;
                }
            }
            listBox1.Items.Clear(); listBox1.Update();
            foreach (Country country in countries)
            {
                label1.Text = (collection.Count).ToString();
                listBox1.Items.Add(country);
            }
            listBox1.SetSelected(index1, true);
        }
Exemplo n.º 10
0
        //public List<Country> countriesNEW = new List<Country>();   // Использовать для проверки элементов в листе

        private async void textBox1_TextChanged(object sender, EventArgs e)
        {
            // Очищаем список.
            listBox1.Items.Clear();
            //CountOfCountriey = 250;
            label1.Text = listBox1.Items.Count.ToString();
            label1.Refresh();
            valueCountry = textBox1.Text;
            if (string.IsNullOrWhiteSpace(textBox1.Text))
            {
                List <Country> countries = await RESTCountriesAPI.GetAllCountriesAsync();

                ListBox.ObjectCollection collection = new ListBox.ObjectCollection(listBox1);
                foreach (Country country in countries)
                {
                    label1.Text = collection.Count.ToString();
                    collection.Add(country);
                    //listBox1.DisplayMember = "Name";
                    label1.Text = collection.Count.ToString();
                }
            }
        }
Exemplo n.º 11
0
        async void requestRest(string userNameCountry)
        {
            Country restCountry = await RESTCountriesAPI.GetCountryByFullNameAsync(userNameCountry);

            CountryTextBox.Text = ($"Название: {restCountry.Name}\n" +
                                   $"Код: {restCountry.Alpha2Code}\n" +
                                   $"Площадь: {restCountry.Area}\n" +
                                   $"Население: {restCountry.Population}\n" +
                                   $"Столица: {restCountry.Capital}\n" +
                                   $"Регион: {restCountry.Region}");
            DialogResult result = MessageBox.Show(
                "Сохранить страну в базу?",
                "Сохранение",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Information,
                MessageBoxDefaultButton.Button1,
                MessageBoxOptions.DefaultDesktopOnly);

            if (result == DialogResult.Yes)
            {
                WriteinDB(restCountry);
            }
        }
        /*
         * request countries time zones and maintian a dictionry of country and it's time zones
         */
        private async Task <Dictionary <string, IList <string> > > RequestContryZonesAsync()
        {
            Dictionary <string, IList <string> > timeZones;

            //check if it is already cached
            bool timeZoneExist = _memoryCache.TryGetValue("timeZones", out timeZones);

            if (timeZoneExist)
            {
                return(timeZones); //return cached values
            }
            timeZones = new Dictionary <string, IList <string> >();
            foreach (var countryCode in _countryCodes)
            {
                Country result = await RESTCountriesAPI.GetCountryByCodeAsync(countryCode);

                if (!timeZones.ContainsKey(countryCode))
                {
                    timeZones.Add(countryCode, result.Timezones);
                }
            }
            _memoryCache.Set("timeZones", timeZones);
            return(timeZones);
        }
Exemplo n.º 13
0
        private async void Form1_Load(object sender, EventArgs e)
        {
            //Change this path for your own computer
            //string connectionString = @"Server=(localdb)\\mssqllocaldb;Database=testTaskDB;Trusted_Connection=True;MultipleActiveResultSets=true";

            sqlConnection = new SqlConnection(connectionString);
            await sqlConnection.OpenAsync();

            SqlDataReader sqlReader = null;
            SqlCommand    command   = new SqlCommand("SELECT * FROM [Countries]", sqlConnection);

            sqlReader = await command.ExecuteReaderAsync();



            // **************************************************************************************************************** Основной код
            List <Country> countries = await RESTCountriesAPI.GetAllCountriesAsync();

            ListBox.ObjectCollection collection = new ListBox.ObjectCollection(listBox1);
            textBox1.Focus();
            int i = 0;

            foreach (Country country in countries)
            {
                collection.Add(country);
                //listBox1.Items.Add(country);
                //listBox1.DisplayMember = "Name";

                SqlCommand command1 = new SqlCommand("INSERT INTO [Citiess] (Name) VALUES(@Name)", sqlConnection);
                SqlCommand command2 = new SqlCommand("INSERT INTO [Regions] (Name) VALUES(@Name)", sqlConnection);
                SqlCommand command3 = new SqlCommand("INSERT INTO [Countries] (Name, CountryCode, CapitalId, Area, Population, RegionId) VALUES(@Name, @CountryCode,@CapitalID, @Area, @Population, @RegionId)", sqlConnection);
                SqlCommand command4 = new SqlCommand("SELECT Citiess.Name FROM [Countries] INNER JOIN [Citiess] ON Countries.CapitalId = Cities.Id)", sqlConnection);
                SqlCommand command5 = new SqlCommand("INSERT INTO [Countries] (RegionId) VALUES (Countries.Id)", sqlConnection);
                command1.Parameters.AddWithValue("Name", country.Capital);
                command2.Parameters.AddWithValue("Name", country.Region);
                if (country.Name == null)
                {
                    country.Name = "NONE";
                    command3.Parameters.AddWithValue("Name", country.Name);
                }
                else
                {
                    command3.Parameters.AddWithValue("Name", country.Name);
                }

                command3.Parameters.AddWithValue("CountryCode", country.Alpha2Code);
                command3.Parameters.AddWithValue("CapitalId", i++);
                command3.Parameters.AddWithValue("Area", country.Area);
                command3.Parameters.AddWithValue("Population", country.Population);
                command3.Parameters.AddWithValue("RegionId", i++);

                //await command3.ExecuteNonQueryAsync();
                //await command4.ExecuteNonQueryAsync();
                //await command5.ExecuteNonQueryAsync();

                //await command5.ExecuteNonQueryAsync();
                //await command1.ExecuteNonQueryAsync();
                //await command2.ExecuteNonQueryAsync();
            }
            if (sqlConnection != null && sqlConnection.State != ConnectionState.Closed)
            {
                sqlConnection.Close();
            }
            CountOfCountriey = collection.Count;
        }
Exemplo n.º 14
0
        //Осуществляется проверка на введенные данные и попытка найти заданную страну
        public async void TRYING()
        {
RepeatFindCountry:
            if (CountOfCountriey == 250)
            {
                //List<Country> countries = await RESTCountriesAPI.GetAllCountriesAsync();
                //ListBox.ObjectCollection collection = new ListBox.ObjectCollection(listBox1);
                try
                {
                    if (textBox1.Text != "")
                    {
                        //valueCountry = textBox1.Text;
                        listBox1.Items.Clear();
                        List <Country> countries = await RESTCountriesAPI.GetCountriesByNameContainsAsync(textBox1.Text);

                        ListBox.ObjectCollection collection = new ListBox.ObjectCollection(listBox1);

                        foreach (Country country in countries)
                        {
                            collection.Add(country);
                            //listBox1.DisplayMember = "Name";
                            label1.Text = collection.Count.ToString();

                            //Передача данных по стране
                            Strana.Text    = country.Name; stran = Strana.Text;
                            KodStrani.Text = country.Alpha2Code;
                            Stolica.Text   = country.Capital;

                            double plosh    = (double)country.Area;
                            string newplosh = plosh.ToString("#,#", CultureInfo.InvariantCulture);
                            Ploshad.Text = String.Format(CultureInfo.InvariantCulture, "{0:#,#}", newplosh + " км. кв.");

                            int    Nasel    = (int)country.Population;
                            string newNasel = Nasel.ToString("#,#", CultureInfo.InvariantCulture);
                            Naselenie.Text = String.Format(CultureInfo.InvariantCulture, "{0:#,#}", newNasel + " человек");

                            RegionStrani.Text = country.Region;
                        }
                        listBox1.Items.Clear(); listBox1.Update();
                        foreach (Country country in countries)
                        {
                            label1.Text = (collection.Count).ToString();
                            listBox1.Items.Add(country);
                        }
                        listBox1.SetSelected(0, true);
                    }
                    else
                    {
                        //List<Country> countries = await RESTCountriesAPI.GetAllCountriesAsync();
                        //ListBox.ObjectCollection collection = new ListBox.ObjectCollection(listBox1);
                        //MessageBox.Show("Введите страну!", "Ошибка", MessageBoxButtons.OK);
                    }
                }
                catch
                {
                    Strana.ResetText();
                    KodStrani.ResetText();
                    Stolica.ResetText();
                    Ploshad.ResetText();
                    Naselenie.ResetText();
                    RegionStrani.ResetText();

                    MessageBox.Show("Cтрана не найдена. Проверьте правильность введенных данных!", "Ошибка", MessageBoxButtons.OK);
                    textBox1.Clear();
                    goto RepeatFindCountry;
                }
            }
            //else CountOfCountriey = 251;
        }
Exemplo n.º 15
0
        private bool IsValidCountryCategory(UpdateApplicantModel applicant, string homeCountry)
        {
            var validCountries = RESTCountriesAPI.GetAllCountriesAsync().Result;

            return(validCountries.Exists(x => x.Name == homeCountry));
        }
Exemplo n.º 16
0
        public async Task <ActionResult> Search(string countryName)
        {
            var c = await RESTCountriesAPI.GetCountryByFullNameAsync(countryName);

            return(View(c));
        }