Example #1
0
 public void AddStop(StopViewModel stop)
 {
     using (var DB = new BusTicketsContext())
     {
         var addStop = DB.Stops.Add(new Stop {
             Name = stop.Name, Description = stop.Description, Status = stop.Status
         });
         DB.SaveChanges();
     }
 }
Example #2
0
        public Stop()
        {
            InitializeComponent();

            // Create Page View Model
            PageViewModel = new StopViewModel(App.SelectedStopInfo, this);

            // Set Data Context
            DataContext = PageViewModel;
        }
Example #3
0
 public void SetRouteDataSource(DataSource routeDataSource)
 {
     if (_routeDataSource != routeDataSource)
     {
         StopViewModel vm = DataGridViewModel as StopViewModel;
         vm.SetRouteDataSource(routeDataSource);
         vm.RoutesRouteNameFieldName = RoutesRouteNameFieldName;
         _routeDataSource            = routeDataSource;
     }
 }
        public StopPage(StopViewModel StopViewModel)
        {
            InitializeComponent();
            this.StopViewModel = StopViewModel;
            BindingContext     = StopViewModel;
            ISimpleAudioPlayer player     = CrossSimpleAudioPlayer.Current;
            WebClient          wc         = new WebClient();
            Stream             fileStream = wc.OpenRead(StopViewModel.AudioUri);

            player.Load(fileStream);
        }
Example #5
0
        private void OnExpanderDrop(object sender, DragEventArgs e)
        {
            StopViewModel stopVM = DataGridViewModel as StopViewModel;

            if (stopVM == null)
            {
                return;
            }
            if (_dragRowIndex < 0)
            {
                return;
            }
            //Schema.Item dragStop = e.Data.GetData(typeof(Schema.Item)) as Schema.Item;
            AddInsShare.Schema.Item dragStop = dgStops.Items[_dragRowIndex] as AddInsShare.Schema.Item;
            if (dragStop == null)
            {
                return;
            }

            // dropped on a Group?
            String routeName = GetDroppedOnGroupRouteName(e);

            if (routeName != null)
            {
                Log.Trace("Dropped item " + _dragRowIndex + " on group " + routeName);
                stopVM.CalculateRoute(dragStop, null, routeName, true, Window.GetWindow(this));
                return;
            }

            // dropped on an Item?
            int dropIndex = this.GetDataGridItemCurrentRowIndex(e.GetPosition);

            if (dropIndex < 0)
            {
                return;
            }
            if (dropIndex == _dragRowIndex)
            {
                return;
            }
            Log.Trace("Dropped item " + _dragRowIndex + " on item " + dropIndex);

            AddInsShare.Schema.Item dropStop = dgStops.Items[dropIndex] as AddInsShare.Schema.Item;
            if (dropStop == null)
            {
                return;
            }

            // Temp workaround - use the ALT key to drop onto the group (optimize == true)
            bool bOptimize = (e.KeyStates == DragDropKeyStates.AltKey);

            stopVM.CalculateRoute(dragStop, dropStop, null, bOptimize, Window.GetWindow(this));
        }
 public static StopViewModel Create(this IModelFactory factory, Stop model)
 {
     var stop = new StopViewModel
     {
         Id = model.Id,
         Name = model.Name,
         Arrival = model.Arrival,
         Longitude = model.Longitude,
         Latitude = model.Latitude
     };
     return stop;
 }
Example #7
0
 private void SetStopDataSource(DataSource stopDataSource)
 {
     if (_stopDataSource != stopDataSource)
     {
         StopViewModel vm = DataGridViewModel as StopViewModel;
         vm.SetDataSource(stopDataSource);
         vm.TrackIdFieldName        = TrackIdFieldName;
         vm.GroupByFieldName        = GroupByFieldName;
         vm.SortByFieldName1        = SortByFieldName1;
         vm.SortByFieldName2        = SortByFieldName2;
         vm.StopsRouteNameFieldName = StopsRouteNameFieldName;
         _stopDataSource            = stopDataSource;
     }
 }
Example #8
0
        private void buttonLoadPlan_Click_1(object sender, RoutedEventArgs e)
        {
            StopViewModel stopVM = DataGridViewModel as StopViewModel;

            if (stopVM == null)
            {
                return;
            }

            LoadPlanWindow loadPlanWindow = new LoadPlanWindow(stopVM);

            loadPlanWindow.Owner = Window.GetWindow(this);
            loadPlanWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            loadPlanWindow.ShowDialog();
        }
