public IHttpActionResult Post(Resource resource) { // Check for bad values, done by the data annotations in the model class. if (!ModelState.IsValid) { return BadRequest(ModelState); } // Try to save resource try { resourceService.SaveResource(resource); } catch (DataBaseEntryNotFoundException) { return NotFound(); } catch (DuplicateNameException) { return Conflict(); } catch (ApprovedException exception) { return BadRequest(exception.Message); } catch { return InternalServerError(); } // Respond that the booking was created and redirect return Ok(resource); //CreatedAtRoute("DefaultApi", new { id = resource.ResourceId }, resource); }
public void SaveResource(Resource Resource) { // Preparare validation return data ICollection<ValidationResult> validationResults; // Try to validate given data if (Resource.Validate(out validationResults)) { // If a new Resource should be created if (Resource.ResourceId == 0) { ResourceDAL.InsertResource(Resource); } // Existing Resource should be updated else { // Check that the Resource exists before update if (ResourceDAL.GetResourceById(Resource.ResourceId) == null) { throw new DataBaseEntryNotFoundException(); } // Update Resource ResourceDAL.UpdateResource(Resource); } } // Validation failed else { // Create exception ApplicationException exception = new ApplicationException("Resource object contained invalid values."); // Add validation data to exception. exception.Data.Add("ValidationResults", validationResults); throw exception; } }
public void UpdateResource(Resource Resource) { // Create connection object using (this.CreateConnection()) { try { SqlCommand cmd; // Connect to database cmd = this.Setup("appSchema.usp_ResourceUpdate", DALOptions.closedConnection); // Add in parameters for Stored procedure cmd.Parameters.Add("@ResourceId", SqlDbType.SmallInt).Value = Resource.ResourceId; cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50).Value = Resource.Name; cmd.Parameters.Add("@Count", SqlDbType.SmallInt).Value = Resource.Count; cmd.Parameters.Add("@BookingPricePerHour", SqlDbType.Decimal).Value = Resource.BookingPricePerHour; cmd.Parameters.Add("@MinutesMarginAfterBooking", SqlDbType.SmallInt).Value = Resource.MinutesMarginAfterBooking; cmd.Parameters.Add("@WeekEndCount", SqlDbType.SmallInt).Value = Resource.WeekEndCount; // Open DB connection connection.Open(); // Execute insert to database cmd.ExecuteNonQuery(); } catch (Exception exception) { if (exception.Message == "There is already a resource with the given name.") { throw new DuplicateNameException(exception.Message); } // Throw exception throw new ApplicationException(DAL_ERROR_MSG); } } }
// Methods public void ResourceDelete(Resource Resource) { ResourceDelete(Resource.ResourceId); }