Пример #1
0
        public void GennerateCountry()
        {
            Bogus.Faker <CountryEntity> country = new Bogus.Faker <CountryEntity>()
                                                  .StrictMode(true)
                                                  .RuleFor(id => id.Id, f => Guid.NewGuid())
                                                  .RuleFor(zipcode => zipcode.ZipCode, f => f.Address.ZipCode())
                                                  .RuleFor(city => city.City, f => f.Address.City())
                                                  .RuleFor(streetadd => streetadd.StreetAddress, f => f.Address.StreetAddress())
                                                  .RuleFor(citypre => citypre.CityPrefix, f => f.Address.CityPrefix())
                                                  .RuleFor(citysuf => citysuf.CitySuffix, f => f.Address.CitySuffix())
                                                  .RuleFor(strname => strname.StreetName, f => f.Address.StreetName())
                                                  .RuleFor(building => building.BuildingNumber, f => f.Address.BuildingNumber())
                                                  .RuleFor(strsuffix => strsuffix.StreetSuffix, f => f.Address.StreetSuffix())
                                                  .RuleFor(ct => ct.Country, f => f.Address.Country())
                                                  .RuleFor(fulladd => fulladd.FullAddress, f => f.Address.FullAddress())
                                                  .RuleFor(code => code.CountryCode, f => f.Address.CountryCode())
                                                  .RuleFor(state => state.State, f => f.Address.State())
                                                  .RuleFor(stateAbb => stateAbb.StateAbbreviation, f => f.Address.StateAbbr())
                                                  .RuleFor(latitube => latitube.Latitude, f => f.Address.Latitude().ToString())
                                                  .RuleFor(longitube => longitube.Longitude, f => f.Address.Longitude().ToString())
                                                  .RuleFor(dir => dir.Direction, f => f.Address.Direction())
                                                  .RuleFor(card => card.CardinalDirection, f => f.Address.CardinalDirection())
                                                  .RuleFor(ord => ord.OrdinalDirection, f => f.Address.OrdinalDirection())
                                                  .RuleFor(date => date.CreateDate, f => DateTime.Now);
            CountryEntity result = country.Generate();

            db.Set <CountryEntity>().Add(result);
        }
Пример #2
0
        public async Task <IActionResult> Edit(int id, CountryEntity countryEntity)
        {
            if (id != countryEntity.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                countryEntity.Name = countryEntity.Name.ToUpper();
                _context.Update(countryEntity);

                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
                catch (Exception ex)
                {
                    if (ex.InnerException.Message.Contains("duplicate"))
                    {
                        ModelState.AddModelError(string.Empty, "Already exists a country wiht the same name.");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, ex.Message);
                    }
                }
            }
            return(View(countryEntity));
        }
        // GET: Categories

        public string getLstContry()
        {
            List <CountryEntity> lst = new List <CountryEntity>();

            _conn.Open();

            //---
            MySqlCommand cmd = new MySqlCommand("GETCOUNTTRY", _conn.conn);

            cmd.CommandType = CommandType.StoredProcedure;

            using (var cursor = cmd.ExecuteReader())
            {
                while (cursor.Read())
                {
                    CountryEntity item = new CountryEntity(
                        Convert.ToString(cursor["COUNTRY_ID"]),
                        Convert.ToString(cursor["COUNTRY_CODE"]),
                        Convert.ToString(cursor["COUNTRY_NAME"]));

                    lst.Add(item);
                }
            }
            _conn.Close();

            return(JsonConvert.SerializeObject(lst));
        }
Пример #4
0
        public ServiceMessage Delete(string countryName)
        {
            string message;
            bool   success = true;

            try
            {
                CountryEntity countryEntity = unitOfWork.Countries.Get(countryName);
                if (countryEntity != null)
                {
                    unitOfWork.Countries.Remove(countryEntity);
                    unitOfWork.Commit();

                    message = "Country deleted";
                }
                else
                {
                    message = "Country with such name doesn't exist";
                    success = false;
                }
            }
            catch (Exception ex)
            {
                message = ExceptionMessageBuilder.BuildMessage(ex);
                success = false;
            }

            return(new ServiceMessage(message, success));
        }
