public HttpResponseMessage Put(int id, Ad ad) { if (ModelState.IsValid && id == ad.Id) { ad.ModifiedDate = DateTime.Now; try { _repo.Attach<Ad>(ad); _repo.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK, ad); } catch (DbUpdateConcurrencyException) { return Request.CreateResponse(HttpStatusCode.Conflict); } } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } }
protected bool CanEdit(Ad ad) { return IsAdmin() || AdBelongsToUser(ad); }
public HttpResponseMessage Post(Ad ad) { if (ModelState.IsValid) { //WebMatrix.WebData.WebSecurity. try { // Initializing data ad.CreatedDate = DateTime.Now; ad.IsActive = true; ad.UserId = WebSecurity.CurrentUserId; if (ad.Locations != null) { foreach (var loc in ad.Locations) { // Create DbGeopgraphy data for GeoLocation field if (loc.Latitude != 0 && loc.Longtitude != 0) { loc.GeoLocation = DbGeography.FromText(string.Format("POINT({0} {1})", loc.Longtitude.ToString(), loc.Latitude.ToString())); } // Get AdminAreaLevel2 if (loc.AdminAreaLevel2 != null) { var adminAreaLevel2 = _repo.GetQueryable<AdminAreaLevel2>().Where(x => x.Name.Equals(loc.AdminAreaLevel2.Name.Trim())).FirstOrDefault(); // If adminAreaLevel2 already exists, just reference it. Otherwise, create a new one if (adminAreaLevel2 != null) { loc.AdminAreaLevel2Id = adminAreaLevel2.Id; loc.AdminAreaLevel2 = null; } // Get AdminAreaLevel1 if (loc.AdminAreaLevel2.AdminAreaLevel1 != null) { var adminAreaLevel1 = _repo.GetQueryable<AdminAreaLevel1>().Where(x => x.Name.Equals(loc.AdminAreaLevel2.AdminAreaLevel1.Name.Trim())).FirstOrDefault(); // If adminAreaLevel1 already exists, just reference it. Otherwise, create a new one if (adminAreaLevel1 != null) { loc.AdminAreaLevel2.AdminAreaLevel1Id = adminAreaLevel1.Id; loc.AdminAreaLevel2.AdminAreaLevel1 = null; } } } } } var newlyCreatedAd = _repo.Add<Ad>(ad); _repo.SaveChanges(); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, newlyCreatedAd); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = newlyCreatedAd.Id })); return response; } catch (DbUpdateException) { return Request.CreateResponse(HttpStatusCode.Conflict); } } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } }
/// <summary> /// Check if an ad belongs to the current user /// </summary> /// <param name="ad"></param> /// <returns></returns> protected bool AdBelongsToUser(Ad ad) { return ad.UserId == WebSecurity.GetUserId(User.Identity.Name); }