public void Delete() { using (MSSQLDbClient sqlClient = new MSSQLDbClient(ConnectionString)) { CategoryRowApiO existingCategory = sqlClient.Fill <CategoryRowApiO>(GetRecordSql); if (existingCategory == null) { this.Create(); existingCategory = sqlClient.Fill <CategoryRowApiO>(GetRecordSql); } Assert.NotNull(existingCategory); using (RESTClient restClient = new RESTClient(BaseUrl)) { List <KeyValuePair <string, string> > routeParams = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("CategoryId", existingCategory.CategoryId.ToString()) }; RestResult <CategoryRowApiO> apiResult = restClient.Execute <CategoryRowApiO>("Category/{CategoryId}", RestSharp.Method.DELETE, routeParameters: routeParams, headerParameters: Headers); Assert.True(apiResult.StatusCode == 301, apiResult.Content); } CategoryRowApiO dbCategory = sqlClient.Fill <CategoryRowApiO>(GetRecordSql); Assert.Null(dbCategory); } }
public void Create() { using (MSSQLDbClient sqlClient = new MSSQLDbClient(ConnectionString)) { CategoryRowApiO existingCategory = sqlClient.Fill <CategoryRowApiO>(GetRecordSql); if (existingCategory != null) { this.Delete(); } using (RESTClient restClient = new RESTClient(BaseUrl)) { CategoryRowApiO newCategory = new CategoryRowApiO() { CategoryName = TestCategoryName, Description = "Some text about the item" }; RestResult <CategoryRowApiO> apiResult = restClient.Execute <CategoryRowApiO>("Category", RestSharp.Method.PUT, jsonBody: newCategory, headerParameters: Headers); Assert.True(apiResult.StatusCode == 201, apiResult.Content); CategoryRowApiO sqlResult = sqlClient.Fill <CategoryRowApiO>("SELECT CategoryID as CategoryId, CategoryName, Description FROM Categories WHERE CategoryName = '" + newCategory.CategoryName + "' ORDER BY CategoryID"); Assert.True(sqlResult.CategoryName == apiResult.Result.CategoryName && sqlResult.Description == apiResult.Result.Description && sqlResult.CategoryId == apiResult.Result.CategoryId); } } }
public void UpdatePartialBadly() { using (MSSQLDbClient sqlClient = new MSSQLDbClient(ConnectionString)) { CategoryRowApiO existingCategory = sqlClient.Fill <CategoryRowApiO>(GetRecordSql); if (existingCategory == null) { this.Create(); existingCategory = sqlClient.Fill <CategoryRowApiO>(GetRecordSql); } Assert.NotNull(existingCategory); using (RESTClient restClient = new RESTClient(BaseUrl)) { string partialJson = "{ \"CategoryId\": " + existingCategory.CategoryId + " }"; RestResult <CategoryRowApiO> apiResult = restClient.Execute <CategoryRowApiO>("Category", RestSharp.Method.PATCH, jsonBodyPartial: partialJson, headerParameters: Headers); // the assert should be false. The model we are working with is simple and has only 1 required parameter. Assert.True(apiResult.StatusCode == 200, apiResult.Content); } CategoryRowApiO dbCategory = sqlClient.Fill <CategoryRowApiO>(GetRecordSql); Assert.False(dbCategory.CategoryName == string.Empty, "Incorrect text was saved."); } }
public void UpdatePartial() { using (MSSQLDbClient sqlClient = new MSSQLDbClient(ConnectionString)) { CategoryRowApiO existingCategory = sqlClient.Fill <CategoryRowApiO>(GetRecordSql); if (existingCategory == null) { this.Create(); existingCategory = sqlClient.Fill <CategoryRowApiO>(GetRecordSql); } Assert.NotNull(existingCategory); using (RESTClient restClient = new RESTClient(BaseUrl)) { string partialJson = "{ \"CategoryId\": " + existingCategory.CategoryId + ", \"Description\": \"All about more text\" }"; RestResult <CategoryRowApiO> apiResult = restClient.Execute <CategoryRowApiO>("Category", RestSharp.Method.PATCH, jsonBodyPartial: partialJson, headerParameters: Headers); Assert.True(apiResult.StatusCode == 200, apiResult.Content); } CategoryRowApiO dbCategory = sqlClient.Fill <CategoryRowApiO>(GetRecordSql); Assert.True(dbCategory.Description == "All about more text", "Incorrect text was saved."); } }
public void Update() { using (MSSQLDbClient sqlClient = new MSSQLDbClient(ConnectionString)) { CategoryRowApiO existingCategory = sqlClient.Fill <CategoryRowApiO>(GetRecordSql); if (existingCategory == null) { this.Create(); existingCategory = sqlClient.Fill <CategoryRowApiO>(GetRecordSql); } Assert.NotNull(existingCategory); using (RESTClient restClient = new RESTClient(BaseUrl)) { CategoryRowApiO updatedCategory = existingCategory; updatedCategory.Description += " More text."; RestResult <CategoryRowApiO> apiResult = restClient.Execute <CategoryRowApiO>("Category", RestSharp.Method.PATCH, jsonBody: updatedCategory, headerParameters: Headers); Assert.True(apiResult.StatusCode == 200, apiResult.Content); Assert.True(apiResult.Result.Description.EndsWith(" More text."), "The updated text was not returned"); } CategoryRowApiO dbCategory = sqlClient.Fill <CategoryRowApiO>(GetRecordSql); Assert.True(dbCategory.Description.EndsWith(" More text."), "The updated text was not returned"); } }
public CategoryRowApiO GetCategory(int categoryId) { Category category = this.CategoryRepository.Fetch(categoryId); CategoryRowApiO result = new CategoryRowApiO(); using (Transposition tranposition = new Transposition()) { result = tranposition.Transpose <CategoryRowApiO>(category, result); } return(result); }
public void CreateInvalid() { using (RESTClient restClient = new RESTClient(BaseUrl)) { CategoryRowApiO newCategory = new CategoryRowApiO() { CategoryName = string.Empty, Description = "Some text about the item" }; RestResult <CategoryRowApiO> apiResult = restClient.Execute <CategoryRowApiO>("Category", RestSharp.Method.PUT, jsonBody: newCategory, headerParameters: Headers); Assert.True(apiResult.StatusCode == 406 || apiResult.StatusCode == 400, apiResult.Content); } }
public ActionResult <CategoryRowApiO> Put([FromBody] CategoryRowApiO category) { try { if (ModelState.IsValid == true) { CategoryRowApiO result = default(CategoryRowApiO); result = this.CategoryService.Create(category); this.CategoryService.Commit(); // Save the record to get the new id result = this.CategoryService.Fetch(category); Response.StatusCode = StatusCodes.Status201Created; // created return(result); } else { throw new ModelStateException(string.Format("Validation Failed, the {0} contains invalid data.", category.GetType().ToString()), ModelState); } } catch (ArgumentNullException e) { // expectation failed - field is missing Response.AddBody(e.Message); return(new StatusCodeResult(417)); } catch (ModelStateException e) { // not acceptable Response.AddBody(e.Message); return(new StatusCodeResult(406)); } catch (RecordFoundException e) { // bad request Response.AddBody(e.Message); return(new StatusCodeResult(400)); } catch (Exception e) { // application error internal server error Response.AddBody(e.Message); return(new StatusCodeResult(500)); } }
/// <summary> /// Adds a new record /// </summary> /// <param name="apiModel"></param> /// <returns>The key for the new record.</returns> public CategoryRowApiO Create(CategoryRowApiO apiModel) { CategoryRowApiO result = default(CategoryRowApiO); if (apiModel == null) { throw new ArgumentNullException("The input parameter cannot be null"); } else { if (ModelState.IsValid == false) { string modelType = apiModel.GetType().ToString(); ModelState.AddModelError(string.Empty, string.Format("Validation Failed, the {0} contains invalid data.", modelType)); throw new ModelStateException(string.Format("The {0} is not valid", modelType), ModelState); } else { // check the item does not already exist Category dbModel = this.CategoryRepository.FetchAll.Where(cat => cat.CategoryName == apiModel.CategoryName).FirstOrDefault(); if (dbModel != null) { // the item already exists throw new RecordFoundException(string.Format("A record for '{0}' already exists!", apiModel.CategoryId.ToString())); } else { dbModel = new Category(); // map the item and add it using (Transposition transposition = new Transposition()) { dbModel = transposition.Transpose <Category>(apiModel, dbModel); this.CategoryRepository.Create(dbModel); result = transposition.Transpose <CategoryRowApiO>(dbModel, apiModel); } } } } return(result); }
public CategoryRowApiO Update(CategoryRowApiO apiModel) { CategoryRowApiO result = default(CategoryRowApiO); if (apiModel == null) { throw new ArgumentNullException("The input parameter cannot be null"); } else { if (ModelState.IsValid == false) { string modelType = apiModel.GetType().ToString(); ModelState.AddModelError(string.Empty, string.Format("Validation Failed, the {0} contains invalid data.", modelType)); throw new ModelStateException(string.Format("The {0} is not valid", modelType), ModelState); } else { // find the item Category dbModel = this.CategoryRepository.Fetch(apiModel.CategoryId); if (dbModel == null) { // item was not found! throw new RecordNotFoundException("Could not find a item with id '{0}'", apiModel.CategoryId.ToString()); } else { // map the apiO to the db model. using (Transposition transposition = new Transposition()) { dbModel = transposition.Transpose <Category>(apiModel, dbModel); // update the item this.CategoryRepository.Update(dbModel); result = transposition.Transpose <CategoryRowApiO>(dbModel, apiModel); } } } } return(result); }
/// <summary> /// Fetches 1 category /// </summary> /// <param name="categoryId"></param> /// <returns></returns> public CategoryRowApiO Fetch(int categoryId) { Category category = this.CategoryRepository.Fetch(categoryId); if (category == null) { throw new RecordNotFoundException("Could not find a item with id '{0}'", categoryId.ToString()); } else { CategoryRowApiO result = new CategoryRowApiO(); using (Transposition tranposition = new Transposition()) { result = tranposition.Transpose <CategoryRowApiO>(category, result); } return(result); } }
/// <summary> /// Fetch an item using a other fields apart from its key. /// </summary> /// <param name="category"></param> /// <returns></returns> public CategoryRowApiO Fetch(CategoryRowApiO category) { Category categoryDb = this.CategoryRepository.FetchAll.Where(f => f.CategoryName.Substring(0, category.CategoryName.Length) == category.CategoryName && f.Description.Substring(0, category.Description.Length) == category.Description).FirstOrDefault(); if (categoryDb == null) { throw new RecordNotFoundException("Could not find a matching item."); } else { CategoryRowApiO result = new CategoryRowApiO(); using (Transposition transposition = new Transposition()) { result = transposition.Transpose(categoryDb, result); } return(result); } }
public void GetOne() { using (RESTClient restClient = new RESTClient(BaseUrl)) { List <KeyValuePair <string, string> > routeParams = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("CategoryId", "2") }; RestResult <CategoryRowApiO> apiResult = restClient.Execute <CategoryRowApiO>("Category/{CategoryId}", RestSharp.Method.POST, routeParameters: routeParams, headerParameters: Headers); Assert.True(apiResult.Success, apiResult.Content); Assert.NotNull(apiResult); using (MSSQLDbClient sqlClient = new MSSQLDbClient(ConnectionString)) { CategoryRowApiO sqlResult = sqlClient.Fill <CategoryRowApiO>("SELECT CategoryID as CategoryId, CategoryName, Description FROM Categories WHERE CategoryId = 2 ORDER BY CategoryID"); Assert.NotNull(sqlResult); Assert.True(apiResult.Result.CategoryId == sqlResult.CategoryId && apiResult.Result.CategoryName == sqlResult.CategoryName, "The records do not match."); } } }
public ActionResult <CategoryRowApiO> Patch([FromBody] CategoryRowApiO category) { try { if (category == default(CategoryRowApiO)) { // See if a partial has been sent. using (StreamReader sr = new StreamReader(Request.Body)) { string requestBody = sr.ReadToEnd(); if (requestBody != null) { if (requestBody.Length > 0) { using (JSONSerialiser serialiser = new JSONSerialiser()) { // The request may contain a partial so work around this. category = serialiser.Deserialize <CategoryRowApiO>(requestBody); } } } } } if (category != default(CategoryRowApiO)) { if (ModelState.IsValid) { CategoryRowApiO result = this.CategoryService.Update(category); this.CategoryService.Commit(); // Updated Response.StatusCode = 200; // OK return(result); } else { throw new ModelStateException(string.Format("Validation Failed, the {0} contains invalid data.", category.GetType().ToString()), ModelState); } } else { throw new ArgumentException("No json body could be found."); } } catch (ArgumentNullException e) { // expectation failed - field is missing Response.AddBody(e.Message); return(new StatusCodeResult(417)); } catch (ModelStateException e) { // not acceptable Response.AddBody(e.Message); return(new StatusCodeResult(406)); } catch (RecordNotFoundException e) { Response.AddBody(e.Message); return(new StatusCodeResult(204)); // no content } catch (Exception e) { // application error internal server error Response.AddBody(e.Message); return(new StatusCodeResult(500)); } }