Пример #5
0
        public async Task UpdateCountry(CountryDto pCountryDto)
        {
            CountryEntity lCountryEntity = await this._countryRepository.GetById(pCountryDto.Id);

            Mapping.Mapper.Map <CountryDto, CountryEntity>(pCountryDto, lCountryEntity);
            await this._countryRepository.Update(lCountryEntity);
        }
Пример #6
0
        public ServiceMessage Update(CountryEditDTO countryEditDTO)
        {
            string message;
            bool   success = true;

            try
            {
                CountryEntity countryEntity = unitOfWork
                                              .Countries
                                              .GetAll()
                                              .SingleOrDefault(country => country.Name == countryEditDTO.OldCountryName);
                if (countryEntity != null)
                {
                    countryEntity.Name = countryEditDTO.NewCountryName;
                    unitOfWork.Commit();

                    message = "Country was renamed";
                }
                else
                {
                    message = "Country with such name doesn't exist";
                    success = false;
                }
            }
            catch (Exception ex)
            {
                message = ExceptionMessageBuilder.BuildMessage(ex);
                success = false;
            }

            return(new ServiceMessage(message, success));
        }
Пример #7
0
        public Country(CountryEntity CountryEntity) : base(CountryEntity)
        {
            if (CountryEntity.CityEntities != null)
            {
                this.Cities = new HashSet <City>();
                foreach (CityEntity CityEntity in CountryEntity.CityEntities)
                {
                    CityEntity.CountryId = CountryEntity.Id;
                    this.Cities.Add(new City(CityEntity));
                }
            }

            if (CountryEntity.ShipmentDetailEntities != null)
            {
                this.ShipmentDetails = new HashSet <ShipmentDetail>();
                foreach (ShipmentDetailEntity ShipmentDetailEntity in CountryEntity.ShipmentDetailEntities)
                {
                    ShipmentDetailEntity.CountryId = CountryEntity.Id;
                    this.ShipmentDetails.Add(new ShipmentDetail(ShipmentDetailEntity));
                }
            }

            if (CountryEntity.TaxEntities != null)
            {
                this.Taxes = new HashSet <Tax>();
                foreach (TaxEntity TaxEntity in CountryEntity.TaxEntities)
                {
                    TaxEntity.CountryId = CountryEntity.Id;
                    this.Taxes.Add(new Tax(TaxEntity));
                }
            }
        }
Пример #8
0
        public JsonResultEntity Create([FromBody] CountryEntity countryEntity)
        {
            CountryBL        countryBL = new CountryBL();
            JsonResultEntity response  = new JsonResultEntity();

            try
            {
                var result = countryBL.Create(countryEntity);

                if (result.HasWarning())
                {
                    response.Message = String.Join(",", result.Warning);
                    return(response);
                }

                response.Success = true;
                response.Data    = result.Value;
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                LoggerHelper.Error(ex);
            }

            return(response);
        }
Пример #9
0
        public bool Update(CountryEntity entity)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("update Countries ");
            strSql.Append(" set Country=@Country, Language=@Language ");
            strSql.Append(" where ID=@ID ");
            Database db = DatabaseFactory.CreateDatabase();

            using (DbCommand dbCommand = db.GetSqlStringCommand(strSql.ToString()))
            {
                try
                {
                    db.AddInParameter(dbCommand, "Country", DbType.String, entity.Country);
                    db.AddInParameter(dbCommand, "Language", DbType.Int32, entity.Language);
                    db.AddInParameter(dbCommand, "ID", DbType.Int32, entity.ID);
                    return(db.ExecuteNonQuery(dbCommand) > 0);
                }
                catch (Exception ex)
                {
                    new log4netProvider().LogSQL(strSql.ToString(), dbCommand.Parameters, ex);
                    return(false);
                }
            }
        }
