public async Task <IActionResult> Get([FromBody] CoordinatesDto credentials) { ServiceResponse <List <Dictionary <string, string> > > response = await nurseService.getNurses(credentials); if (response.Data.Count != 0) { return(Ok(response)); } return(BadRequest(response)); }
public StepResultDto MakeStep(StepDto newStep) { var game = _dbContext.Set <Game>() .Where(x => x.Id == newStep.GameId) .Include(x => x.Steps) .First(); var tickTackToeGame = new TickTackToeGame(game.Steps); tickTackToeGame.MakeStep(newStep.Coordinates.X, newStep.Coordinates.Y, game.UserPlayerType); var winnerDto = tickTackToeGame.TryGetWinner(); var step = new Step() { GameId = game.Id, Player = game.UserPlayerType, X = newStep.Coordinates.X, Y = newStep.Coordinates.Y, }; _dbContext.Add(step); CoordinatesDto newStepCoordinates = null; if (winnerDto.Winner == null && !winnerDto.IsDraw) { var botPlayerType = game.UserPlayerType == PlayerType.X ? PlayerType.O : PlayerType.X; newStepCoordinates = tickTackToeGame.MakeBotStep(botPlayerType); winnerDto = tickTackToeGame.TryGetWinner(); var botStep = new Step() { GameId = game.Id, Player = botPlayerType, X = newStepCoordinates.X, Y = newStepCoordinates.Y, }; _dbContext.Add(botStep); } game.Winner = winnerDto.Winner; game.IsFinished = winnerDto.Winner != null || winnerDto.IsDraw; _dbContext.SaveChanges(); return(new StepResultDto { Winner = winnerDto.Winner, BotStep = newStepCoordinates, IsFinished = game.IsFinished }); }
// GET api/values public IEnumerable <BirdObserverDto> Put(CoordinatesDto coordinates) { string json = ""; try { using (WebClient wc = new WebClient()) { string url = String.Format("http://ebird.org/ws1.1/data/obs/geo/recent?lng={0}&lat={1}&fmt=json", coordinates.longitude.ToString(), coordinates.latitude.ToString()); json = wc.DownloadString(url); JArray birdObserverArray = JArray.Parse(json); IList <BirdObserverDto> birdObserverDto = new List <BirdObserverDto>(); try { IList <BirdObserver> birdObservers = birdObserverArray.Select(bo => new BirdObserver { Name = (string)bo["comName"], ScientificName = (string)bo["sciName"], Location = (string)bo["locName"], NumberSpotted = ConvertToInt((string)bo["howMany"]), DateObserved = (DateTime)bo["obsDt"], Latitude = (double)bo["lat"], Longitude = (double)bo["lng"] }).ToList(); foreach (BirdObserver bo in birdObservers) { var boDto = Mapper.Map <BirdObserver, BirdObserverDto>(bo); birdObserverDto.Add(boDto); _context.BirdObservers.Add(bo); } _context.SaveChanges(); //now do a save to the Database } catch (Exception e) { string msg = e.InnerException.Message; } return(birdObserverDto); } } catch (Exception e) { string taz = e.InnerException.ToString(); } return(null); }
public StepDto StartGame() { var openGamesCount = _dbContext .Set <Game>() .Where(x => !x.IsFinished) .Count(); if (openGamesCount >= 3) { throw new Exception("Too many game sessions"); } var userPlayerType = (PlayerType) new Random().Next(0, 2); var game = new Game { UserPlayerType = userPlayerType, }; CoordinatesDto newStepCoordinates = null; if (userPlayerType == PlayerType.O) { var tickTackToeGame = new TickTackToeGame(); newStepCoordinates = tickTackToeGame.MakeBotStep(PlayerType.X); var step = new Step() { Player = PlayerType.X, X = newStepCoordinates.X, Y = newStepCoordinates.Y, }; game.Steps = new List <Step>() { step }; } _dbContext.Add(game); _dbContext.SaveChanges(); return(new StepDto { GameId = game.Id, Coordinates = newStepCoordinates }); }
public async Task <List <Dictionary <string, string> > > getNurses(CoordinatesDto credentials) { conn.Open(); string sql = "select id, fullName, location from nurse"; MySqlCommand cmd = new MySqlCommand(sql, conn); MySqlDataReader result = await Task.Run(() => { return(cmd.ExecuteReader()); }); List <Dictionary <string, string> > nurses = new List <Dictionary <string, string> >(); Dictionary <string, string> nurse; while (result.Read()) { string locationJson = result.GetString(2); Location startingLocation = new Location(credentials.Latitude, credentials.Longitude); CoordinatesDto nurseLocation = JsonSerializer.Deserialize <CoordinatesDto>(locationJson); Location destinationLocation = new Location(nurseLocation.Latitude, nurseLocation.Longitude); double distance = this.getDistance(startingLocation, destinationLocation); if (distance <= 100000) {// less than 100km string nurseAddress = this.getFormattedAddress(destinationLocation); string distanceKm = String.Format("{0:0.00}km", (distance / 1000)); nurse = new Dictionary <string, string>(); nurse.Add("id", result.GetInt32(0).ToString()); nurse.Add("name", result.GetString(1)); nurse.Add("location", nurseAddress); nurse.Add("distance", distanceKm); nurses.Add(nurse); } } conn.Close(); return(nurses); }
public IHttpActionResult Create([FromBody] CoordinatesDto coordsDto) { if (coordsDto == null) { return(BadRequest("Не передан необходимый параметр.")); } try { var coords = Mapper.Map <Coordinates>(coordsDto); var count = _rep.PutAsync(coords).Result; Logger.Trace("Добавлены координаты."); return(Ok(count)); } catch (Exception ex) { Logger.Error("Ошибка добавления координат.", ex); return(InternalServerError()); } }
public async Task <ServiceResponse <List <Dictionary <string, string> > > > getNurses(CoordinatesDto credentials) { List <Dictionary <string, string> > nurses = await nurseDAO.getNurses(credentials); ServiceResponse <List <Dictionary <string, string> > > response = new ServiceResponse <List <Dictionary <string, string> > >(); if (nurses.Count != 0) { response.Data = nurses; response.Message = "Nurses retrieved succesfully!"; } else { response.Message = "Error retrieving nurses!"; response.Success = false; } return(response); }
/// <summary> /// Реализует выполнение работы по имитации действий пользователей. /// </summary> /// <param name="userName">Имя пользователя.</param> /// <param name="baseAdress">Адрес сервиса.</param> /// <param name="startDate">Дата добавления координат, из команды.</param> private void Work(int userName, string baseAdress, DateTime startDate) { try { UserDto user; // Используем протобуф для четных пользователей. var useProtobuf = (userName % 2) == 0; using (var client = new HttpClient()) { if (useProtobuf) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf")); } var createQquery = string.Format(_queryFormat, userName); client.BaseAddress = new Uri(new Uri(baseAdress), createQquery); var response = client.GetAsync(client.BaseAddress).Result; if (!response.IsSuccessStatusCode) { return; } var data = response.Content.ReadAsAsync(_returnType, new MediaTypeFormatter[] { FormatterFactory.CreateJsonFormatter(), FormatterFactory.CreateProtoBufFormatter() }).Result; user = (UserDto)data; Console.WriteLine(user); Logger.Trace(user.ToString()); } var token = AuthClient.GetToken(baseAdress, user.Name, user.Password).Result; // Случайные числа для координат. var random = new Random(user.Name); var lat = random.NextDouble(); var lng = random.NextDouble(); while (true) { var parameters = new CoordinatesDto { Date = startDate, Latitude = (decimal)((lat - random.NextDouble()) * 90), Longtitude = (decimal)((lng - random.NextDouble()) * 180), UserId = user.Id }; using (var client = new HttpClient()) { if (useProtobuf) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf")); } client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); client.BaseAddress = new Uri(new Uri(baseAdress), _coordsPutFormat); var response = client.PutAsync(client.BaseAddress, parameters, useProtobuf ? (MediaTypeFormatter)FormatterFactory.CreateProtoBufFormatter() : FormatterFactory.CreateJsonFormatter()).Result; if (!response.IsSuccessStatusCode) { return; } var data = response.Content.ReadAsAsync(_coordsReturnType, new MediaTypeFormatter[] { FormatterFactory.CreateJsonFormatter(), FormatterFactory.CreateProtoBufFormatter() }).Result; if ((int)data == 1) { var message = string.Format("Добавлена запись координат, пользователь {0}.", userName); #if DEBUG Console.WriteLine(message); #endif Logger.Trace(message); } } Thread.Sleep(1000); } } catch (ThreadAbortException) {} catch (AggregateException ex) { Console.WriteLine(ex.InnerException.Message); Logger.Error("Ошибка имитации.", ex.InnerException); } catch (Exception ex) { Console.WriteLine(ex.Message); Logger.Error("Ошибка имитации.", ex); } }
private CoordinatesDto GetWinCoords(PlayerType player) { for (int i = 0; i < 3; i++) { bool xFilled = true; bool yFilled = true; CoordinatesDto xEmptyCell = null; CoordinatesDto yEmptyCell = null; for (int j = 0; j < 3; j++) { xFilled = xFilled && ((xEmptyCell == null && Matrix[i, j] == null) || Matrix[i, j] == player); if (Matrix[i, j] == null) { xEmptyCell = new CoordinatesDto { X = i, Y = j }; } yFilled = yFilled && ((yEmptyCell == null && Matrix[j, i] == null) || Matrix[j, i] == player); if (Matrix[j, i] == null) { yEmptyCell = new CoordinatesDto { X = j, Y = i }; } if (j == 2) { if (xFilled) { return(xEmptyCell); } if (yFilled) { return(yEmptyCell); } } } } bool xDiagFilled = true; bool yDiagFilled = true; CoordinatesDto xDiagEmptyCell = null; CoordinatesDto yDiagEmptyCell = null; for (int i = 0; i < 3; i++) { xDiagFilled = xDiagFilled && ((xDiagEmptyCell == null && Matrix[i, i] == null) || Matrix[i, i] == player); if (Matrix[i, i] == null) { xDiagEmptyCell = new CoordinatesDto { X = i, Y = i }; } yDiagFilled = yDiagFilled && ((yDiagEmptyCell == null && Matrix[i, 2 - i] == null) || Matrix[i, 2 - i] == player); if (Matrix[i, 2 - i] == null) { yDiagEmptyCell = new CoordinatesDto { X = i, Y = 2 - i }; } if (i == 2) { if (xDiagFilled) { return(xDiagEmptyCell); } if (yDiagFilled) { return(yDiagEmptyCell); } } } return(null); }