CRUD Operation using Web API and Windows Application

Niladri.Biswas
Posted by in Windows Forms category on for Beginner level | Points: 250 | Views : 31812 red flag

In this article we will perform a basic CRUD operation using Web API and Windows Application


 Download source code for 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.

Page copy protected against web site content infringement by Copyscape

About the Author

Niladri.Biswas
Full Name: Niladri Biswas
Member Level: Platinum
Member Status: Member
Member Since: 10/25/2010 11:04:24 AM
Country: India
Best Regards, Niladri Biswas
http://www.dotnetfunda.com
Technical Lead at HCL Technologies

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)