Пример #10
0
        public CountryEntity Get(int entityId)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append(" select Country, Language ");
            strSql.Append(" from Countries ");
            strSql.Append(" where ID=@ID ");
            Database db = DatabaseFactory.CreateDatabase();

            using (DbCommand dbCommand = db.GetSqlStringCommand(strSql.ToString()))
            {
                try
                {
                    CountryEntity entity = null;
                    db.AddInParameter(dbCommand, "ID", DbType.Int32, entityId);

                    IDataReader reader = db.ExecuteReader(dbCommand);
                    if (reader.Read())
                    {
                        entity = new CountryEntity(reader);
                        reader.Close();
                        return(entity);
                    }
                    return(null);
                }
                catch (Exception ex)
                {
                    new log4netProvider().LogSQL(strSql.ToString(), dbCommand.Parameters, ex);
                    return(null);
                }
            }
        }
Пример #11
0
        public int Insert(CountryEntity entity)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("insert into Countries(");
            strSql.Append(" Country, Language )");
            strSql.Append(" values (");
            strSql.Append("@Country, @Language)");
            strSql.Append(";select ISNULL( SCOPE_IDENTITY(),0);");
            Database db = DatabaseFactory.CreateDatabase();

            using (DbCommand dbCommand = db.GetSqlStringCommand(strSql.ToString()))
            {
                try
                {
                    db.AddInParameter(dbCommand, "Country", DbType.String, entity.Country);
                    db.AddInParameter(dbCommand, "Language", DbType.Int32, entity.Language);
                    int    result;
                    object obj = db.ExecuteScalar(dbCommand);
                    if (!int.TryParse(obj.ToString(), out result))
                    {
                        return(0);
                    }
                    return(result);
                }
                catch (Exception ex)
                {
                    new log4netProvider().LogSQL(strSql.ToString(), dbCommand.Parameters, ex);
                    return(0);
                }
            }
        }
Пример #12
0
        private static List <PersonEntity> GeneratePeople()
        {
            List <PersonEntity> retval = new List <PersonEntity>();

            CountryEntity aus = DBCountries.Find(c => c.Country_Code == "AUS");

            PersonEntity person1 = new PersonEntity()
            {
                Person_Id        = Guid.NewGuid(),
                Person_FirstName = "Bruce",
                Person_LastName  = "Wayne",
                Person_Country   = aus
            };

            CountryEntity nz = DBCountries.Find(c => c.Country_Code == "NZL");

            PersonEntity person2 = new PersonEntity()
            {
                Person_Id        = Guid.NewGuid(),
                Person_FirstName = "Clark",
                Person_LastName  = "Kent",
                Person_Country   = nz
            };

            retval.Add(person1);
            retval.Add(person2);

            return(retval);
        }
Пример #13
0
        private static void TestingFactbook18CosmosDbContext()
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("secrets.json", optional: true, reloadOnChange: true);
            var    configuration              = builder.Build();
            string connectionString           = configuration["CosmosDB"];
            Factbook18CosmosDbContext context = new Factbook18CosmosDbContext(connectionString);

            Console.WriteLine("Context created ...");

            //Console.WriteLine("Listing countries.........");
            //foreach (var item in context.Countries)
            //    Console.WriteLine(item.Name);

            //Console.WriteLine("Loading coparable fields...");
            //foreach (var item in context.ComparableFields)
            //    Console.WriteLine(item.FieldName);

            //Console.WriteLine("Loading notes and defs...");
            //foreach (var item in context.NotesAndDefs)
            //    Console.WriteLine(item.FieldName);

            Console.WriteLine("Testing GetCountryDetails function ...");
            string        CountryCode = "SV";
            CountryEntity c           = context.GetCountryDetails(CountryCode);

            if (c != null)
            {
                Console.WriteLine(c.CountryData[0].Children[0].Value);
            }
        }
Пример #14
0
        private static List <CountryEntity> GenerateCountries()
        {
            List <CountryEntity> retval = new List <CountryEntity>();

            CountryEntity aus = new CountryEntity()
            {
                Country_Id   = Guid.NewGuid(),
                Country_Code = "AUS",
                Country_Name = "Australia"
            };

            CountryEntity nz = new CountryEntity()
            {
                Country_Id   = Guid.NewGuid(),
                Country_Code = "NZL",
                Country_Name = "New Zealand"
            };

            CountryEntity sng = new CountryEntity()
            {
                Country_Id   = Guid.NewGuid(),
                Country_Code = "SNG",
                Country_Name = "Singapore"
            };

            retval.Add(aus);
            retval.Add(nz);
            retval.Add(sng);

            return(retval);
        }