Example #9
0
        private void buttonToggleEdit_Click_1(object sender, RoutedEventArgs e)
        {
            StopViewModel stopVM = (DataGridViewModel as StopViewModel);

            if (stopVM.InEditMode)
            {
                stopVM.StopEditMode();
            }
            else
            {
                stopVM.StartEditMode();
            }

            UpdateButtonsState();
        }
Example #10
0
        public async Task <JsonResult> Post(int tripId, [FromBody] StopViewModel stopVM)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var        stop   = Mapper.Map <Stop>(stopVM);
                    string     URI    = "http://maps.google.com/maps/api/geocode/json?address=" + stop.Name + "&sensor=false";
                    HttpClient client = new HttpClient();

                    var response = await client.GetAsync(URI);

                    var responseContent = response.Content;
                    var jsonGeo         = await responseContent.ReadAsStringAsync();

                    _repo.GetTripWithStopsByTripId(tripId, User.Identity.Name).Destinations.Add(stop);

                    var json = new JsonResult(jsonGeo);
                    var obj  = JObject.Parse(jsonGeo);
                    var lat  = FindJObject(obj.Children(), "results[0].geometry.location.lat");
                    var lng  = FindJObject(obj.Children(), "results[0].geometry.location.lng");
                    if (lat != null && lng != null)
                    {
                        stop.Latitude  = lat.Values <double>().First();
                        stop.Longitude = lng.Values <double>().First();
                    }
                    if (_repo.SaveAll())
                    {
                        Response.StatusCode = StatusCodes.Status200OK;
                        return(Json(Mapper.Map <StopViewModel>(stop)));
                    }
                    else
                    {
                        Response.StatusCode = StatusCodes.Status500InternalServerError;
                        return(Json(false));
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError(e.Message);
                    return(Json(e));
                }
            }
            else
            {
                return(Json(new { error = ModelState }));
            }
        }
Example #11
0
        private void buttonClearPlan_Click_1(object sender, RoutedEventArgs e)
        {
            StopViewModel stopVM = DataGridViewModel as StopViewModel;

            if (stopVM == null)
            {
                return;
            }

            MessageBoxResult confirmation = System.Windows.MessageBox.Show("Are you sure you would like to clear the plan?", "Clear Plan", MessageBoxButton.YesNo);

            if (confirmation == MessageBoxResult.Yes)
            {
                stopVM.ClearPlan();
            }
        }
Example #12
0
        protected StopViewModel FindNearestStop(LatLng initialLocation, IEnumerable <StopViewModel> stops)
        {
            StopViewModel minStop     = stops.First();
            double        minDistance = DistanceBetween(initialLocation, minStop.LatLng);

            foreach (var currentStop in stops)
            {
                double currentDistance = DistanceBetween(initialLocation, currentStop.LatLng);
                if (currentDistance < minDistance)
                {
                    minStop     = currentStop;
                    minDistance = currentDistance;
                }
            }

            return(minStop);
        }
