/// <summary> /// Update a contact. /// </summary> /// <param name="id"> /// The id of the contact. /// </param> /// <param name="contact"> /// The contact information to update. /// </param> public void Put(int id, Contact contact) { if (id != contact.Id) { throw new HttpResponseException(HttpStatusCode.BadRequest); } var existing = this.Get(id); if (existing == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } this.Repository.Update(contact); }
/// <summary> /// Update and existing contact. /// </summary> /// <param name="contact"> /// The contact to update. /// </param> /// <returns> /// The updated <see cref="Contact"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// The contact was null /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The contact did not have a valid id /// </exception> /// <exception cref="DataException"> /// A contact with that id does not exist /// </exception> public Contact Update(Contact contact) { if (contact == null) { throw new ArgumentNullException("contact"); } if (contact.Id < 1) { throw new ArgumentOutOfRangeException("contact"); } var existingContact = this.Get(contact.Id); if (existingContact == null) { throw new DataException("Contact does not exist."); } existingContact.FirstName = contact.FirstName; existingContact.LastName = contact.LastName; existingContact.Modified = DateTime.Now; return existingContact; }
/// <summary> /// The post/insert for a contact. /// </summary> /// <param name="contact"> /// The contact to insert. /// </param> /// <returns> /// The <see cref="HttpResponseMessage"/>. /// </returns> /// <exception cref="HttpResponseException"> /// An exception occurred attempting to insert /// </exception> public HttpResponseMessage Post(Contact contact) { try { var newContact = this.Repository.Insert(contact); var response = Request.CreateResponse(HttpStatusCode.Created, contact); var resource = this.Url.Route(null, new { id = newContact.Id }) ?? string.Empty; response.Headers.Location = new Uri(Request.RequestUri, resource); return response; } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } }
/// <summary> /// Insert a new contact. /// </summary> /// <param name="contact"> /// The contact to insert. /// </param> /// <returns> /// The inserted <see cref="Contact"/>. /// </returns> public Contact Insert(Contact contact) { if (contact == null) { throw new ArgumentNullException("contact"); } if (contact.Id > 0) { throw new DataException("Cannot insert existing contact."); } contact.Modified = contact.Created = DateTime.Now; contact.Id = Contacts.Any() ? Contacts.Max(c => c.Id) + 1 : 1; Contacts.Add(contact); return contact; }