Пример #15
0
        public async Task <IActionResult> Create(CountryEntity countryEntity)
        {
            if (ModelState.IsValid)
            {
                _context.Add(countryEntity);

                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }

                catch (Exception ex)
                {
                    if (ex.InnerException.Message.Contains("duplicate"))
                    {
                        ModelState.AddModelError(string.Empty, $"Already exists the Country:{countryEntity.Name}");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, ex.InnerException.Message);
                    }
                }
            }
            return(View(countryEntity));
        }
Пример #16
0
        public async Task GetStateProvincesList_SortedAlphabetically()
        {
            var country = new CountryEntity {
                era_countrycode = "c1", era_name = "c_c", era_countryid = "1", era_isocountrycode = "c1"
            };
            IEnumerable <StateProvinceEntity> stateProvinces = new[]
            {
                new StateProvinceEntity {
                    era_code = "s1", era_name = "s_a", era_provinceterritoriesid = "1", _era_relatedcountry_value = country.era_countryid
                },
                new StateProvinceEntity {
                    era_code = "s1", era_name = "s_c", era_provinceterritoriesid = "2", _era_relatedcountry_value = country.era_countryid
                },
                new StateProvinceEntity {
                    era_code = "s1", era_name = "s_b", era_provinceterritoriesid = "3", _era_relatedcountry_value = country.era_countryid
                },
            };
            var mockedListsRepo = new Mock <IListsRepository>();

            mockedListsRepo.Setup(m => m.GetCountriesAsync()).Returns(Task.FromResult(new[] { country }.AsEnumerable()));
            mockedListsRepo.Setup(m => m.GetStateProvincesAsync()).Returns(Task.FromResult(stateProvinces));
            var provider = new ListsProvider(mockedListsRepo.Object);

            var result = await provider.GetStateProvincesAsync(country.era_isocountrycode);

            Assert.Equal(stateProvinces.Select(c => c.era_name).OrderBy(c => c), result.Select(c => c.Name));
        }
        public string CreateNewCountry(CountryEntity ce)
        {
            var countryCodeAlreadyExists = CountryEntityCheck.DoesCountryCodeAlreadyExist(DataContext, ce.CountryCode);

            if (countryCodeAlreadyExists)
            {
                return(CountryEntityCheck.CountryCodeAlreadyExists);
            }

            var dwAlreadyExists = CountryEntityCheck.DoesCountryDwAlreadyExist(DataContext, ce.CountryDw, ce.Id);

            if (dwAlreadyExists)
            {
                return(CountryEntityCheck.DwCodeAlreadyExists);
            }
            var newCountryEntity = new COUNTRy
            {
                active              = true,
                country1            = ce.CountryCode,
                country_dw          = ce.CountryDw,
                country_description = ce.CountryName
            };

            DataContext.COUNTRies.InsertOnSubmit(newCountryEntity);

            var returned = SubmitDbChanges();

            return(returned);
        }