Example #13
0
        public async Task <JsonResult> Post(string tripName, [FromBody] StopViewModel vm)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // map to entity
                    var newStop = Startup.Mapper.Map <Stop>(vm);

                    // lookup geos
                    var coordResult = await this.coordService.Lookup(newStop.Name);

                    if (!coordResult.Success)
                    {
                        Response.StatusCode = (int)HttpStatusCode.BadRequest;
                        return(Json(coordResult));
                    }

                    newStop.Longitude = coordResult.Longitude;
                    newStop.Latitude  = coordResult.Latitude;

                    // save to db
                    var userName = User.Identity.Name;
                    repo.AddStop(tripName, userName, newStop);

                    if (repo.SaveAll())
                    {
                        Response.StatusCode = (int)HttpStatusCode.OK;
                        return(Json(Startup.Mapper.Map <StopViewModel>(newStop)));
                    }
                }
                else
                {
                }
            }
            catch (Exception ex)
            {
                logger.LogError("Failed to save new stop");
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json("Failed to save new Stop"));
            }

            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return(Json("Validation failed on new Stop"));
        }
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo info)
        {
            // value to Visibility
            StopViewModel vm = value as StopViewModel;

            if (vm == null)
            {
                return(Visibility.Collapsed);
            }

            Item item = vm.CutStop as Item;

            if (item == null)
            {
                return(Visibility.Collapsed);
            }

            return(Visibility.Visible);
        }
        public ActionResult Index(StopViewModel sm)
        {
            if (ModelState.IsValid)
            {
                string[] From = sm.stop_latlonFrom.Split('_');
                string[] To   = sm.stop_latlonTo.Split('_');
                double   latF = Convert.ToDouble(From[0]);
                double   lonF = Convert.ToDouble(From[1]);
                double   latT = Convert.ToDouble(To[0]);
                double   lonT = Convert.ToDouble(To[1]);
                ViewBag.distance = "The distance is " + DistanceAlgorithm.DistanceBetweenPlaces(lonF, latF, lonT, latT).ToString("0.00") + " Kilometres.";

                return(View(sm));
            }
            else
            {
                return(RedirectToAction("Index"));
            }
        }
      public async Task <JsonResult> Post(string tripName, [FromBody] StopViewModel vm)
      {
          try
          {
              if (ModelState.IsValid)
              {
                  //map to entity
                  var newStop = AutoMapper.Mapper.Map <Stop>(vm);

                  //look up geocoordinates
                  var coordResult = await _coordService.Lookup(newStop.Name);


                  if (!coordResult.Success)
                  {
                      Response.StatusCode = (int)HttpStatusCode.BadRequest;

                      return(Json(coordResult.Message));
                  }

                  newStop.Longitude = coordResult.Longitude;
                  newStop.Latitude  = coordResult.Latitude;
                  //save to db
                  _repository.AddStop(tripName, newStop, User.Identity.Name);

                  if (_repository.SaveAll())
                  {
                      Response.StatusCode = (int)(int)HttpStatusCode.Created;

                      return(Json(AutoMapper.Mapper.Map <StopViewModel>(newStop)));
                  }
              }
          }
          catch (Exception e)
          {
              _logger.LogError($"Failed to save new stop", e);
              Response.StatusCode = (int)HttpStatusCode.BadRequest;
              return(Json("Failed to save new stop"));
          }

          Response.StatusCode = (int)HttpStatusCode.BadRequest;
          return(Json("Validation Failed on new stop"));
      }
