CRUD Operation using Web API and Windows Application

31 篇文章 0 订阅

原文: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"

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.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值