Пример #18
0
        public async Task GetJurisdictionsList_FilterByMultipleTypes_JurisdictionsOfTypes()
        {
            var country = new CountryEntity {
                era_countrycode = "c1", era_name = "c_c", era_countryid = "1", era_isocountrycode = "c1"
            };
            var stateProvince = new StateProvinceEntity {
                era_code = "s1", era_name = "s_a", era_provinceterritoriesid = "1_1", _era_relatedcountry_value = country.era_countryid
            };
            IEnumerable <JurisdictionEntity> jurisdictions = new[]
            {
                new JurisdictionEntity {
                    era_jurisdictionid = "j1", era_jurisdictionname = "j2", era_type = JurisdictionType.City.GetHashCode().ToString(), _era_relatedprovincestate_value = stateProvince.era_provinceterritoriesid
                },
                new JurisdictionEntity {
                    era_jurisdictionid = "j2", era_jurisdictionname = "j3", era_type = JurisdictionType.District.GetHashCode().ToString(), _era_relatedprovincestate_value = stateProvince.era_provinceterritoriesid
                },
                new JurisdictionEntity {
                    era_jurisdictionid = "j3", era_jurisdictionname = "j1", era_type = JurisdictionType.DistrictMunicipality.GetHashCode().ToString(), _era_relatedprovincestate_value = stateProvince.era_provinceterritoriesid
                },
            };
            var mockedListsRepo = new Mock <IListsRepository>();

            mockedListsRepo.Setup(m => m.GetCountriesAsync()).Returns(Task.FromResult(new[] { country }.AsEnumerable()));
            mockedListsRepo.Setup(m => m.GetStateProvincesAsync()).Returns(Task.FromResult(new[] { stateProvince }.AsEnumerable()));
            mockedListsRepo.Setup(m => m.GetJurisdictionsAsync()).Returns(Task.FromResult(jurisdictions));
            var provider = new ListsProvider(mockedListsRepo.Object);

            var result = await provider.GetJurisdictionsAsync(new[] { JurisdictionType.City, JurisdictionType.District }, stateProvince.era_code, country.era_countrycode);

            Assert.Equal(2, result.Count());
        }
Пример #19
0
        public async Task <CountryDto> GetCountryById(int id)
        {
            CountryEntity lCountryEntity = await this._countryRepository.GetById(id);

            CountryDto lReturn = Mapping.Mapper.Map <CountryDto>(lCountryEntity);

            return(lReturn);
        }
Пример #20
0
        public async Task <CountryEntity> Add(CountryEntity pEntity)
        {
            await this.dbContext.Countries.AddAsync(pEntity);

            await this.dbContext.SaveChangesAsync();

            return(pEntity);
        }
Пример #21
0
        public async Task UpdateAsync(CountryEntity country)
        {
            using SqlConnection db = new SqlConnection(_dalSettings.ConnectionString);

            await db.ExecuteAsync(
                "UpdateCountry",
                country,
                commandType : CommandType.StoredProcedure);
        }
Пример #22
0
        public async Task <int> AddAsync(CountryEntity country)
        {
            using SqlConnection db = new SqlConnection(_dalSettings.ConnectionString);

            return(await db.QuerySingleOrDefaultAsync <int>(
                       "AddCountry",
                       new { name = country.Name },
                       commandType : CommandType.StoredProcedure));
        }
Пример #23
0
        public async Task <bool> CheckDuplicateAsync(CountryEntity country)
        {
            using SqlConnection db = new SqlConnection(_dalSettings.ConnectionString);

            return(await db.ExecuteScalarAsync <bool>(
                       "CheckCountryDuplicate",
                       new { name = country.Name },
                       commandType : CommandType.StoredProcedure));
        }
Пример #24
0
 internal static Country Map(this CountryEntity entity)
 {
     return(new Country
     {
         Id = entity.id,
         Name = entity.displayName,
         IsoCode = entity.isoCode,
     });
 }
Пример #25
0
        public static void WriteToDB(IList <CitiesImportModel> myList, string typeOfCity)
        {
            var countryCapitalQuery = (from s in myList
                                       where s.Capital.Equals(typeOfCity)
                                       orderby s.Country ascending
                                       select s);

            using (var dbContext = new CityContext())
            {
                dbContext.Database.Connection.Close();
            }
            var countryGroups = from city in countryCapitalQuery
                                group city by new
            {
                city.Country,
                city.ISO2,
                city.ISO3
            }
            into countryGroup
            orderby countryGroup.Key.Country
            select countryGroup;

            using (var db = new CityContext())
            {
                foreach (var country in countryGroups)
                {
                    var countryName   = country.Key.Country;
                    var ISO2          = country.Key.ISO2;
                    var ISO3          = country.Key.ISO3;
                    var CountryEntity = new CountryEntity
                    {
                        Name = countryName,
                        ISO2 = ISO2,
                        ISO3 = ISO3
                    };
                    db.Countries.Add(CountryEntity);
                    db.SaveChanges();
                    int id = CountryEntity.CountryID;
                    foreach (var city in country)
                    {
                        var CityEntity = new CityEntity
                        {
                            City_name  = city.City_name,
                            Admin_name = city.Admin_name,
                            City_ascii = city.City_ascii,
                            Lat        = city.Lat,
                            Lng        = city.Lng,
                            Capital    = city.Capital,
                            CountryId  = id,
                            Population = city.Population
                        };
                        db.Cities.Add(CityEntity);
                        db.SaveChanges();
                    }
                }
            }
        }
