CRUD Operation using Web API and Windows Application

원문:http://www.dotnetfunda.com/articles/show/2341/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"
CRUD Operation using Web API and Windows Application_第1张图片
Next choose "Web API" and let the view engine be "Razor".Click "OK"
CRUD Operation using Web API and Windows Application_第2张图片
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
CRUD Operation using Web API and Windows Application_第3张图片
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
CRUD Operation using Web API and Windows Application_第4张图片
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.
CRUD Operation using Web API and Windows Application_第5张图片
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.
CRUD Operation using Web API and Windows Application_第6张图片
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.
CRUD Operation using Web API and Windows Application_第7张图片
Conclusion
Hope this will be helpful.Thanks for reading.Zipped file is attached herewith.

좋은 웹페이지 즐겨찾기