public async Task <IActionResult> Edit(long id, [Bind("ID,Name,CountryId")] Models.City city) { if (id != city.ID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(city); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CityExists(city.ID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["CountryId"] = new SelectList(_context.countries, "ID", "Name", city.CountryId); return(View(city)); }
public ActionResult DeleteConfirmed(int id) { Models.City city = db.Cities.Find(id); db.Cities.Remove(city); db.SaveChanges(); return(RedirectToAction("Index")); }
private void CreateServiceFromInputData() { Service.name = TextBoxName.Text; Service.description = TextBoxDescription.Text; Service.slogan = TextBoxSlogan.Text; Service.typeService = TextBoxTypeService.Text; Service.workingHours = TextBoxWorkingHours.Text; string maximunCost = TextBoxMaximumCost.Text; try { if (!String.IsNullOrEmpty(maximunCost)) { Service.maximumCost = float.Parse(maximunCost, CultureInfo.InvariantCulture.NumberFormat); } string minimalCost = TextBoxMinimalCost.Text; if (!String.IsNullOrEmpty(minimalCost)) { Service.minimalCost = float.Parse(minimalCost, CultureInfo.InvariantCulture.NumberFormat); } } catch (FormatException formatException) { TelegramBot.SendToTelegram(formatException); LogException.Log(this, formatException); } Service.idMemberATE = Login.tokenAccount.idMemberATE; if (ComboBoxCity.SelectedItem != null) { string optionCity = ((ComboBoxItem)ComboBoxCity.SelectedItem).Content.ToString(); citySelection = cities.Find(City => City.name.Equals(optionCity)); Service.idCity = citySelection.idCity; } }
/// <summary> /// Copy from legacy to new record For the table of HET_City /// </summary> /// <param name="dbContext"></param> /// <param name="oldObject"></param> /// <param name="city"></param> static private void CopyToInstance(PerformContext performContext, DbAppContext dbContext, HETSAPI.Import.HETS_City oldObject, ref Models.City city, string systemId) { bool isNew = false; if (city == null) { isNew = true; city = new Models.City(); } if (dbContext.Cities.Where(x => x.Name.ToUpper() == oldObject.Name.ToUpper()).Count() == 0) { isNew = true; city.Name = oldObject.Name.Trim(); city.Id = dbContext.Cities.Max(x => x.Id) + 1; //oldObject.Seq_Num; city.CreateTimestamp = DateTime.UtcNow; city.CreateUserid = systemId; } if (isNew) { dbContext.Cities.Add(city); //Adding the city to the database table of HET_CITY } try { dbContext.SaveChangesForImport(); } catch (Exception e) { performContext.WriteLine("*** ERROR With add or update City ***"); performContext.WriteLine(e.ToString()); } }
// gets appartment data and predicts a price public async Task <string> predict(int inCityID, int inRoomsNumber, int inSizeInMeters, bool inIsThereElivator, bool inFurnitureInculded, bool inIsRenovated) { // Get the city in which the apartment is located Models.City currCity = _context.City.Where(c => c.ID == inCityID).First(); // create an ApartmentData object from the given parameters ML.ApartmentData newExample = new ML.ApartmentData { cityID = inCityID, cityAvarageSalary = currCity.avarageSalary, region = (int)currCity.region, cityGraduatesPercent = currCity.GraduatesPercents, RoomsNumber = inRoomsNumber, sizeInMeters = inSizeInMeters, isThereElivator = inIsThereElivator, furnitureInculded = inFurnitureInculded, isRenovated = inIsRenovated }; //Read the model from the zip file var model = await PredictionModel.ReadAsync <ApartmentData, AppartmentPricePrediction>(ModelBuilder.MODEL_PATH); // Make the prediction ML.AppartmentPricePrediction prediction = model.Predict(newExample); return(((int)prediction.price).ToString()); }
public void CityRead() { Booking.Models.City c = new Models.City(9999, "Test"); Booking.DB.DbCity dbCity = new DB.DbCity(); dbCity.Delete(9999); dbCity.Create(c); Assert.IsNotNull(dbCity.Get(9999)); }
public static DAL.City convertToDB(Models.City city) { return(new DAL.City() { allCountValid = city.allCountValid, areaKod = city.areaKod, cityName = city.cityName, nowCountValid = city.nowCountValid, id = city.id }); }
public ActionResult Edit([Bind(Include = "CityId,Name,YearFounded,Population,CountryId")] Models.City city) { if (ModelState.IsValid) { db.Entry(city).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.CountryId = new SelectList(db.Countries, "CountryId", "Name", city.CountryId); return(View(city)); }
public async Task <IActionResult> Create([Bind("ID,Name,CountryId")] Models.City city) { if (ModelState.IsValid) { _context.Add(city); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["CountryId"] = new SelectList(_context.countries, "ID", "Name", city.CountryId); return(View(city)); }
//public async Task<ActionResult<City>> SaveCity([FromBody]dynamic dto) public async Task <ActionResult <City> > SaveCity([FromBody] CityDTO _CityS) { City _City = _CityS; // City _City = new City(); // City _CityS = new City(); //JsonConvert.DeserializeObject<CityDTO>(dto.ToString()); if (_CityS != null) //if (_City != null) { try { //_City = JsonConvert.DeserializeObject<CityDTO>(dto.ToString()); City _listProduct = new City(); string baseadress = config.Value.urlbase; HttpClient _client = new HttpClient(); _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + HttpContext.Session.GetString("token")); var result = await _client.GetAsync(baseadress + "api/City/GetCityById/" + _City.Id); string valorrespuesta = ""; if (result.IsSuccessStatusCode) { valorrespuesta = await(result.Content.ReadAsStringAsync()); _City = JsonConvert.DeserializeObject <CityDTO>(valorrespuesta); } if (_City == null) { _City = new Models.City(); } if (_City.Id == 0) { var insertresult = await Insert(_CityS); } else { var updateresult = await Update(_City.Id, _CityS); } } catch (Exception ex) { _logger.LogError($"Ocurrio un error: { ex.ToString() }"); throw ex; } } else { return(BadRequest("No llego correctamente el modelo!")); } return(Json(_City)); }
// GET: Cities/Delete/5 public ActionResult Delete(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Models.City city = db.Cities.Find(id); if (city == null) { return(HttpNotFound()); } return(View(city)); }
// GET: Cities/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Models.City city = db.Cities.Find(id); if (city == null) { return(HttpNotFound()); } ViewBag.CountryId = new SelectList(db.Countries, "CountryId", "Name", city.CountryId); return(View(city)); }
public City(DataTypes.WorldData.City c) { AbsolutePosition = c.Position; RelativePosition = c.Position; State = c.State; clearedDialogue = new DialogModel(c.ClearedDialogAsset); unlockedDialogue = new DialogModel(c.UnlockedDialogAsset); newlyUnlockedDialogue = new DialogModel(c.NewlyUnlockedDialogAsset); successDialogue = new DialogModel(c.SuccessAsset); Name = c.Name; Unlocked = new Models.City[] { null, null, null }; Data = c; }
public void CityCreate() { Booking.Models.City c = new Models.City(9999, "Test"); Booking.DB.DbCity dbCity = new DB.DbCity(); dbCity.Delete(9999); Assert.IsNull(dbCity.Get(9999)); dbCity.Create(c); Assert.AreEqual(c.Zipcode, dbCity.Get(9999).Zipcode); }
public void CityUpdate() { Booking.Models.City c = new Models.City(9999, "Test"); Booking.DB.DbCity dbCity = new DB.DbCity(); dbCity.Delete(9999); dbCity.Create(c); Assert.AreEqual(dbCity.Get(9999).CityName, "Test"); c.CityName = "Changed"; dbCity.Update(c); Assert.AreEqual(dbCity.Get(9999).CityName, "Changed"); }
private void GetCity() { RestClient client = new RestClient(urlBase); client.Timeout = -1; string urlService = "cities/" + Service.idCity; city = new Models.City(); var request = new RestRequest(urlService, Method.GET); foreach (RestResponseCookie cookie in Login.cookies) { request.AddCookie(cookie.Name, cookie.Value); } request.AddHeader("Token", Login.tokenAccount.token); System.Net.ServicePointManager.ServerCertificateValidationCallback = (senderX, certificate, chain, sslPolicyErrors) => { return(true); }; try { IRestResponse response = client.Execute(request); if (response.StatusCode == System.Net.HttpStatusCode.Created || response.StatusCode == System.Net.HttpStatusCode.OK) { city = JsonConvert.DeserializeObject <Models.City>(response.Content); if (city == null) { MessageBox.Show("No se encontro la ciudad. Intente más tarde", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } else { Models.Error responseError = JsonConvert.DeserializeObject <Models.Error>(response.Content); MessageBox.Show(responseError.error, "Error", MessageBoxButton.OK, MessageBoxImage.Error); if (response.StatusCode == System.Net.HttpStatusCode.Forbidden || response.StatusCode == System.Net.HttpStatusCode.Unauthorized || response.StatusCode == System.Net.HttpStatusCode.RequestTimeout) { Login login = new Login(); login.Show(); Close(); } } } catch (Exception exception) { MessageBox.Show("No se pudo obtener información de la base de datos. Intente más tarde", "Error", MessageBoxButton.OK, MessageBoxImage.Error); TelegramBot.SendToTelegram(exception); LogException.Log(this, exception); } }
private void CreateMemberATEFromInputData() { memberATE.username = TextBoxUserName.Text; memberATE.lastname = TextBoxLastName.Text; memberATE.name = TextBoxName.Text; memberATE.email = TextBoxEmail.Text; if (DatePickerDateBirth.SelectedDate != null) { string dateBirth = DatePickerDateBirth.SelectedDate.Value.ToString("yyyy/MM/dd"); memberATE.dateBirth = dateBirth; } if (ComboBoxCity.SelectedItem != null) { string optionCity = ((ComboBoxItem)ComboBoxCity.SelectedItem).Content.ToString(); citySelection = cities.Find(City => City.name.Equals(optionCity)); memberATE.idCity = citySelection.idCity; } }
public void CityDelete() { Booking.Models.City c = new Models.City(9999, "Test"); Booking.DB.DbCity dbCity = new DB.DbCity(); dbCity.Delete(9999); dbCity.Create(c); if (dbCity.Get(9999).Zipcode == c.Zipcode) { dbCity.Delete(9999); Assert.IsNull(dbCity.Get(9999)); } else { Assert.Fail(); } }
public override async Task <Forecast> GetForecastOnDay(Models.City city) { if (city == null) { throw new Exception("City is not be null"); } var forecast = new Models.Forecast(); using (HttpClient client = new HttpClient()) { try { using (HttpResponseMessage response = await client.GetAsync(GetForecastUri(city.Name))) { if (response.IsSuccessStatusCode) { var responseJson = await response.Content.ReadAsStringAsync(); //Преобразуем JSON из респонса в JObject, и обращаемся к его ключам как к полям класса, dynamic responseObj = Newtonsoft.Json.Linq.JObject.Parse(responseJson); forecast.Temp = (float)responseObj.main.temp; forecast.Humidity = (float)responseObj.main.humidity; forecast.Pressure = (float)responseObj.main.pressure; } else { Console.WriteLine(response.ReasonPhrase); this.ServiceAvailable = false; } } } catch (Exception e) { Console.WriteLine(e.Message); this.ServiceAvailable = false; } } forecast.city = city; forecast.WeatherApi = this; return(forecast); }
/// <summary> /// Carga las ciudades a la BD /// </summary> public static void GetCity() { using (Y2kContext context = new Y2kContext()) { if (!context.City.Any()) { string content = Task.Run(GetDate).Result; List <Models.City> cities = JsonConvert.DeserializeObject <List <Models.City> >(content); foreach (var c in cities) { Models.City city = new Models.City(); city.IdExternal = c.Id; city.Name = c.Name; city.Country = c.Country; context.City.Add(city); } context.SaveChanges(); } } }
public IActionResult Create(Models.City item) { citiesRepository.Add(item); return(RedirectToAction("Index")); }
public Counterparty() { City = new Models.City(); }
public void Delete(Models.City c) { entities.Cities.Remove(c); }
public void Add(Models.City c) { entities.Cities.Add(c); }
public void Delete(Models.City c) { crep.Delete(c); Save(); }
public IHttpActionResult ListSchoolInfo() { List <ViewModel.API.School> SchoolInfoList = new List <ViewModel.API.School>(); string ConnectionString; App_Start.ConnectionString constr = new App_Start.ConnectionString(); ConnectionString = constr.GetConnectionString(); SqlConnection conn = new SqlConnection(ConnectionString); SqlDataReader rdr = null; //=========================================================================== //------------------------------- Get Cities ----------- List <Models.City> Cities = new List <Models.City>(); #region Get Cities try { if (conn.State == ConnectionState.Closed) { conn.Open(); } SqlCommand cmd = new SqlCommand(@"select * from Cities where (active =1 or active is null)", conn); rdr = cmd.ExecuteReader(); DataTable dataTable = new DataTable(); dataTable.Load(rdr); if (dataTable != null) { if ((dataTable.Rows.Count > 0)) { Cities = (from DataRow dr in dataTable.Rows select new Models.City() { Code = Convert.ToInt32(dr["Code"].ToString()), State_Code = Convert.ToInt32(dr["State_Code"].ToString()), Pname = dr["Pname"].ToString(), Ename = dr["Ename"].ToString(), } ).ToList(); } } } catch (Exception ex) { if (rdr != null) { rdr.Close(); rdr = null; } if (conn.State == ConnectionState.Open) { conn.Close(); } var msg = new HttpResponseMessage(HttpStatusCode.InternalServerError) { ReasonPhrase = "Internal Server Error!!!" }; throw new HttpResponseException(msg); } #endregion //------------------------------- Get Cities ----------- //=========================================================================== //=========================================================================== //------------------------------- Get CityZones ----------- List <Models.CityZone> CityZones = new List <Models.CityZone>(); #region Get CityZones try { if (conn.State == ConnectionState.Closed) { conn.Open(); } SqlCommand cmd = new SqlCommand(@"select * from CityZones where (active =1 or active is null)", conn); rdr = cmd.ExecuteReader(); DataTable dataTable = new DataTable(); dataTable.Load(rdr); if (dataTable != null) { if ((dataTable.Rows.Count > 0)) { CityZones = (from DataRow dr in dataTable.Rows select new Models.CityZone() { Code = Convert.ToInt32(dr["Code"].ToString()), Zone_Code = Convert.ToInt32(dr["Zone_Code"].ToString()), Pname = dr["Pname"].ToString(), Ename = dr["Ename"].ToString(), } ).ToList(); } } } catch (Exception ex) { if (rdr != null) { rdr.Close(); rdr = null; } if (conn.State == ConnectionState.Open) { conn.Close(); } var msg = new HttpResponseMessage(HttpStatusCode.InternalServerError) { ReasonPhrase = "Internal Server Error!!!" }; throw new HttpResponseException(msg); } #endregion //------------------------------- Get Cities ----------- //=========================================================================== //=========================================================================== //------------------------------- Get School List ----- #region Get School List try { if (conn.State == ConnectionState.Closed) { conn.Open(); } SqlCommand cmd = new SqlCommand(@"select id,name,address,city_code,tel1,En_Name,Description,boyOrGirl,Edit_Date from Institutes where (Active =1 or Active is null)" , conn); rdr = cmd.ExecuteReader(); DataTable dataTable = new DataTable(); dataTable.Load(rdr); if (dataTable != null) { if ((dataTable.Rows.Count > 0)) { foreach (DataRow item in dataTable.Rows) { ViewModel.API.School CurrentSchool = new ViewModel.API.School(); CurrentSchool.about = item["Description"].ToString(); CurrentSchool.address = item["address"].ToString(); bool gender = item["boyOrGirl"].ToString() != "" ? bool.Parse(item["boyOrGirl"].ToString()) : true; if (gender == true) { CurrentSchool.gender = "پسرانه"; } else { CurrentSchool.gender = "دخترانه"; } CurrentSchool.id = int.Parse(item["id"].ToString()); CurrentSchool.lastRefreshed = item["Edit_Date"].ToString() != null ? item["Edit_Date"].ToString() : ""; //CurrentSchool.liked = ""; CurrentSchool.phoneNumber = item["tel1"].ToString(); CurrentSchool.schoolName = item["name"].ToString(); string url = ""; if (item["En_Name"].ToString() != "") { url = "http://egbaliye.forooshgahyas.ir/Content/images/schools/" + CurrentSchool.id + "/" + item["En_Name"].ToString() + "-main.JPG"; } CurrentSchool.imageUrl = url; int Zone_Code = 0, Code = 0, State_Code = 0; #region Analyze CityCode if (item["city_code"].ToString() != "") { string CityCode = item["city_code"].ToString(); if (CityCode.Length >= 4) { string provinceCode = CityCode.Substring(0, 4); if (provinceCode != "") { Code = int.Parse(provinceCode); if (CityCode.Length >= 8) { string townCode = CityCode.Substring(4, 4); if (townCode != "") { State_Code = int.Parse(townCode); if (CityCode.Length >= 12) { string regionCode = CityCode.Substring(8, 4); if (regionCode != "") { Zone_Code = int.Parse(regionCode); } } } } } } } #endregion Models.City CurrentCity = Cities.Where(p => p.Code == Code && p.State_Code == Code).FirstOrDefault(); if (CurrentCity != null) { CurrentSchool.province = CurrentCity.Pname; } CurrentCity = Cities.Where(p => p.Code == State_Code && p.State_Code == Code).FirstOrDefault(); if (CurrentCity != null) { CurrentSchool.town = CurrentCity.Pname; } Models.CityZone myzone = CityZones.Where(p => p.Code == State_Code && p.Zone_Code == Zone_Code).FirstOrDefault(); if (myzone != null) { CurrentSchool.region = myzone.Zone_Code; } SchoolInfoList.Add(CurrentSchool); } } } } catch (Exception ex) { if (rdr != null) { rdr.Close(); rdr = null; } if (conn.State == ConnectionState.Open) { conn.Close(); } var msg = new HttpResponseMessage(HttpStatusCode.InternalServerError) { ReasonPhrase = "Internal Server Error!!!" }; throw new HttpResponseException(msg); } #endregion //------------------------------- Get School List ----- //=========================================================================== if (rdr != null) { rdr.Close(); rdr = null; } if (conn.State == ConnectionState.Open) { conn.Close(); } return(Ok(SchoolInfoList)); }
public Models.City FindCity(int id) { Models.City city = cityRepo.Find(id); return(city); }
public void AddCity(Models.City city) { cityRepo.Create(city); }
public void EditCity(Models.City city) { cityRepo.Update(city); }
public void Add(Models.City c) { crep.Add(c); Save(); }
/// <summary> /// Import existing Cities /// </summary> /// <param name="performContext"></param> /// <param name="dbContext"></param> /// <param name="fileLocation"></param> static private void ImportCities(PerformContext performContext, DbAppContext dbContext, string fileLocation, string systemId) { string completed = DateTime.Now.ToString("d") + "-" + "Completed"; ImportMap importMap = dbContext.ImportMaps.FirstOrDefault(x => x.OldTable == oldTable && x.OldKey == completed && x.NewKey == sigId); if (importMap != null) { performContext.WriteLine("*** Importing " + xmlFileName + " is complete from the former process ***"); return; } try { string rootAttr = "ArrayOf" + oldTable; performContext.WriteLine("Processing " + oldTable); var progress = performContext.WriteProgressBar(); progress.SetValue(0); // create serializer and serialize xml file XmlSerializer ser = new XmlSerializer(typeof(HETS_City[]), new XmlRootAttribute(rootAttr)); MemoryStream memoryStream = ImportUtility.memoryStreamGenerator(xmlFileName, oldTable, fileLocation, rootAttr); HETSAPI.Import.HETS_City[] legacyItems = (HETSAPI.Import.HETS_City[])ser.Deserialize(memoryStream); foreach (var item in legacyItems.WithProgress(progress)) { // see if we have this one already. importMap = dbContext.ImportMaps.FirstOrDefault(x => x.OldTable == oldTable && x.OldKey == item.City_Id.ToString()); if (importMap == null) // new entry { Models.City city = null; CopyToInstance(performContext, dbContext, item, ref city, systemId); ImportUtility.AddImportMap(dbContext, oldTable, item.City_Id.ToString(), newTable, city.Id); } else // update { Models.City city = dbContext.Cities.FirstOrDefault(x => x.Id == importMap.NewKey); if (city == null) // record was deleted { CopyToInstance(performContext, dbContext, item, ref city, systemId); // update the import map. importMap.NewKey = city.Id; dbContext.ImportMaps.Update(importMap); dbContext.SaveChangesForImport(); } else // ordinary update. { CopyToInstance(performContext, dbContext, item, ref city, systemId); // touch the import map. importMap.LastUpdateTimestamp = DateTime.UtcNow; dbContext.ImportMaps.Update(importMap); dbContext.SaveChangesForImport(); } } } performContext.WriteLine("*** Done ***"); ImportUtility.AddImportMap(dbContext, oldTable, completed, newTable, sigId); } catch (Exception e) { performContext.WriteLine("*** ERROR ***"); performContext.WriteLine(e.ToString()); } }