Example #17
0
        public async Task <IActionResult> Create(string tripName, [FromBody] StopViewModel vm)
        {
            try
            {
                // If the VM is valid
                if (ModelState.IsValid)
                {
                    var newStop = Mapper.Map <Stop>(vm);

                    // Lookup the Geocodes
                    var result = await _coordsService.GetCoordsAsync(newStop.Name);

                    if (!result.Success)
                    {
                        _logger.LogError(result.Message);
                    }
                    else
                    {
                        newStop.Latitude  = result.Latitude;
                        newStop.Longitude = result.Longitude;

                        // Save to the Database
                        _repository.AddStop(tripName, newStop);

                        if (await _repository.SaveChangesAsync())
                        {
                            return(Created($"/api/trips/{tripName}/stops/{newStop.Name}",
                                           Mapper.Map <StopViewModel>(newStop)));
                        }
                    }
                }
                else
                {
                    return(BadRequest("Model state not valid"));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Failed to save new Stop: {0}", ex);
            }

            return(BadRequest("Failed to save new stop"));
        }
Example #18
0
        public async Task <IActionResult> Post(string tripName, [FromBody] StopViewModel vm)
        {
            try
            {
                // If the VM is valid
                if (vm.Arrival > DateTime.Now)
                {
                    ModelState.AddModelError("", "This date didn't become!");
                }
                if (ModelState.IsValid)
                {
                    var newStop = Mapper.Map <Stop>(vm);

                    //Lookup the Geocodes
                    var result = await _coordService.GetCoordsAsync(newStop.Name);

                    if (!result.Success)
                    {
                        _logger.LogError($"Failed to get coords: {result.Message}");
                    }
                    else
                    {
                        newStop.Latitude  = result.Latitude;
                        newStop.Longitude = result.Longitude;

                        // Save to the Database
                        _repository.AddStop(tripName, newStop, User.Identity.Name);

                        if (await _repository.SaveChangesAsync())
                        {
                            return(Created($"/api/trips/{tripName}/stops/{newStop.Name}", Mapper.Map <StopViewModel>(newStop)));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Error occured while POST: {ex}");
            }

            return(BadRequest($"Error occured while POST:"));
        }
Example #19
0
        private StopViewModel SetViewModel(string NameOfStop, SortState sortState, int page = 1)
        {
            IEnumerable <Stop> stops = railroadContext.Stops;

            stops = SortSearch(stops, sortState, NameOfStop ?? "");
            int pageSize = 10;
            int count    = stops.Count();

            stops = stops.Skip((page - 1) * pageSize).Take(pageSize).ToList();
            PageViewModel pageViewModel = new PageViewModel(count, page, pageSize);
            StopViewModel viewModel     = new StopViewModel
            {
                Stops         = stops,
                PageViewModel = pageViewModel,
                NameOfStop    = NameOfStop,
                SortViewModel = new SortViewModel(sortState)
            };

            return(viewModel);
        }
Example #20
0
        public async Task <IActionResult> Post(string tripName, [FromBody] StopViewModel vm)
        {
            try
            {
                Console.WriteLine($"************MODEL STATE - {ModelState.IsValid}*******");
                // If the VM is valid
                if (ModelState.IsValid)
                {
                    var newStop = Mapper.Map <Stop>(vm);
                    Console.WriteLine($"STOP NAME -{newStop.Name}*******");
                    // Lookup the Geocodes
                    var result = await _coordsService.GetCoordsAsync(newStop.Name);

                    Console.WriteLine($"******result sc - {result.Success} lat {result.Latitude} long {result.Longitude}***");
                    if (!result.Success)
                    {
                        _logger.LogError(result.Message);
                    }
                    else
                    {
                        newStop.Latitude  = result.Latitude;
                        newStop.Longitude = result.Longitude;

                        // Save to the Database
                        _repository.AddStop(tripName, User.Identity.Name, newStop);

                        if (await _repository.SaveChangesAsync())
                        {
                            return(Created($"/api/trips/{tripName}/stops/{newStop.Name}",
                                           Mapper.Map <StopViewModel>(newStop)));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Failed to save new Stop: {0}", ex);
            }

            return(BadRequest("Failed to save new stop"));
        }
        public async Task <IActionResult> Delete(string trackingNumber, [FromBody] StopViewModel vm)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _repository.deleteStop(trackingNumber, vm.Location, vm.Activity);

                    if (await _repository.SaveChangesAsync())
                    {
                        return(Ok("Successfully Deleted"));
                    }
                }
            }
            catch (Exception ex)
            {
                return(BadRequest("Unable to delete: " + ex));
            }

            return(BadRequest("Failed to delete stop"));
        }
Example #22
0
        private void UpdateButtonsState()
        {
            StopViewModel stopVM      = (DataGridViewModel as StopViewModel);
            bool          bInEditMode = stopVM.InEditMode;

            buttonSaveEdits.IsEnabled = bInEditMode;
            dgStops.AllowDrop         = bInEditMode;
            buttonLoadPlan.IsEnabled  = !bInEditMode;
            buttonClearPlan.IsEnabled = !bInEditMode;

            if (bInEditMode)
            {
                buttonToggleEdit.Content = "Cancel Edits";
                dgStops.RowStyle         = (Style)FindResource("dgRowStyleInEditMode");
            }
            else
            {
                buttonToggleEdit.Content = "Start Edit";
                dgStops.RowStyle         = (Style)FindResource("dgRowStyle");
            }
        }
Example #23
0
        public ActionResult ReserveTransporter()
        {
            var form  = Request.Form;
            var model = new TransporterReservationViewModel();

            model.Id   = Convert.ToInt32(form["transporterId"]);
            model.From = new PlaceViewModel()
            {
                Id = form["fromId"], Name = WebUtility.HtmlDecode(WebUtility.HtmlDecode(form["fromName"])), Lat = form["fromLat"], Lng = form["fromLng"]
            };
            model.To = new PlaceViewModel()
            {
                Id = form["toId"], Name = WebUtility.HtmlDecode(WebUtility.HtmlDecode(form["toName"])), Lat = form["toLat"], Lng = form["toLng"]
            };
            string json = form["Stops"];

            if (!string.IsNullOrEmpty(json))
            {
                var jarr = JArray.Parse(json);
                for (int i = 0; i < jarr.Count; i++)
                {
                    var jobj = jarr[i] as JObject;
                    var stop = new StopViewModel()
                    {
                        Sort  = Convert.ToInt32(jobj["stopSort"].ToString()),
                        Place = new PlaceViewModel()
                        {
                            Id = jobj["placeId"].ToString(), Name = jobj["placeName"].ToString()
                        },
                        PassengerCountGetOn  = Convert.ToInt32(jobj["passengerCountGetOn"].ToString()),
                        PassengerCountGetOff = Convert.ToInt32(jobj["passengerCountGetOff"].ToString())
                    };
                    model.Stops.Add(stop);
                }
            }
            TempData["model"] = model;

            return(RedirectToAction("PurchaseBill"));
        }
Example #24
0
        public async Task <IActionResult> Post(string tripName, [FromBody] StopViewModel vm)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var newstop = Mapper.Map <Stop>(vm);

                    _repos.AddStop(tripName, newstop);
                    if (await _repos.SaveChangesAsync())
                    {
                        return(Created($"api/trips/{tripName}/stops/{newstop.Name}",
                                       Mapper.Map <StopViewModel>(newstop)));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Fail to save stop {ex}");
            }
            return(BadRequest($"Fail to add a stop to {tripName}"));
        }
Example #25
0
        public async Task <IActionResult> Post(string tripName, [FromBody] StopViewModel vm)
        {
            try
            {
                // If the VM is valid
                if (ModelState.IsValid)
                {
                    var newStop = Mapper.Map <Stop>(vm);

                    //lookup GeoCode
                    var result = await _geoCordService.GetGeoCord(newStop.Name);

                    if (!result.Success)
                    {
                        _logger.LogError("Failed to get Geo Cordinate");
                    }
                    else
                    {
                        newStop.Longitude = result.Longitude;
                        newStop.Latitude  = result.Latitude;

                        //Save to DB
                        _repository.AddStop(tripName, User.Identity.Name, newStop);

                        if (await _repository.SaveChangesAsync())
                        {
                            return(Created($"/api/trips/{tripName}/stops/{newStop.Name}",
                                           Mapper.Map <StopViewModel>(newStop)));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Failed to save stop {ex.Message}");
            }

            return(BadRequest("Failed to save stop"));
        }
        public async Task <JsonResult> Post(string tripName, [FromBody] StopViewModel vm)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var newStop = Mapper.Map <Stop>(vm);


                    var coordinateResult = await _coordinateService.Lookup(newStop.Name);

                    if (!coordinateResult.Success)
                    {
                        Response.StatusCode = (int)HttpStatusCode.NotFound;
                        return(Json($"Couldn't locate the city, Message: {coordinateResult.Message}"));
                    }

                    newStop.Longitude = coordinateResult.Longitude;
                    newStop.Latitude  = coordinateResult.Latitude;

                    _repository.AddStop(newStop, User.Identity.Name, tripName);
                    if (_repository.SaveAll())
                    {
                        Response.StatusCode = (int)HttpStatusCode.Created;
                        return(Json(Mapper.Map <StopViewModel>(newStop)));
                    }

                    return(Json(null));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Failed to save the new stop", ex);
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json("Failboat"));
            }
            return(Json(null));
        }
Example #27
0
        public async Task <IActionResult> Post(string tripName, [FromBody] StopViewModel vm)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var newStop = Mapper.Map <Stop>(vm);

                    //looking the geocode
                    var result = await _coordsService.GeoCoordsAsync(newStop.Name);

                    if (!result.Success)
                    {
                        _logger.LogError(result.Message);
                    }
                    else
                    {
                        newStop.Latitude  = result.Latitude;
                        newStop.Longitude = result.Longitude;


                        //saving to database
                        _repository.AddStop(tripName, newStop, User.Identity.Name);

                        if (await _repository.SaveChangesAsync())
                        {
                            return(Created($"/api/trips/{tripName}/Stops/{newStop.Name}",
                                           Mapper.Map <StopViewModel>(newStop)));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Failed to get stops: {0}", ex);
            }
            return(BadRequest());
        }
        public async Task <JsonResult> Post(string tripName, [FromBody] StopViewModel vm)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    //Map top Entity
                    var newStop = Mapper.Map <Stop>(vm);

                    //LookingUp Coordinates
                    var coordResult = await _coordService.Lookup(newStop.Name);

                    if (!coordResult.Success)
                    {
                        Response.StatusCode = (int)HttpStatusCode.BadRequest;
                        Json(coordResult.Message);
                    }

                    newStop.Longitude = coordResult.Longitude;
                    newStop.Latitude  = coordResult.Latitude;

                    //save to database
                    _repository.AddStop(tripName, newStop);
                    if (_repository.SaveAll())
                    {
                        Response.StatusCode = (int)HttpStatusCode.Created;
                        return(Json(Mapper.Map <StopViewModel>(newStop)));
                    }
                }
                return(Json(null));
            }
            catch (Exception ex)
            {
                _logger.LogError("Failed to add new stop", ex);
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(ex.ToString()));
            }
        }
