//POST api/products public HttpResponseMessage PostProduct([FromBody]ProductModel model, [ValueProvider(typeof(HeaderValueProviderFactory<string>))]string sessionKey) { var responseMsg = this.PerformOperationAndHandleExceptions<HttpResponseMessage>( () => { using (var context = new StoreContext()) { this.ValidateSessionKey(sessionKey); var admin = context.Users.FirstOrDefault(u => u.SessionKey == sessionKey); if (admin == null) { throw new ArgumentException("Invalid SessionKey or user is already logouted"); } else if (admin.IsAdmin != true) { throw new ArgumentException("Unauthorized Access"); } //TODO: Validate Escaping var category = context.Categories.Find(model.CategoryId); if (category == null) { throw new ArgumentException("Category not found"); } var product = new Product { Name = this.EscapeChars(model.Name), Description = this.EscapeChars(model.Description), ImageSource = this.EscapeChars(model.ImageSource), Category = category, Price = model.Price, Quantity = model.Quantity, }; context.Products.Add(product); context.SaveChanges(); } var response = new HttpResponseMessage(HttpStatusCode.Created); return response; }); return responseMsg; }
//PUT api/products/{productId} public HttpResponseMessage PutProduct([FromBody]ProductModel model, int productId, [ValueProvider(typeof(HeaderValueProviderFactory<string>))]string sessionKey) { var responseMsg = this.PerformOperationAndHandleExceptions<HttpResponseMessage>( () => { using (var context = new StoreContext()) { this.ValidateSessionKey(sessionKey); var admin = context.Users.FirstOrDefault(u => u.SessionKey == sessionKey); if (admin == null) { throw new ArgumentException("Invalid SessionKey or user is already logouted"); } else if (admin.IsAdmin != true) { throw new ArgumentException("Unauthorized Access"); } //TODO: Validate Escaping var existingProduct = context.Products.FirstOrDefault(p => p.Id == productId); if (existingProduct == null) { throw new ArgumentException("Product not found"); } var category = context.Categories.FirstOrDefault(c => c.Id == model.CategoryId); if (category == null) { throw new ArgumentException("Category not found"); } if (model.Name != null) { existingProduct.Name = model.Name; } if (model.Description != null) { existingProduct.Description = model.Description; } existingProduct.Category = category; if (model.Price != 0) { existingProduct.Price = model.Price; } //TODO: Should have an option to set the quantity 0 //default quantity-to is 1 = 0; if (model.Quantity != 0) { existingProduct.Quantity = model.Quantity; } var product = new Product { Name = model.Name, Description = model.Description, ImageSource = model.ImageSource, Category = category, Price = model.Price, Quantity = model.Quantity, }; context.SaveChanges(); } var response = new HttpResponseMessage(HttpStatusCode.Created); return response; }); return responseMsg; }