public ActionResult VehicleRegister1(VehicleRegisterViewModel newVehicleModel, int id) { bool result = false; try { Vehicle newVehicle = RegisterVehicle(newVehicleModel, id); result = _vehicleService.Add(newVehicle); } catch (Exception) { ViewBag.result = "Bir Hata Oluştu"; } if (result) { ViewBag.result = "Araç Kaydı Başarılı Bir Şekilde Oluşturuldu"; } else { ViewBag.result = "Kayıt Oluşturulurken Bir Hata Oluştu"; } return(View()); }
internal void AddVehicle(string driverID, string vehicleNumber, string maker, VehicleType type, byte seats) { Vehicle vehicle = SetVehicle(vehicleNumber, maker, type, seats, driverID); vehicle = VehicleServices.Create(vehicle); VehicleServices.Add(vehicle); VehicleServices.SaveData(); }
public IActionResult Post([FromBody] VehicleRequestModel request) { logger.LogInformation($"POST /api/vehicle reach with body: {request}"); var response = vehicleService.Add(request); return(response.CreateResponse(this)); }
public IActionResult Create([FromBody] Vehicle Model) { var vehicle = _repos.Add(Model); if (vehicle == null) { return(BadRequest(new { message = "Error Occured" })); } return(Ok(new { message = vehicle.ID })); }
public IActionResult Add(Vehicle car) { var result = _vehicleService.Add(car); if (result.Success) { return(Ok(result)); } return(BadRequest(result)); }
public IActionResult Add(Vehicle vehicle) { var result = _vehicleService.Add(vehicle); if (result.Success) { return(Ok(result.Message)); } return(BadRequest(result.Message)); }
public async Task <IActionResult> Create([FromForm] VehicleDTO vehicle) { userDTO = new UserDTO { Name = User.Identity.Name }; if (service.Add(vehicle, userDTO) != null) { return(RedirectToAction("Index")); } return(RedirectToAction("Index", "Home")); }
public ActionResult Create(VehicleModel obj) { if (ModelState.IsValid) { vehicleService.Add(obj); return(RedirectToAction("Index")); } else { return(View(obj)); } }
public IActionResult Add(VehicleDto vehicleDto) { var response = new ResponseViewModel(); response = _vehicleService.Add(vehicleDto); if (!response.IsSuccess) { return(BadRequest(response)); } return(Ok(response)); }
public IActionResult Post([FromBody] Vehicle Vehicle) { if (Vehicle == null) { return(BadRequest("Vehicle is null.")); } _vehicleService.Add(Vehicle); return(CreatedAtRoute( "Get", new { ID = Vehicle.VehicleID }, Vehicle)); }
public IActionResult Post([FromBody] VehicleApiModel newVehicle) { try { var vehicle = newVehicle.ToDomainModel(); _vehicleService.Add(vehicle); return(Ok(vehicle.ToApiModel())); } catch (Exception ex) { ModelState.AddModelError("AddNewVehicle", ex.Message); return(BadRequest(ModelState)); } }
public IActionResult PostVehicle([FromBody][Required] VehicleDto vehicleDto) { if (!ModelState.IsValid || vehicleDto == null || string.IsNullOrEmpty(vehicleDto.Name)) { return(BadRequest(ModelState)); } Vehicle vehicle = default(Vehicle); try{ vehicle = _mapper.Map <Vehicle>(vehicleDto); vehicle = _vehicleService.Add(vehicle); } catch (AppException) { } return(Ok(new { Vehicle = vehicle, StatusCode = "Vehicle added" })); }
public IActionResult AddVehicle([FromBody] VehicleModel model) { var authorId = int.Parse(HttpContext.User.Claims .FirstOrDefault(x => x.Type == ClaimTypes.Name) ?.Value !); var vehicle = _mapper.Map <Vehicle>(model); vehicle.OwnerId = authorId; try { _vehicleService.Add(vehicle); return(Ok()); } catch (AppException ex) { return(BadRequest(new { message = ex.Message })); } }
public IHttpActionResult PostVehicle(Vehicle vehicle) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } string token = ""; if (Request.Headers.Contains("oauth_token")) { token = Request.Headers.GetValues("oauth_token").First(); } try { vehicleService.Add(token, vehicle); return(Ok("vehiculo creado con exito")); } catch (Exception e) { return(Content(HttpStatusCode.ExpectationFailed, e.Message)); } }
// dotnet add package Microsoft.Extensions.DependencyInjection static async Task Main(string[] args) { Console.WriteLine("Rest API Console Client"); IServiceCollection services = new ServiceCollection(); services.AddSingleton <IVehicleService, ServiceStackVehicleService>(); var serviceProvider = services.BuildServiceProvider(); HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://localhost:5000"); // IVehicleService vehicleService = new ApiVehicleService(client); // IVehicleService vehicleService = new ServiceStackVehicleService(); IVehicleService vehicleService = serviceProvider.GetRequiredService <IVehicleService>(); IEnumerable <Vehicle> vehicles = await vehicleService.Get(); foreach (var vehicle in vehicles) { Console.WriteLine($"{vehicle.Model} {vehicle.ProductionYear}"); } Vehicle vehicle1 = await vehicleService.Get(1); Vehicle vehicle2 = new Vehicle { Model = "Syrena", ProductionYear = 1974, }; await vehicleService.Add(vehicle2); Console.WriteLine("Press any key to exit."); Console.ReadKey(); }
private void btnSave_Click(object sender, EventArgs e) { if (ValidateVehicle()) { if (ActualVehicle == null) { var newVehicle = new Vehicle() { }; newVehicle.VIN = txtVIN.Text; newVehicle.VehicleType = (VehicleType)cbTypeVehicle.SelectedItem; newVehicle.Color = txtColor.Text; newVehicle.Model = txtModel.Text; newVehicle.Brand = txtBrand.Text; newVehicle.Year = int.Parse(txtYear.Text); newVehicle.sell = new Sell(); _vehicleService.Add(frmLogin.token, newVehicle); MessageBox.Show("Se agrego correctamente el vehiculo.", "Agregado Correctamente", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { ActualVehicle.VIN = txtVIN.Text; ActualVehicle.VehicleType = (VehicleType)cbTypeVehicle.SelectedItem; ActualVehicle.Color = txtColor.Text; ActualVehicle.Model = txtModel.Text; ActualVehicle.Brand = txtBrand.Text; ActualVehicle.Year = int.Parse(txtYear.Text); _vehicleService.Update(frmLogin.token, ActualVehicle); MessageBox.Show("Vehiculo actualizado correctamente.", "Actualizado Correctamente", MessageBoxButtons.OK, MessageBoxIcon.Information); } ActualVehicle = null; this.Close(); } }
public HttpResponseMessage Create(HttpRequestMessage request, VehicleViewModel VehicleVm) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState); } else { var newVehicle = new Vehicle(); newVehicle.UpdateVehicle(VehicleVm); newVehicle.CreatedBy = User.Identity.Name; _vehicleService.Add(newVehicle); _vehicleService.SaveChanges(); var responseData = Mapper.Map <Vehicle, VehicleViewModel>(newVehicle); response = request.CreateResponse(HttpStatusCode.Created, responseData); } return response; })); }
private void btnImport_Click_1(object sender, EventArgs e) { if (ValidateInputImport()) { try { Assembly importedAssembly = Assembly.LoadFile(txtPathDll.Text); foreach (var type in importedAssembly.GetTypes()) { if (typeof(IImportReader).IsAssignableFrom(type)) { IImportReader mechanism = (IImportReader)Activator.CreateInstance(type, null); IEnumerable <VehicleDTO> vehicles = mechanism.ImportVehicles(txtPath.Text); if (vehicles.Count() > 0) { List <Vehicle> listVehicles = new List <Vehicle>(); int countVehicle = 1; foreach (var VehicleDTO in vehicles) { Vehicle newVehicle = new Vehicle(); newVehicle.VIN = VehicleDTO.VIN; newVehicle.Brand = VehicleDTO.Brand; newVehicle.Year = VehicleDTO.Year; newVehicle.VehicleType = (BackEnd.Domain.Enum.VehicleType)VehicleDTO.Type; newVehicle.Model = VehicleDTO.Model; newVehicle.Color = VehicleDTO.Color; newVehicle.sell = new Sell(); _vehicleService.Add(frmLogin.token, newVehicle); countVehicle++; } _logger.Info(frmLogin._user.Name, "Importacion", "se importaron " + countVehicle + " vehiculos"); frmVehicle frmVehicles = new frmVehicle(_vehicleService); frmVehicles.ShowDialog(); } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } //try //{ // Assembly importAssembly = Assembly.LoadFile(@fullPath); // //Type assType = importAssembly.GetType(name); // string readerType = "XML"; // if (name.Contains("CSV")) // readerType = "CSV"; // Type assType = importAssembly.GetTypes().First(t => t.Name.Contains(readerType)); // MethodInfo assMethod = assType.GetMethod("ImportVehicles"); // if (assMethod != null) // { // ParameterInfo[] parameters = assMethod.GetParameters(); // object classInstance = Activator.CreateInstance(assType, null); // importReader = (IImportReader)classInstance; // // object[] parametersArray = new object[] { txtPath.Text }; // var Vehicles = importReader.ImportVehicles(txtPath.Text); // var VehiclesQuantity = Vehicles.Count; // MessageBox.Show(string.Format("Se importaron correctamente {0} Vehicles", VehiclesQuantity), // "Importación Correcta", MessageBoxButtons.OK, MessageBoxIcon.Information); // _logger.Info(_username, "Importación", string.Format("Se importaron {0} Vehicles", VehiclesQuantity)); // if (VehiclesQuantity > 0) // { // List<Vehicle> listVehicles = new List<Vehicle>(); // int countVehicle = 1; // foreach (var VehicleDTO in Vehicles) // { // Vehicle newVehicle = new Vehicle() // { // Id = countVehicle, // VIN = VehicleDTO.VIN, // Model=VehicleDTO.Model, // Brand = VehicleDTO.Brand, // Year = VehicleDTO.Year, // Color=VehicleDTO.Color, // VehicleType = (BackEnd.Domain.Enum.VehicleType)VehicleDTO.Type, // }; // _vehicleService.Add(frmLogin.token, newVehicle); // countVehicle++; // } // frmVehicle frmVehicles = new frmVehicle(_vehicleService); // frmVehicles.ShowDialog(); // } // } // else // { // MessageBox.Show(string.Format("No se encontro el método ImportVehicles en la dll {0}", fullPath), // "Error al Importar", MessageBoxButtons.OK, MessageBoxIcon.Error); // } //} //catch (System.IO.FileNotFoundException) //{ // MessageBox.Show(string.Format("No se encontro la dll {0} en la ruta {1}", dll, _path), // "Error al Importar", MessageBoxButtons.OK, MessageBoxIcon.Error); //} } }
public async Task <IActionResult> Add([FromBody] Vehicle vehicle) { return(Ok(await _vehicleService.Add(vehicle))); }
public VehiclesModule(IVehicleService service, IUserService userService, IDownloadService downloadService, INotificationService notificationService) : base("vehicles") { this.RequiresAuthentication(); Get("/{id}/preview", x => HttpStatusCode.NotFound); Get("/", x => { Debug.Log($"Listing vehicles"); try { int page = Request.Query["page"]; // TODO: Items per page should be read from personal user settings. // This value should be independent for each module: Vehicles, vehicles and simulation. // But for now 5 is just an arbitrary value to ensure that we don't try and Page a count of 0 int count = Request.Query["count"] > 0 ? Request.Query["count"] : Config.DefaultPageSize; return(service.List(page, count, this.Context.CurrentUser.Identity.Name).Select(VehicleResponse.Create).ToArray()); } catch (Exception ex) { Debug.LogException(ex); return(Response.AsJson(new { error = $"Failed to list vehicles: {ex.Message}" }, HttpStatusCode.InternalServerError)); } }); Get("/{id:long}", x => { long id = x.id; Debug.Log($"Getting vehicle with id {id}"); try { var vehicle = service.Get(id, this.Context.CurrentUser.Identity.Name); return(VehicleResponse.Create(vehicle)); } catch (IndexOutOfRangeException) { Debug.Log($"Vehicle with id {id} does not exist"); return(Response.AsJson(new { error = $"Vehicle with id {id} does not exist" }, HttpStatusCode.NotFound)); } catch (Exception ex) { Debug.LogException(ex); return(Response.AsJson(new { error = $"Failed to get vehicle with id {id}: {ex.Message}" }, HttpStatusCode.InternalServerError)); } }); Post("/", x => { Debug.Log($"Adding new vehicle"); try { var req = this.BindAndValidate <VehicleRequest>(); if (!ModelValidationResult.IsValid) { var message = ModelValidationResult.Errors.First().Value.First().ErrorMessage; Debug.Log($"Validation for adding vehicle failed: {message}"); return(Response.AsJson(new { error = $"Failed to add vehicle: {message}" }, HttpStatusCode.BadRequest)); } var vehicle = req.ToModel(this.Context.CurrentUser.Identity.Name); var uri = new Uri(vehicle.Url); if (uri.IsFile) { vehicle.Status = "Valid"; vehicle.LocalPath = uri.LocalPath; } else if (service.GetCountOfUrl(vehicle.Url) > 0) { List <VehicleModel> matchingModels = service.GetAllMatchingUrl(vehicle.Url); vehicle.Status = matchingModels[0].Status; vehicle.LocalPath = matchingModels[0].LocalPath; } else { vehicle.Status = "Downloading"; vehicle.LocalPath = WebUtilities.GenerateLocalPath("Vehicles"); } long id = service.Add(vehicle); Debug.Log($"Vehicle added with id {id}"); vehicle.Id = id; SIM.LogWeb(SIM.Web.VehicleAddName, vehicle.Name); SIM.LogWeb(SIM.Web.VehicleAddURL, vehicle.Url); SIM.LogWeb(SIM.Web.VehicleAddBridgeType, vehicle.BridgeType); if (!uri.IsFile && service.GetCountOfUrl(vehicle.Url) == 1) { SIM.LogWeb(SIM.Web.VehicleDownloadStart, vehicle.Name); downloadService.AddDownload( uri, vehicle.LocalPath, progress => notificationService.Send("VehicleDownload", new { vehicle.Id, progress }, vehicle.Owner), success => { string status = success && Validation.BeValidAssetBundle(vehicle.LocalPath) ? "Valid" : "Invalid"; service.SetStatusForPath(status, vehicle.LocalPath); service.GetAllMatchingUrl(vehicle.Url).ForEach(v => { notificationService.Send("VehicleDownloadComplete", v, v.Owner); SIM.LogWeb(SIM.Web.VehicleDownloadFinish, vehicle.Name); }); } ); } return(VehicleResponse.Create(vehicle)); } catch (Exception ex) { Debug.LogException(ex); return(Response.AsJson(new { error = $"Failed to add vehicle: {ex.Message}" }, HttpStatusCode.InternalServerError)); } }); Put("/{id:long}", x => { long id = x.id; Debug.Log($"Updating vehicle with id {id}"); try { var req = this.BindAndValidate <VehicleRequest>(); if (!ModelValidationResult.IsValid) { var message = ModelValidationResult.Errors.First().Value.First().ErrorMessage; Debug.Log($"Validation for updating vehicle failed: {message}"); return(Response.AsJson(new { error = $"Failed to update vehicle: {message}" }, HttpStatusCode.BadRequest)); } var vehicle = service.Get(id, this.Context.CurrentUser.Identity.Name); vehicle.Name = req.name; vehicle.Sensors = req.sensors == null ? null : string.Join(",", req.sensors); if (req.sensors != null) { SIM.LogWeb(SIM.Web.VehicleEditSensors); } vehicle.BridgeType = req.bridgeType; SIM.LogWeb(SIM.Web.VehicleEditName, vehicle.Name); SIM.LogWeb(SIM.Web.VehicleEditURL, vehicle.Url); SIM.LogWeb(SIM.Web.VehicleEditBridgeType, vehicle.BridgeType); if (vehicle.Url != req.url) { Uri uri = new Uri(req.url); if (uri.IsFile) { vehicle.Status = "Valid"; vehicle.LocalPath = uri.LocalPath; } else if (service.GetCountOfUrl(req.url) == 0) { vehicle.Status = "Downloading"; vehicle.LocalPath = WebUtilities.GenerateLocalPath("Vehicles"); SIM.LogWeb(SIM.Web.VehicleDownloadStart, vehicle.Name); downloadService.AddDownload( uri, vehicle.LocalPath, progress => notificationService.Send("VehicleDownload", new { vehicle.Id, progress }, vehicle.Owner), success => { string status = success && Validation.BeValidAssetBundle(vehicle.LocalPath) ? "Valid" : "Invalid"; service.SetStatusForPath(status, vehicle.LocalPath); service.GetAllMatchingUrl(vehicle.Url).ForEach(v => { // TODO: We have a bug about flickering vehicles, is it because of that? notificationService.Send("VehicleDownloadComplete", v, v.Owner); SIM.LogWeb(SIM.Web.VehicleDownloadFinish, vehicle.Name); }); } ); } else { List <VehicleModel> vehicles = service.GetAllMatchingUrl(req.url); vehicle.Status = vehicles[0].Status; vehicle.LocalPath = vehicles[0].LocalPath; } vehicle.Url = req.url; } int result = service.Update(vehicle); if (result > 1) { throw new Exception($"More than one vehicle has id {id}"); } else if (result < 1) { throw new IndexOutOfRangeException(); } return(VehicleResponse.Create(vehicle)); } catch (IndexOutOfRangeException) { Debug.Log($"Vehicle with id {id} does not exist"); return(Response.AsJson(new { error = $"Vehicle with id {id} does not exist" }, HttpStatusCode.NotFound)); } catch (Exception ex) { Debug.LogException(ex); return(Response.AsJson(new { error = $"Failed to update vehicle with id {id}: {ex.Message}" }, HttpStatusCode.InternalServerError)); } }); Delete("/{id:long}", x => { long id = x.id; Debug.Log($"Removing vehicle with id {id}"); try { VehicleModel vehicle = service.Get(id, this.Context.CurrentUser.Identity.Name); if (service.GetCountOfUrl(vehicle.Url) == 1) { if (vehicle.Status == "Downloading") { downloadService.StopDownload(vehicle.Url); SIM.LogWeb(SIM.Web.VehicleDownloadStop, vehicle.Name); } if (!new Uri(vehicle.Url).IsFile&& File.Exists(vehicle.LocalPath)) { Debug.Log($"Deleting file at path: {vehicle.LocalPath}"); File.Delete(vehicle.LocalPath); } } int result = service.Delete(id, vehicle.Owner); SIM.LogWeb(SIM.Web.VehicleDeleteName, vehicle.Name); SIM.LogWeb(SIM.Web.VehicleDeleteURL, vehicle.Url); SIM.LogWeb(SIM.Web.VehicleDeleteBridgeType, vehicle.BridgeType); if (result > 1) { throw new Exception($"More than one vehicle has id {id}"); } else if (result < 1) { throw new IndexOutOfRangeException(); } return(new { }); } catch (IndexOutOfRangeException) { Debug.Log($"Vehicle with id {id} does not exist"); return(Response.AsJson(new { error = $"Vehicle with id {id} does not exist" }, HttpStatusCode.NotFound)); } catch (Exception ex) { Debug.LogException(ex); return(Response.AsJson(new { error = $"Failed to remove vehicle with id {id}: {ex.Message}" }, HttpStatusCode.InternalServerError)); } }); Put("/{id:long}/cancel", x => { long id = x.id; Debug.Log($"Cancelling download of Vehicle with id {id}"); try { VehicleModel vehicle = service.Get(id, this.Context.CurrentUser.Identity.Name); if (vehicle.Status == "Downloading") { downloadService.StopDownload(vehicle.Url); vehicle.Status = "Invalid"; service.Update(vehicle); SIM.LogWeb(SIM.Web.VehicleDownloadStop, vehicle.Name); } else { throw new Exception($"Failed to cancel Vehicle download: Vehicle with id {id} is not currently downloading"); } return(new { }); } catch (IndexOutOfRangeException) { Debug.Log($"Vehicle with id {id} does not exist"); return(Response.AsJson(new { error = $"Vehicle with id {id} does not exist" }, HttpStatusCode.NotFound)); } catch (Exception ex) { Debug.LogException(ex); return(Response.AsJson(new { error = $"Failed to cancel download of vehicle with id {id}: {ex.Message}" }, HttpStatusCode.InternalServerError)); } }); Put("/{id:long}/download", x => { long id = x.id; Debug.Log($"Restarting download of Vehicle with id {id}"); try { VehicleModel vehicle = service.Get(id, this.Context.CurrentUser.Identity.Name); Uri uri = new Uri(vehicle.Url); if (!uri.IsFile) { if (vehicle.Status == "Invalid") { vehicle.Status = "Downloading"; downloadService.AddDownload( uri, vehicle.LocalPath, progress => { Debug.Log($"Vehicle Download at {progress}%"); notificationService.Send("VehicleDownload", new { vehicle.Id, progress }, vehicle.Owner); }, success => { var updatedModel = service.Get(id, vehicle.Owner); updatedModel.Status = success && Validation.BeValidAssetBundle(updatedModel.LocalPath) ? "Valid" : "Invalid"; service.Update(updatedModel); notificationService.Send("VehicleDownloadComplete", updatedModel, updatedModel.Owner); SIM.LogWeb(SIM.Web.VehicleDownloadFinish, vehicle.Name); } ); } else { throw new Exception($"Failed to restart download of Vehicle: Vehicle is not in invalid state"); } } else { throw new Exception($"Failed to restart download of Vehicle: file URL is not remote"); } int result = service.Update(vehicle); if (result > 1) { throw new Exception($"More than one Vehicle has id {id}"); } else if (result < 1) { throw new IndexOutOfRangeException(); } return(VehicleResponse.Create(vehicle)); } catch (IndexOutOfRangeException) { Debug.Log($"Vehicle with id {id} does not exist"); return(Response.AsJson(new { error = $"Vehicle with id {id} does not exist" }, HttpStatusCode.NotFound)); } catch (Exception ex) { Debug.LogException(ex); return(Response.AsJson(new { error = $"Failed to cancel download of Vehicle with id {id}: {ex.Message}" }, HttpStatusCode.InternalServerError)); } }); }
public async Task Handle(AddVehicleEvent notification, CancellationToken cancellationToken) { await vehicleService.Add(notification.Vehicle); }
public async Task <bool> Handle(SaveVehicleEvent request, CancellationToken cancellationToken) { await vehicleService.Add(request.Vehicle); return(true); }
public IActionResult Post([FromBody] Vehicle vehicle) { vehicleService.Add(vehicle); return(CreatedAtRoute("GetVehicle", new { id = vehicle.Id }, vehicle)); }