CRUD Operation using Web API and Windows Application
Introduction
In this article we will perform a basic CRUD operation using Web API and Windows Application
Straight to Experiment
Fire up visual studio and choose "ASP.NET MVC 4 Web Application"
Next choose "Web API" and let the view engine be "Razor".Click "OK"
Add an Product Model (Product.cs) in the Models Folder
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
Add an Interface IProductRepository.cs as under
interface IProductRepository
{
IEnumerable GetAll();
Product Get(int id);
Product Add(Product item);
bool Update(Product item);
bool Delete(int id);
}
Add a concrete ProductRepository.cs as under
public class ProductRepository : IProductRepository
{
private List<Product> products = new List<Product>();
private int _nextId = 1;
public ProductRepository()
{
Add(new Product { Name = "Floppy Disk", Category = "Hardware/Electronics", Price = 20.10M });
Add(new Product { Name = "BMW", Category = "Car", Price = 3400000 });
}
public IEnumerable<Product> GetAll()
{
return products;
}
public Product Get(int id)
{
return products.Find(p => p.Id == id);
}
public Product Add(Product item)
{
item.Id = _nextId++;
products.Add(item);
return item;
}
public bool Update(Product item)
{
int index = products.FindIndex(p => p.Id == item.Id);
products.RemoveAt(index);
products.Insert(index, item);
return true;
}
public bool Delete(int id)
{
products.RemoveAll(p => p.Id == id);
return true;
}
}
Run the application
Now create a windows application and make a UI screen as under
For obtaining all the product, let us write the below code
private async void GetAllProducts()
{
using (var client = new HttpClient())
{
using (var response = await client.GetAsync(URI))
{
if (response.IsSuccessStatusCode)
{
var productJsonString = await response.Content.ReadAsStringAsync();
dataGridView1.DataSource = JsonConvert.DeserializeObject<Product[]>(productJsonString).ToList();
}
}
}
}
First of all we are creating an instance of the HttpClient. Then by using the "GetAsync" we are sending a GET request to the specified Uri as an asynchronous operation.
By using the "ReadAsStringAsync" method, we are writing the HTTP content to a string as an asynchronous operation.
The JsonConvert.DeserializeObject will convert the JSon string to the specified dotnet type.For this to use we need to download the JSON.net library.And then add the "Newtonsoft.Json.dll" specific to the dotnet version.
Finally we are binding the result to the grid
For inserting a product, let us write the below code
private async void AddProduct()
{
Product p = new Product();
p.Id = 3;
p.Name = "Rolex";
p.Category = "Watch";
p.Price = 1299936;
using (var client = new HttpClient())
{
var serializedProduct = JsonConvert.SerializeObject(p);
var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json");
var result = await client.PostAsync(URI, content);
}
GetAllProducts();
}
First of all we are creating the product object and adding a product to it.Then serializing the product to the JSon string by using the "JsonConvert.SerializeObject" method.
Finally we are using the "PostAsync" method for sending a POST request to the specified Uri as an asynchronous operation.
And invoking the "GetAllProducts()" to show the new collection.
The update method implementation is as under
private async void UpdateProduct()
{
Product p = new Product();
p.Id = 3;
p.Name = "Rolex";
p.Category = "Watch";
p.Price = 1400000; //changed the price
using (var client = new HttpClient())
{
var serializedProduct = JsonConvert.SerializeObject(p);
var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json");
var result = await client.PutAsync(String.Format("{0}/{1}", URI, p.Id), content);
}
GetAllProducts();
}
The implementation is very similar to the Insert methid except that we are using "PutAsync" that will send a PUT request to the specified Uri as an asynchronous operation.
And finally comes the Delete method whose implementation is as under
private async void DeleteProduct()
{
using (var client = new HttpClient())
{
var result = await client.DeleteAsync(String.Format("{0}/{1}", URI, 3));
}
GetAllProducts();
}
We are passing the id(which is 3 in this case) to the "DeleteAsync" method that will send a DELETE request to the specified Uri as an asynchronous operation.
Conclusion
Hope this will be helpful.Thanks for reading.Zipped file is attached herewith.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
【kintone】async/await 로 순서대로 데이터를 취득한다전회는 kintone.Promise.all 로 복수의 비동기 처리를 동시 병행으로 실행하면서, 전부 끝나면 다음의 처리를 실시···라고 하는 프로그램에 대해 썼습니다. 이번에는 async/await 로 다른 앱에서 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.