Example #29
0
        public StopService(Stop stopModel, AppShell appShell, MapService mapService, LocationChecker locationChecker, GameService gameService)
        {
            Model           = stopModel;
            Model.Service   = this;
            ViewModel       = new StopViewModel(appShell, Model.Name);
            MapService      = mapService;
            LocationChecker = locationChecker;
            GameService     = gameService;
            if (Model.Position != null)
            {
                IsVisibleInState2 = Model.Position.IsVisibleAsStopPosition;
            }

            State = 0;
            if ((bool)Model.IsInitial)
            {
                SetAsVisible();
            }
            else
            {
                SetAsUnvisible();
            }
        }
        public async Task <IActionResult> Post(string trackingNumber, [FromBody] StopViewModel vm)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var newStop = Mapper.Map <Stop>(vm);

                    //save to db
                    _repository.AddStops(trackingNumber, newStop);

                    if (await _repository.SaveChangesAsync())
                    {
                        return(Created($"/api/trips/{trackingNumber}/stops/{newStop.Location}", Mapper.Map <StopViewModel>(newStop)));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Failed to save new stop information: {0}", ex);
            }
            return(BadRequest("Failed to save new stop information"));
        }
        public async Task <JsonResult> Post(string tripName, [FromBody] StopViewModel viewModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var newStop = Mapper.Map <Stop>(viewModel);

                    var geo = await _geoService.Lookup(viewModel.Name);

                    if (!geo.Success)
                    {
                        Response.StatusCode = (int)HttpStatusCode.BadRequest;
                        return(Json(geo.Message));
                    }

                    newStop.Latitude  = geo.Latitude;
                    newStop.Longitude = geo.Longitude;

                    _repo.AddStop(tripName, newStop, User.Identity.Name);

                    if (_repo.SaveAll())
                    {
                        Response.StatusCode = ( int )HttpStatusCode.Created;
                        return(Json(Mapper.Map <StopViewModel>(newStop)));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Failed to save new stop", ex);
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json("Failed to save new stop!"));
            }

            return(Json("Validation failed on new stop"));
        }
        public async Task <IActionResult> Post(string tripName, [FromBody] StopViewModel stop)
        {
            if (ModelState.IsValid)
            {
                var newStop = Mapper.Map <Stop>(stop);

                // Lookup the Geocodes
                var result = await _coordsService.GetCoordsAsync(newStop.Name);

                if (!result.Success)
                {
                    //_logger.LogError(result.Message);
                }
                else
                {
                    newStop.Latitude  = result.Latitude;
                    newStop.Longitude = result.Longitude;
                }

                // Save to database
                _repository.AddStop(tripName, newStop);


                if (await _repository.SaveChangesAsync())
                {
                    // Returning the TripViewModel and not the entity itself (Trip) for security/encapsulation.
                    return(Created($"api/trips/{tripName}/stops/{newStop.Name}",
                                   Mapper.Map <StopViewModel>(newStop)));
                }
            }

            // DEBUGGING: Determine why ModelState is invalid:
            //var errors = ModelState.Values.SelectMany(v => v.Errors);

            // Returning just the ModelState is helpful for debugging in internal services.
            return(BadRequest("Failed to save the stop."));
        }