Пример #26
0
        public async Task UpdateAsync(CountryEntity country)
        {
            using SqlConnection db = new SqlConnection(_connectionSettings.GetConnectionString("AirportDatabase"));

            await db.ExecuteAsync(
                "UpdateCountry",
                country,
                commandType : CommandType.StoredProcedure);
        }
Пример #27
0
 /// <summary> setups the sync logic for member _country</summary>
 /// <param name="relatedEntity">Instance to set as the related entity of type entityType</param>
 private void SetupSyncCountry(IEntity2 relatedEntity)
 {
     if (_country != relatedEntity)
     {
         DesetupSyncCountry(true, true);
         _country = (CountryEntity)relatedEntity;
         base.PerformSetupSyncRelatedEntity(_country, new PropertyChangedEventHandler(OnCountryPropertyChanged), "Country", IpcountryEntity.Relations.CountryEntityUsingCountryId, true, new string[] {  });
     }
 }
Пример #28
0
        public List <T> ParsingResult <T, T2>(List <T2> data) where T : Entity where T2 : class
        {
            var parsedData = data as List <CountryDto>;

            if (parsedData == null)
            {
                throw new System.Exception("Can't parse data");
            }

            var countries = new List <CountryEntity>();

            using (var context = new CountryContext())
            {
                var regions      = parsedData.Select(x => x.Region.Value);
                var incomeLevels = parsedData.Select(x => x.IncomeLevel.Value);
                var adminregions = parsedData.Select(x => x.Adminregion.Value);
                var lendingTypes = parsedData.Select(x => x.LendingType.Value);

                var values = regions.Concat(incomeLevels.Concat(adminregions.Concat(lendingTypes))).Distinct().ToList();

                var allRegions = context.Regions
                                 .Where(x => values.Contains(x.Value))
                                 .ToList();

                foreach (var country in countries)
                {
                    var adminregion = allRegions
                                      .FirstOrDefault(x => x.Value == country.Adminregion.Value);

                    var incomeLevel = allRegions
                                      .FirstOrDefault(x => x.Value == country.IncomeLevel.Value);

                    var region = allRegions
                                 .FirstOrDefault(x => x.Value == country.Region.Value);

                    var lendingType = allRegions
                                      .FirstOrDefault(x => x.Value == country.LendingType.Value);

                    var newCountry = new CountryEntity
                    {
                        Adminregion = adminregion,
                        IncomeLevel = incomeLevel,
                        Region      = region,
                        LendingType = lendingType,
                        CapitalCity = country.CapitalCity,
                        Iso2Code    = country.Iso2Code,
                        Latitude    = country.Latitude,
                        Longitude   = country.Longitude,
                        Name        = country.Name
                    };

                    countries.Add(newCountry);
                }
            }

            return(countries as List <T>);
        }
Пример #29
0
        public CountryEntity Create(CountryEntity countryEntity)
        {
            var query = @"INSERT INTO ""Country""(""CountryName"",""IsoCode"",""ContinentName"",""ContinentCode"",""GeonameID"") VALUES(@CountryName,@IsoCode,@ContinentName,@ContinentCode,@GeonameID) RETURNING ""ID"";";

            int id = DbConnection.Query <int>(query, countryEntity).Single();

            countryEntity.ID = id;
            return(countryEntity);
        }
Пример #30
0
        public Country GetCountry()
        {
            CountryEntity countryEntity = countryService.GetCountryEntity();
            Country       country       = new Country()
            {
                Name = countryEntity.Name + Postfix
            };

            return(country);
        }