///<summary>Inserts one County into the database. Returns the new priKey.</summary> internal static long Insert(County county) { if(DataConnection.DBtype==DatabaseType.Oracle) { county.CountyNum=DbHelper.GetNextOracleKey("county","CountyNum"); int loopcount=0; while(loopcount<100){ try { return Insert(county,true); } catch(Oracle.DataAccess.Client.OracleException ex){ if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){ county.CountyNum++; loopcount++; } else{ throw ex; } } } throw new ApplicationException("Insert failed. Could not generate primary key."); } else { return Insert(county,false); } }
public Competition GetCompetitionByNameYearAndCounty(string name, DateTime year, County county) { DateTime start = DateTime.Parse("01/01/" + year.Year); DateTime end = DateTime.Parse("31/12/" + year.Year); return context.Competitions .Where(c => c.Name == name && c.StartDate >= start && c.StartDate <= end) .FirstOrDefault(); }
///<summary>Converts a DataTable to a list of objects.</summary> public static List<County> TableToList(DataTable table){ List<County> retVal=new List<County>(); County county; for(int i=0;i<table.Rows.Count;i++) { county=new County(); county.CountyNum = PIn.Long (table.Rows[i]["CountyNum"].ToString()); county.CountyName= PIn.String(table.Rows[i]["CountyName"].ToString()); county.CountyCode= PIn.String(table.Rows[i]["CountyCode"].ToString()); retVal.Add(county); } return retVal; }
public Venue CreateVenue(string name, string location, County county) { Venue ven = new Venue(); ven.Name = name; ven.Location = location; ven.County = county; context.Venues.Add(ven); context.SaveChanges(); return ven; }
public int Update(County value) { string sql = "UPDATE [T_County] SET [NAME]=@NAME,[SPELLING]=@SPELLING,[SHORTSPELLING]=@SHORTSPELLING,[HOTLEVEL]=@HOTLEVEL,[CITY]=@CITY WHERE [CODE]=@CODE"; using (var dbOperator = new DbOperator(Provider, ConnectionString)) { dbOperator.AddParameter("CODE", value.Code); dbOperator.AddParameter("NAME", value.Name); dbOperator.AddParameter("SPELLING", value.Spelling ?? string.Empty); dbOperator.AddParameter("SHORTSPELLING", value.ShortSpelling ?? string.Empty); dbOperator.AddParameter("HOTLEVEL", value.HotLevel); dbOperator.AddParameter("CITY", value.CityCode); return(dbOperator.ExecuteNonQuery(sql)); } }
public int Insert(County value) { string sql = "INSERT INTO [T_County]([CODE],[NAME],[SPELLING],[SHORTSPELLING],[HOTLEVEL],[CITY]) VALUES(@CODE,@NAME,@SPELLING,@SHORTSPELLING,@HOTLEVEL,@CITY)"; using (var dbOperator = new DbOperator(Provider, ConnectionString)) { dbOperator.AddParameter("CODE", value.Code); dbOperator.AddParameter("NAME", value.Name); dbOperator.AddParameter("SPELLING", value.Spelling ?? string.Empty); dbOperator.AddParameter("SHORTSPELLING", value.ShortSpelling ?? string.Empty); dbOperator.AddParameter("HOTLEVEL", value.HotLevel); dbOperator.AddParameter("CITY", value.CityCode); return(dbOperator.ExecuteNonQuery(sql)); } }
public void Update(County countyNew) { if (countyNew == null) { return; } using (var db = new AddressContext()) { var cityOld = db.Countys .Single(x => x.CountyId.Equals(countyNew.CountyId)); cityOld = countyNew; db.SaveChanges(); } }
///<summary>Updates the Countyname and code in the County table, and also updates all patients that were using the oldCounty name.</summary> public static void Update(County Cur) { string command = "UPDATE county SET " + "CountyName ='" + POut.PString(Cur.CountyName) + "'" + ",CountyCode ='" + POut.PString(Cur.CountyCode) + "'" + " WHERE CountyName = '" + POut.PString(Cur.OldCountyName) + "'"; General.NonQ(command); //then, update all patients using that County command = "UPDATE patient SET " + "County ='" + POut.PString(Cur.CountyName) + "'" + " WHERE County = '" + POut.PString(Cur.OldCountyName) + "'"; General.NonQ(command); }
private void AddCounty() { try { string countyName = null; //Get text value from New County Field if this Field is not null and not Empty if (txNewCounty.Value.ToString() != null && !txNewCounty.Value.ToString().Equals("")) { countyName = txNewCounty.Value.ToString(); } if (countyName != null) { //Get all County records from DB var counties = from c in mdolEntities.Counties select c; //Add new County and check if entered County name exists in the Database int dCounter = 0; foreach (var c in counties) { if (c.CountyName.ToLower().Equals(countyName.ToLower())) { dCounter++; } } if (dCounter == 0) { //Add new County record County countyTemp = new County(); countyTemp.CountyName = countyName; mdolEntities.Counties.Add(countyTemp); mdolEntities.SaveChanges(); } else { lblCountyMessage.Text = countyName + ": already exists in the database"; } } txNewCounty.Value = null; LoadCounties(); LoadOriginItems(); } catch (Exception ex) { string str = "Exaption in the: {Origin Class}: [Method: AddCounty()]"; ExceptionsSaver(str); } }
// GET: Counties/Details/5 public async Task <ActionResult> Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } County county = await db.Countys.FindAsync(id); if (county == null) { return(HttpNotFound()); } return(View(county)); }
public override string ToString() { return(string.Join(", ", new string[] { Line1.RemoveFromEnd(",").ToSentenceCase(), Line2.RemoveFromEnd(",").ToSentenceCase(), Town.RemoveFromEnd(",").ToSentenceCase(), County.RemoveFromEnd(",").ToSentenceCase(), Postcode.ToUpper() } .Where(x => !string.IsNullOrWhiteSpace(x)) .Select(x => x))); }
public void AddNewNode(AddNewNodeQueryParams parameters) { GeocodingAddressModelQueryParams address = new GeocodingAddressModelQueryParams(parameters.Street, parameters.DoorNumber, parameters.PostalCode, parameters.County, parameters.District); Station stationAdded = new Station(); //TODO: REFACTOR THIS RootGeocodingDataModel <GeocodingAddressResponseModel> coords = _geocodingDomain.GetCoordsFromAddress(address); Location location = _locationDomain.RetrieveLocation(coords.Data.FirstOrDefault().Latitude, coords.Data.FirstOrDefault().Longitude); if (location == null) { District district = _districtDomain.GetDistrictByDistrictName(address.District); County county = _countyDomain.GetCountyByCountyName(address.County); _locationDomain.InsertLocationData(location, district.Id_District, county.CountyId); location = _locationDomain.RetrieveLocation(coords.Data.FirstOrDefault().Latitude, coords.Data.FirstOrDefault().Longitude); } //SE nao for um sensor real procurar a estação metereologica mais proxima, adicionar a bd, e depois adiconar o no a apontar para a estação if (parameters.IsRealSensor != true) { var stationAddedInfo = _weatherStationApplication .AddWeatherStationToDatabase(address); stationAdded = _weatherStationApplication.RetrieveStationByStationName(stationAddedInfo.station.Name); Location locationStationAddded = stationAddedInfo.locationStations; SmartIrrigationModels.Models.DTOS.Node nodeAdded = _nodeDomain.AddNewNode(parameters, location.Id_Location, stationAdded.Id_Station ?? -1); _weatherStationApplication.AddWeatherStationDataToDatabase(stationAdded, locationStationAddded, nodeAdded); } else { //se for um sensor real, adiciona o no com o IdNearStation a -1 e depois adiciona os sensores a apontar para o no No _nodeDomain.AddNewNode(parameters, location.Id_Location, -1); foreach (var sensor in parameters.SensorsImplemented) { _sensorDomain.AddNewSensor(parameters.Street, sensor, location.Id_Location ?? -1); } } }
public string[] GetHistoryEvaporationByCountyName(County county, string districtName) { RestClient client = new RestClient($"https://api.ipma.pt/open-data/observation/climate/evapotranspiration/{districtName.ToLower()}/et0-{county.CountyId}-{county.Name.ToLower()}.csv"); var request = new RestRequest(); request.AddHeader("Accept", "*/*"); request.AddHeader("Accept-Encoding", "gzip, deflate"); request.AddHeader("User-Agent", "runscope/0.1"); request.Method = Method.GET; var response = client.Execute(request).Content.Split("\n"); return(response); }
static List <Province> ProcessLines(String[] lines) { var provinces = new List <Province>(); var province = default(Province); var city = default(City); foreach (var line in lines) { var id = default(string); var parts = line.Split("\t", StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 2) { id = parts[0]; var right = parts[1]; var nameAndCode = right.Trim(' ').Split(" ", StringSplitOptions.None); var name = nameAndCode[nameAndCode.Length - 2]; var code = nameAndCode[nameAndCode.Length - 1]; if (!right.StartsWith(" ")) { province = new Province() { id = id, name = name, code = code }; provinces.Add(province); } else { // county if (right.StartsWith(" ")) { var county = new County() { id = id, name = name, code = code }; city.Add(county); } else if (right.StartsWith(" ")) { // city city = new City() { id = id, name = name, code = code }; province.Add(city); } } } } return(provinces); }
// GET: Counties/Delete/5 public ActionResult Delete(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } County county = db.Counties.Find(id); if (county == null) { return(HttpNotFound()); } return(View(county)); }
public async Task <Result> Handle(AddCountyCommand request, CancellationToken cancellationToken) { var entity = new County { Name = request.Name, CountryId = request.CountryId }; await _context.Counties.AddAsync(entity, cancellationToken); await _context.SaveChangesAsync(cancellationToken); return(Result.Success("County was created successfully")); }
public Competition CreateCompetition(string name, DateTime startDate, DateTime endDate, County county) { Competition c = new Competition(); c.Name = name; c.StartDate = startDate.Date; c.EndDate = endDate.Date; c.County = county; context.Competitions.Add(c); context.SaveChanges(); return c; }
public bool Update(County updateEntity) { if (updateEntity == null) { throw new Exception("County 無對應資料可更新"); } _dbContext.County.Update(updateEntity); _dbContext.CountyLanguage.UpdateRange(updateEntity.CountyLanguages); // 同時更新二個 Table,會自動加上 transaction return(_dbContext.SaveChanges() > 0); }
public bool CreateCounty(CountyCreate model) { var entity = new County() { CountyName = model.CountyName }; using (var ctx = new ApplicationDbContext()) { ctx.Counties.Add(entity); return(ctx.SaveChanges() == 1); } }
public async Task <Address> Handle(AddAddressCommand request, CancellationToken cancellationToken) { Address address = this.customerRepository.Insert(Address.Create(request.Street, request.ZipCode)); County county = this.customerRepository.SelectCountyById(request.CountyId); if (county != null) { address.SetCounty(county); } await this.customerRepository.UnitOfWork.SaveEntitiesAsync(); return(address); }
protected override void CreateObject() { currentEntity = new County { Id = Id, Code = txtCode.Text, CountyName = txtCountyName.Text, CountryId = _countryId, Description = txtDescription.Text, Statu = tglStatu.IsOn }; ButtonEnableStatus(); }
public async Task <ActionResult <County> > UpdateCounty(int countyId, UpdateCountyCommand updateCountyCommand) { try { updateCountyCommand.SetCountyId(countyId); County county = await this.mediator.Send(updateCountyCommand); return(Ok(county)); } catch (Exception ex) { return(this.BadRequest(ex)); } }
public IHttpActionResult DeleteCounty(int id) { County county = db.Counties.Find(id); if (county == null) { return(NotFound()); } db.Counties.Remove(county); db.SaveChanges(); return(Ok(county)); }
public County CreateCounty(string name, Enums.Provinces province) { CountyTeam ct = new CountyTeam(); ct.Name = name; County c = new County(); c.Name = name; c.Province = province.ToString(); c.CountyTeam = ct; context.Counties.Add(c); context.SaveChanges(); return c; }
// GET: Counties/Edit/5 public ActionResult Edit(int?id) { PopulatePartialView(); if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } County county = db.Counties.Find(id); if (county == null) { return(HttpNotFound()); } return(View(county)); }
private static void MapEntityCounty(GeographicalAreaDto dto, List <County> counties) { var county = counties.FirstOrDefault(na => na.Number == int.Parse(dto.Number)); if (county == null) { county = new County { Number = int.Parse(dto.Number), Name = dto.Name }; counties.Add(county); } }
///<summary>Inserts one County into the database. Returns the new priKey. Doesn't use the cache.</summary> public static long InsertNoCache(County county) { if (DataConnection.DBtype == DatabaseType.MySql) { return(InsertNoCache(county, false)); } else { if (DataConnection.DBtype == DatabaseType.Oracle) { county.CountyNum = DbHelper.GetNextOracleKey("county", "CountyNum"); //Cacheless method } return(InsertNoCache(county, true)); } }
///<summary>Converts a DataTable to a list of objects.</summary> public static List <County> TableToList(DataTable table) { List <County> retVal = new List <County>(); County county; foreach (DataRow row in table.Rows) { county = new County(); county.CountyNum = PIn.Long(row["CountyNum"].ToString()); county.CountyName = PIn.String(row["CountyName"].ToString()); county.CountyCode = PIn.String(row["CountyCode"].ToString()); retVal.Add(county); } return(retVal); }
///<summary>Converts a DataTable to a list of objects.</summary> public static List <County> TableToList(DataTable table) { List <County> retVal = new List <County>(); County county; for (int i = 0; i < table.Rows.Count; i++) { county = new County(); county.CountyNum = PIn.Long(table.Rows[i]["CountyNum"].ToString()); county.CountyName = PIn.String(table.Rows[i]["CountyName"].ToString()); county.CountyCode = PIn.String(table.Rows[i]["CountyCode"].ToString()); retVal.Add(county); } return(retVal); }
/// <summary> /// Pega o municipio /// </summary> /// <param name="pCode">Código do Municipo</param> /// <param name="pCompanyDB">Banco da Empresa</param> /// <returns></returns> public static County GetCounty(int pCode, string pCompanyDB) { pCompanyDB.CheckForArgumentNull("pCompanyDb"); var empl = new County(pCompanyDB); if (!empl.GetByKey(pCode)) { throw new Exception( string.Format( DontFindText1Key, "Municipio", pCode)); } return(empl); }
public ActionResult EditCounty(EditCountyModel model) { if (ModelState.IsValid) { var updatedCounty = new County() { Name = model.Name, ShortName = model.ShortName, IdCounty = model.CountyId }; Services.LocalitiesService.UpdateCounty(updatedCounty); } return(RedirectToAction("EditCounty", new { id = model.CountyId })); }
public async Task <Address> Handle(UpdateAddressCommand request, CancellationToken cancellationToken) { Address address = this.customerRepository.SelectAddressById(request.AddressId); County county = this.customerRepository.SelectCountyById(request.CountyId); address.SetStreet(request.Street); address.SetZipCode(request.ZipCode); if (county != null) { address.SetCounty(county); } this.customerRepository.Update(address); await this.customerRepository.UnitOfWork.SaveEntitiesAsync(); return(address); }
private void btnInsert_Click(object sender, EventArgs e) { try { County county = new County(); county.Description = txtCountyName.Text.ToString(); county.CityID = Convert.ToInt32(cbCity.SelectedValue); ctx.Counties.Add(county); ctx.SaveChanges(); FillCounty(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/** * Search the county in the grid and update it */ public void UpdateCounty(County county) { foreach (DataGridViewRow row in dgvCounties.Rows) { if (row.Cells["CountyName"].Value == null) { continue; } if (row.Cells["CountyName"].Value.ToString().Trim() == county.Name) { row.Cells["CountyCode"].Value = county.Code.ToString(); row.Cells["Processed"].Value = county.Processed? "Processed" : ""; break; } } }
/// <summary> /// Populate the common fields returned by all API requests /// </summary> /// <param name="dto"></param> /// <param name="theCounty"></param> /// <param name="infections"></param> /// <param name="state"></param> /// <returns></returns> private void PopulateBaseDto(BaseDTO dto, County theCounty, IEnumerable <Infections> infections, string state) { // order by date ensures we display the earliest possible date if there is a match on multiple days var maxInfectionDay = infections.Where(x => x.NewCases == infections.Max(i => i.NewCases)).OrderBy(d => d.Date).FirstOrDefault(); var minInfectionDay = infections.Where(x => x.NewCases == infections.Min(i => i.NewCases)).OrderBy(d => d.Date).FirstOrDefault(); dto.AverageDailyCases = Math.Round(infections.Average(i => Convert.ToDouble(i.Count)), 1); dto.Latitude = theCounty?.Lat; dto.Longitude = theCounty?.Long; dto.Location = theCounty?.Name ?? state ?? ""; dto.MaximumNumberOfCases = maxInfectionDay.NewCases; dto.MaximumNumberOfCasesDate = maxInfectionDay.Date.ToString("MM/dd/yyyy"); dto.MinimumNumberOfCases = minInfectionDay.NewCases; dto.MinimumNumberOfCasesDate = minInfectionDay.Date.ToString("MM/dd/yyyy"); }
public override int GetHashCode() { unchecked { var hashCode = Country != null?Country.GetHashCode() : 0; hashCode = (hashCode * 397) ^ (Voivodeship != null ? Voivodeship.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (County != null ? County.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Community != null ? Community.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (City != null ? City.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (District != null ? District.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Street != null ? Street.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Number != null ? Number.GetHashCode() : 0); return(hashCode); } }
public County DeleteCounty(County county) { County cty = context.Counties .Where(c => c == county) .FirstOrDefault(); if (cty != null) { context.Counties.Remove(cty); context.SaveChanges(); return cty; } else { return null; } }
///<summary>Inserts one County into the database. Provides option to use the existing priKey.</summary> public static long Insert(County county,bool useExistingPK){ if(!useExistingPK && PrefC.RandomKeys) { county.CountyNum=ReplicationServers.GetKey("county","CountyNum"); } string command="INSERT INTO county ("; if(useExistingPK || PrefC.RandomKeys) { command+="CountyNum,"; } command+="CountyName,CountyCode) VALUES("; if(useExistingPK || PrefC.RandomKeys) { command+=POut.Long(county.CountyNum)+","; } command+= "'"+POut.String(county.CountyName)+"'," +"'"+POut.String(county.CountyCode)+"')"; if(useExistingPK || PrefC.RandomKeys) { Db.NonQ(command); } else { county.CountyNum=Db.NonQ(command,true); } return county.CountyNum; }
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { if(comboBox1.SelectedIndex < Countylist.Count) { selecteCounty = Countylist[comboBox1.SelectedIndex]; comboBox2.Items.Clear(); for (int i = 0; i < selecteCounty.Shops.Count; i++) { comboBox2.Items.Add(selecteCounty.Shops[i]); } comboBox2.SelectedIndex = 0; } else { selecteCounty = null; } //comboBox1.SelectedItem.ToString() }
public List<Competition> GetCompetitionsByCountyAndYear(County county, DateTime year) { return context.Competitions .Where(c => c.County == county && c.StartDate == year) .ToList(); }
public Competition UpdateCompetition(Competition comp, string name, DateTime startDate, DateTime endDate, County county) { Competition cmp = context.Competitions .Include("County") .Where(c => c.Name == comp.Name && c.StartDate == comp.StartDate && c.EndDate == comp.EndDate) .FirstOrDefault(); if (cmp != null) { cmp.Name = name; cmp.StartDate = startDate.Date; cmp.EndDate = endDate.Date; cmp.County = county; context.SaveChanges(); return cmp; } else { return null; } }
public void takeCounty(County c, int ownership) { if (c.occupied == 1) { revenue -= c.revenue; } else if (c.occupied == 2) { unionRevenue -= c.revenue; } c.occupied = ownership; if (ownership == 1) { revenue += c.revenue; } else if (ownership == 2) { unionRevenue += c.revenue; } }
///<summary>Updates one County in the database.</summary> internal static void Update(County county) { string command="UPDATE county SET " +"CountyName= '"+POut.String(county.CountyName)+"', " +"CountyCode= '"+POut.String(county.CountyCode)+"' " +"WHERE CountyNum = "+POut.Long(county.CountyNum); Db.NonQ(command); }
public Venue UpdateVenue(Venue venue, string name, string location, County county) { Venue ven = context.Venues .Where(v => v == venue) .FirstOrDefault(); if (ven != null) { ven.Name = name; ven.Location = location; ven.County = county; context.SaveChanges(); return ven; } else { return null; } }
public List<Venue> GetVenuesByCounty(County county) { return context.Venues .Where(v => v.County == county) .ToList(); }
public GameStateMap(ContentManager c, Game1 g, int nP) { Content = c; game = g; week = 0; revenue = 0; unionRevenue = 0; funds = 0; unionFunds = 0; ownedCounties = 1; multiPlayer = (nP == 2); playerNumber = 1; enemyNumber = 2; selectingForAttack = 0; selectingForTroopTransfer = 0; selectingForRecruitment = false; actionMenu = null; gpWindow = null; playerNames = new string[] { "\\0UNOCCUPIED", "\\3CHRISTIE\\0", "\\4UNION\\0" }; beginning = true; beginningSelector = 1; beginningTextWindow = new TextWindow(new String[] { playerNames[1] + " SELECT A COUNTY" }, Content, new Vector2(25, 25), new Vector2(500, 25)); inputHandler = new InputHandler(); countyNames = new string[] { "Atlantic", "Bergen", "Burlington", "Camden", "Cape May", "Cumberland", "Essex", "Gloucester", "Hudson", "Hunterdon", "Mercer", "Middlesex", "Monmouth","Morris", "Ocean", "Passaic", "Salem", "Somerset", "Sussex", "Union", "Warren"}; countyRevenues = new int[] { 27,42,34,29,33,21,31,31,31,48,36,33,40,47,29,26,27,47,35,34,32 }; countyPopulations = new int[] { 274,905,448,513,97,156,783,288,634,128,366,809,630,492,576,501,66,323,149,536,108 }; countyGraph = new int[][] { new int[] {2,3,4,5,7}, // Atlantic new int[] {6,8,15}, // Bergen new int[] {10,12,0,3,14}, // Burlington new int[] {0,2,7}, // Camden new int[] {0,5}, // Cape May new int[] {4,0,16,7}, // Cumberland new int[] {1,8,15,19,13}, // Essex new int[] {16,3,5,0}, // Gloucester new int[] {1,6}, // Hudson new int[] {20,13,17,10}, // Hunterdon new int[] {9,17,11,12,2}, // Mercer new int[] {19,17,10,12}, // Middlesex new int[] {10,11,2,14}, // Monmouth new int[] {18,15,6,19,17,9,20}, // Morris new int[] {12,2}, // Ocean new int[] {13,6,1,18}, // Passaic new int[] {7,5}, // Salem new int[] {13, 19, 11, 10, 9}, // Somerset new int[] {15,13,20}, // Sussex new int[] {6,13,17,11}, // Union new int[] {18,13,9} // Warren }; labelOffsets = new Vector2[] { new Vector2(-30,0), // Atlantic new Vector2(-10,-10), // Bergen new Vector2(-15,-20), // Burlington new Vector2(-120, -70), // Camden new Vector2(30, 0), // Cape May new Vector2(0,0), // Cumberland new Vector2(-23, -20), // Essex new Vector2(-30, -20), // Gloucester new Vector2(10, -10), // Hudson new Vector2(-20, -20), // Hunterdon new Vector2(-30, -10), // Mercer new Vector2(-40, 0), // Middlesex new Vector2(0, -5), // Monmouth new Vector2(-20, -5), // Morris new Vector2(-40, -40), // Ocean new Vector2(0, -70), // Passaic new Vector2(-40, -35), // Salem new Vector2(-30, 0), // Somerset new Vector2(-40, -20), // Sussex new Vector2(30, 5), // Union new Vector2(-100, -10) // Warren }; counties = new County[countyNames.Length]; individualCounty = null; icTextWindow = null; int x = 0; foreach (string co in countyNames) // load county sprites { Sprite s = new Sprite(co + ".png", Content, new Vector2(650, 600)); s.position = new Vector2(650 - s.boundingRectangle.Width, 600 - s.boundingRectangle.Height); Sprite sfull = new Sprite(co + "-full.png", Content, new Vector2(0, 0)); counties[x] = new County(co, s, sfull, countyRevenues[x], countyPopulations[x], countyGraph[x++]); } troopLabels = new TextWindow[21]; updateGameLabels(); }
/// <summary> /// Read Countries and their corrosponding Daily Allowance /// </summary> /// <param name="fileName"></param> /// <returns></returns> public List<County> ReadCountiesAndDailyAllowances(string fileName) { string inputReader; string []splitArray = new string[2]; County countires = new County(); StreamReader io = new StreamReader(fileName); //Filtering manually the 1st 4 elements from the text file which are //Finland's Full day Allowance inputReader = io.ReadLine(); splitArray = inputReader.Split(';'); FinFull = splitArray[1]; //Finland's half day allowance inputReader = io.ReadLine(); splitArray = inputReader.Split(';'); FinHalf = splitArray[1]; //Finland's KM Allowance inputReader = io.ReadLine(); splitArray = inputReader.Split(';'); FinKm = splitArray[1]; //Number of Persons Accompanying during the trip inputReader = io.ReadLine(); splitArray = inputReader.Split(';'); FinPerson = splitArray[1]; inputReader = io.ReadLine(); while (inputReader != null) { splitArray = inputReader.Split(';'); countires.Name = splitArray[0]; countires.DailyAllowance = int.Parse(splitArray[1]); countyList.Add(countires); inputReader = io.ReadLine(); } io.Close(); return countyList; //Returns countries list with their corrosponding allowance value }
public void handleInput() { if (okayButton != null) { inputHandler.update(Keyboard.GetState()); okayButton.handleInput(inputHandler); return; } if (actionMenu != null) { inputHandler.update(Keyboard.GetState()); actionMenu.handleInput(inputHandler); if (selectingForAttack != 0 || selectingForRecruitment || selectingForTroopTransfer != 0) { return; } } if (beginningMenu != null) { inputHandler.update(Keyboard.GetState()); beginningMenu.handleInput(inputHandler); return; } MouseState currentMouseState = Mouse.GetState(); inputHandler.updateMouse(currentMouseState); if (inputHandler.allowSingleClick()) { List<County> selectedCounties = new List<County>(); foreach (County c in counties) { if (c.mapRectangle.Contains(currentMouseState.Position)) { selectedCounties.Add(c); } } if (selectedCounties.Count > 0) { County closestCenter = selectedCounties[0]; for (int x = 1; x < selectedCounties.Count; x++) { if (Sprite.getRectangleDistance(selectedCounties[x].mapRectangle.Center, currentMouseState.Position) < Sprite.getRectangleDistance(closestCenter.mapRectangle.Center, currentMouseState.Position)) { closestCenter = selectedCounties[x]; } } individualCounty = closestCenter; icTextWindow = new TextWindow(new string[] { individualCounty.name.ToUpper() + " COUNTY\\n" + "REVENUE: " + individualCounty.revenue + "\\n" + "STATIONED TROOPS: " + individualCounty.troops + "\\n" + "OWNER: " + individualCounty.getOwner() }, Content, new Vector2(350,630), new Vector2(400, 115)); if (beginning) { beginningTextWindow.advanceLine(); beginningTextWindow = new TextWindow( new string[] { "SELECT " + individualCounty.name.ToUpper() }, Content, new Vector2(25, 25), new Vector2(300, 25)); beginningMenu = new Menu( new Vector2(100, 100), new string[] { "YES", "NO" }, new Menu.menuAction[] { selectStartingCounty, cancelStartingCounty }, 2, 1, "test-semifont.png", Content); } else if (selectingForAttack == 1) { targetCounty = individualCounty; selectingForAttack = 2; gpWindow = new TextWindow(new string[] { "SELECT INVADING COUNTY" }, Content, new Vector2(25, 25), new Vector2(360, 25)); } else if (selectingForAttack == 2) { sourceCounty = individualCounty; bool adjacent = false; for (int x = 0; x < sourceCounty.edges.Length; x++) { if (targetCounty == counties[sourceCounty.edges[x]]) { adjacent = true; break; } } int playerFunds = funds; if (playerNumber == 2) playerFunds = unionFunds; if (sourceCounty.occupied != playerNumber) { gpWindow = new TextWindow(new String[] { "SOURCE COUNTY IS NOT YOURS" }, Content, new Vector2(25, 25), new Vector2(500, 25)); okayButton = new Menu(new Vector2(700, 25), new string[] { "OK" }, new Menu.menuAction[] { cancelAttack }, 1, 1, "test-semifont.png", Content); return; } else if (targetCounty.occupied == playerNumber) { gpWindow = new TextWindow(new String[] { "TARGET COUNTY IS ALREADY YOURS" }, Content, new Vector2(25, 25), new Vector2(500, 25)); okayButton = new Menu(new Vector2(700, 25), new string[] { "OK" }, new Menu.menuAction[] { cancelAttack }, 1, 1, "test-semifont.png", Content); return; } else if (!adjacent) { gpWindow = new TextWindow(new String[] { "TARGET COUNTY TOO FAR AWAY" }, Content, new Vector2(25, 25), new Vector2(500, 25)); okayButton = new Menu(new Vector2(700, 25), new string[] { "OK" }, new Menu.menuAction[] { cancelAttack }, 1, 1, "test-semifont.png", Content); return; } else if (playerFunds - (sourceCounty.troops / 2) < 0) { gpWindow = new TextWindow(new String[] { "NOT ENOUGH FUNDS REQUIRED: " + (sourceCounty.troops / 2) }, Content, new Vector2(25, 25), new Vector2(650, 25)); okayButton = new Menu(new Vector2(700, 25), new string[] { "OK" }, new Menu.menuAction[] { cancelAttack }, 1, 1, "test-semifont.png", Content); return; } selectingForAttack = 3; int cost = sourceCounty.troops / 2; gpWindow = new TextWindow(new string[] { "ATTACK " + targetCounty.name.ToUpper() + " FROM " + sourceCounty.name.ToUpper() + "\\nCOST: " + cost }, Content, new Vector2(25, 25), new Vector2(650, 50)); actionMenu = new Menu( new Vector2(100, 100), new string[] { "YES", "NO" }, new Menu.menuAction[] { attackCounty, cancelAttack }, 2, 1, "test-semifont.png", Content); } else if (selectingForTroopTransfer == 1) { targetCounty = individualCounty; selectingForTroopTransfer = 2; gpWindow = new TextWindow(new string[] { "SELECT DONOR" }, Content, new Vector2(25, 25), new Vector2(360, 25)); } else if (selectingForTroopTransfer == 2) { sourceCounty = individualCounty; int playerFunds = funds; if (playerNumber == 2) playerFunds = unionFunds; bool connected = false; List<County> visited = new List<County>(); Stack<County> DFSstack = new Stack<County>(); DFSstack.Push(sourceCounty); while (DFSstack.Count != 0) { County chk = DFSstack.Pop(); if (chk == targetCounty && chk.occupied == playerNumber) { connected = true; break; } else if (visited.Contains(chk)) { continue; } for (int x = 0; x < chk.edges.Length; x++) { if (counties[chk.edges[x]].occupied == playerNumber) DFSstack.Push(counties[chk.edges[x]]); } visited.Add(chk); } if (sourceCounty.occupied != playerNumber) { gpWindow = new TextWindow(new String[] { "SOURCE COUNTY NOT YOURS" }, Content, new Vector2(25, 25), new Vector2(500, 25)); okayButton = new Menu(new Vector2(700, 25), new string[] { "OK" }, new Menu.menuAction[] { cancelTroopMove }, 1, 1, "test-semifont.png", Content); return; } else if (targetCounty.occupied != playerNumber) { gpWindow = new TextWindow(new String[] { "RECIPIENT COUNTY NOT YOURS" }, Content, new Vector2(25, 25), new Vector2(500, 25)); okayButton = new Menu(new Vector2(700, 25), new string[] { "OK" }, new Menu.menuAction[] { cancelTroopMove }, 1, 1, "test-semifont.png", Content); return; } else if (targetCounty == sourceCounty) { gpWindow = new TextWindow(new String[] { "THAT IS POINTLESS" }, Content, new Vector2(25, 25), new Vector2(500, 25)); okayButton = new Menu(new Vector2(700, 25), new string[] { "OK" }, new Menu.menuAction[] { cancelTroopMove }, 1, 1, "test-semifont.png", Content); return; } else if (!connected) { gpWindow = new TextWindow(new String[] { "NO ROUTE FROM SOURCE TO RECIPIENT" }, Content, new Vector2(25, 25), new Vector2(500, 25)); okayButton = new Menu(new Vector2(700, 25), new string[] { "OK" }, new Menu.menuAction[] { cancelTroopMove }, 1, 1, "test-semifont.png", Content); return; } else if (playerFunds - 90 < 0) { gpWindow = new TextWindow(new String[] { "NOT ENOUGH FUNDS REQUIRED: 90" }, Content, new Vector2(25, 25), new Vector2(650, 25)); okayButton = new Menu(new Vector2(700, 25), new string[] { "OK" }, new Menu.menuAction[] { cancelTroopMove }, 1, 1, "test-semifont.png", Content); return; } selectingForTroopTransfer = 3; gpWindow = new TextWindow(new string[] { "MOVE " + (sourceCounty.troops/3) + " FROM " + sourceCounty.name.ToUpper() + " TO " + targetCounty.name.ToUpper() + "\\n" + "COST: 90"}, Content, new Vector2(25, 25), new Vector2(650, 50)); actionMenu = new Menu( new Vector2(100, 100), new string[] { "YES", "NO" }, new Menu.menuAction[] { moveTroops, cancelTroopMove }, 2, 1, "test-semifont.png", Content); } else if (selectingForRecruitment) { sourceCounty = individualCounty; int playerFunds = funds; if (playerNumber == 2) playerFunds = unionFunds; if (sourceCounty.occupied != playerNumber) { gpWindow = new TextWindow(new String[] { "COUNTY NOT YOURS" }, Content, new Vector2(25, 25), new Vector2(500, 25)); okayButton = new Menu(new Vector2(700, 25), new string[] { "OK" }, new Menu.menuAction[] { cancelRecruit }, 1, 1, "test-semifont.png", Content); return; } else if (playerFunds - 30 < 0) { gpWindow = new TextWindow(new String[] { "NOT ENOUGH FUNDS REQUIRED: 30" }, Content, new Vector2(25, 25), new Vector2(650, 25)); okayButton = new Menu(new Vector2(700, 25), new string[] { "OK" }, new Menu.menuAction[] { cancelRecruit }, 1, 1, "test-semifont.png", Content); return; } int cost = 30; gpWindow = new TextWindow(new string[] { "RECRUIT TROOPS IN " + sourceCounty.name.ToUpper() + "\\nCOST: " + cost }, Content, new Vector2(25, 25), new Vector2(500, 50)); actionMenu = new Menu( new Vector2(100, 100), new string[] { "YES", "NO" }, new Menu.menuAction[] { recruitTroops, cancelRecruit }, 2, 1, "test-semifont.png", Content); } } } }
public County UpdateCounty(County county, string name, Enums.Provinces province) { County cty = context.Counties .Where(c => c == county) .FirstOrDefault(); if (cty != null) { cty.Name = name; cty.Province = province.ToString(); context.SaveChanges(); return cty; } else { return null; } }
///<summary>Updates one County in the database. Uses an old object to compare to, and only alters changed fields. This prevents collisions and concurrency problems in heavily used tables.</summary> internal static void Update(County county,County oldCounty) { string command=""; if(county.CountyName != oldCounty.CountyName) { if(command!=""){ command+=",";} command+="CountyName = '"+POut.String(county.CountyName)+"'"; } if(county.CountyCode != oldCounty.CountyCode) { if(command!=""){ command+=",";} command+="CountyCode = '"+POut.String(county.CountyCode)+"'"; } if(command==""){ return; } command="UPDATE county SET "+command +" WHERE CountyNum = "+POut.Long(county.CountyNum); Db.NonQ(command); }
public void selectStartingCounty() { beginningMenu = null; if (individualCounty.occupied == 0) { takeCounty(individualCounty, beginningSelector); } else { cancelStartingCounty(); return; } if (multiPlayer && beginningSelector != 2) { beginningSelector = 2; beginningTextWindow = new TextWindow(new String[] { playerNames[2] + " SELECT A COUNTY" }, Content, new Vector2(25, 25), new Vector2(500, 25)); } else if (multiPlayer && beginningSelector == 2) { playerNumber = 1; beginning = false; beginningTextWindow = null; beginningMenu = null; individualCounty = null; icTextWindow = null; startWeek(); } else { beginning = false; beginningTextWindow = null; beginningMenu = null; individualCounty = null; icTextWindow = null; int oCo = 0; while (oCo != 1) { Random ra = new Random(); int toFill = ra.Next(0, counties.Length); if (counties[toFill].occupied == 0) { takeCounty(counties[toFill], 2); counties[toFill].occupied = 2; oCo++; } } startWeek(); } return; }