calling webapi from windows client - c# - Northwind sample database Products table - find,insert,update,delete
Northwind örnek veritabanı Products tablosunu kullanarak;
önce bir web api programı yazıp kendi bilgisayarımda serv ettim.(http://localhost/WapiNW/)
sonra bir windows programı yapıp, arama, yeni kayıt, değiştirme ve silme işlemlerini yaptım.
aşağıda tümünün çalışma anı ve kod ekran görüntüleriyle gerekli kodları gösterdim.
// web api kod ***************************************************************
global.asaxusing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Routing;
namespace WebApiNW
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
//.....................................................................
var config = GlobalConfiguration.Configuration;
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
//---------------------------------------------------------------
config.Formatters.Remove(config.Formatters.XmlFormatter);
//.....................................................................
}
}
}
webapi.config
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace WebApiNW
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
ProductsController
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using WebApiNW.App_Data;
namespace WebApiNW.Controllers
{
public class ProductsController : ApiController
{
private NORTHWNDEntities db = new NORTHWNDEntities();
// GET: api/Products
public IQueryable<Products> GetProducts()
{
return db.Products;
}
// GET: api/Products/5
[ResponseType(typeof(Products))]
public IHttpActionResult GetProduct(int id)
{
//var product = db.Products.FirstOrDefault((p) => p.ProductID == id);
var product = (from u in db.Products
where u.ProductID == id
select new
{
u.ProductID
,u.ProductName
,u.UnitPrice
,u.SupplierID
,u.CategoryID
,u.QuantityPerUnit
,u.UnitsInStock
,u.UnitsOnOrder
,u.ReorderLevel
,u.Discontinued
,u.Categories.CategoryName
,u.Categories.Picture
}).FirstOrDefault();
if (product == null)
{
return NotFound();
}
return Ok(product);
}
// PUT: api/Products/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutProducts(int id, Products products)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != products.ProductID)
{
return BadRequest();
}
db.Entry(products).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductsExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/Products
[ResponseType(typeof(Products))]
public async Task<IHttpActionResult> PostProducts(Products products)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Products.Add(products);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = products.ProductID }, products);
}
// DELETE: api/Products/5
[ResponseType(typeof(Products))]
public async Task<IHttpActionResult> DeleteProducts(int id)
{
Products products = await db.Products.FindAsync(id);
if (products == null)
{
return NotFound();
}
db.Products.Remove(products);
await db.SaveChangesAsync();
return Ok(products);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool ProductsExists(int id)
{
return db.Products.Count(e => e.ProductID == id) > 0;
}
}
}
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>web api test </title>
<script src="Scripts/jquery-3.2.1.min.js"></script>
</head>
<body>
<div>
<h2>All Products</h2>
<ul id="products" />
</div>
<div>
<h2>Search by ID</h2>
<input type="text" id="prodId" size="5" />
<input type="button" value="Search" onclick="find();" />
<p id="product" />
</div>
<script>
var uri = 'api/Products';
function formatItem(item) {
return "Ürün Adı : " + item.ProductName + " -- Ürün ID : " + item.ProductID ;
}
function find() {
var id = $('#prodId').val();
$.getJSON(uri + '/' + id)
.done(function (data) {
$('#product').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#product').text('Error: ' + err);
});
}
</script>
<script type="text/javascript">
$("#prodId").on('keydown', function (e) {
if (e.which == 13) {
find();
}
});
</script>
</body>
</html>
// windows client kod ***************************************************************
Products class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WinFormWebApiClient
{
public class Products
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public Nullable<int> SupplierID { get; set; }
public Nullable<int> CategoryID { get; set; }
public string QuantityPerUnit { get; set; }
public Nullable<decimal> UnitPrice { get; set; }
public Nullable<short> UnitsInStock { get; set; }
public Nullable<short> UnitsOnOrder { get; set; }
public Nullable<short> ReorderLevel { get; set; }
public bool Discontinued { get; set; }
//---- aşağısı categori tablosu
public string CategoryName { get; set; }
public byte[] Picture { get; set; }
}
}
Form - find and crud -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormWebApiClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
#region" Tanımlamalar "
private HttpClient client = new HttpClient();
private string apiAdress = "http://localhost/WapiNW/api/Products/";
#endregion
#region" Load "
private void Form1_Load(object sender, EventArgs e)
{
Run();
}
#endregion
#region" Olaylar "
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter && this.textBox1.Text.Trim() != "")
{
this.button1.PerformClick();
}
}
#endregion
#region" Buttons "
private async void button1_ClickAsync(object sender, EventArgs e)
{
string spr = apiAdress + this.textBox1.Text;
var product = await GetProductAsync(spr);
ShowProduct(product);
}
private async void buttonEKLE_Click(object sender, EventArgs e)
{
Products productYeni = new Products { ProductName = "testEKLE_" + System.DateTime.Now.ToString()
, UnitPrice = 100m
, CategoryID = 2
, QuantityPerUnit = "10 adet"
, SupplierID=4
,Discontinued=false
,UnitsInStock=100
,UnitsOnOrder=5
,ReorderLevel=40
};
try
{
var url = await CreateProductAsync(productYeni);
//...........................................
var st = url.ToString().Split('/');
int xt = st.Count();
var dt = url.ToString().Split('/')[xt - 1];
this.textBox1.Text = dt;
this.button1.PerformClick();
//...........................................
MessageBox.Show("Kayıt Eklendi : " + url.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private async void buttonDEGISTIR_Click(object sender, EventArgs e)
{
string spr = apiAdress + this.textBox1.Text;
var product = await GetProductAsync(spr);
product.UnitPrice = 99m;
//...........................................
MessageBox.Show("Birim Fiyatı = 99 olarak değiştirilecek....");
var sonuc = await UpdateProductAsync(product);
MessageBox.Show(sonuc.UnitPrice.ToString() + " - olarak değiştirildi");
this.button1.PerformClick();
}
#endregion
#region" Diger "
private void Run()
{
client.BaseAddress = new Uri(apiAdress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
private async Task<Products> GetProductAsync(string path)
{
Products product = null;
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
product = await response.Content.ReadAsAsync<Products>();
}
return product;
}
private void ShowProduct(Products product)
{
//string str1 = ($"Name: {product.ProductName}\r\nPrice: {product.UnitPrice}\r\nCategory: {product.CategoryName}");
//.....................................
this.Cursor = Cursors.WaitCursor;
//.....................................
try
{
if (product == null)
{
//.....................................
this.Cursor = Cursors.Default;
//.....................................
MessageBox.Show("Kayıt Bulunamadı");
return;
}
//..........................................
if (product.Picture != null && product.Picture.Length > 0)
{
byte[] imgary = product.Picture;
ImageConverter converter = new ImageConverter();
pictureBox1.Image = (Image)converter.ConvertFrom(imgary);
}
else
{
pictureBox1.Image = null;
}
//..........................................
this.labelCategoryName.Text = product.CategoryName;
this.labelProductName.Text = product.ProductName;
this.labelBirimFiyati.Text = string.Format("{0:C2}", product.UnitPrice);
//..........................................
}
catch (Exception ex)
{
//.....................................
this.Cursor = Cursors.Default;
//.....................................
MessageBox.Show(ex.Message);
return;
}
//.....................................
this.Cursor = Cursors.Default;
//.....................................
}
#endregion
//****************** CRUD İŞLEMLERİ *****************************
//TODO:EKLE
private async Task<Uri> CreateProductAsync(Products product)
{
// çağrılması.....
//Products productYeni = new Products { ProductName = "test_12", UnitPrice = 100, CategoryID = 2 ,QuantityPerUnit=1};
//var url = await CreateProductAsync(productYeni);
//...................................................
HttpResponseMessage response = await client.PostAsJsonAsync(apiAdress, product);
response.EnsureSuccessStatusCode();
return response.Headers.Location;
}
//TODO:DEĞİŞTİR
private async Task<Products> UpdateProductAsync(Products product)
{
//çağrılması :önce değiştirilecek sonra şöyle çağrılacak ..
//await UpdateProductAsync(product);
//...................................................
try
{
string sd = apiAdress + product.ProductID;
HttpResponseMessage response = await client.PutAsJsonAsync(sd, product);
response.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
return product;
}
//TODO:SİL
private async Task<System.Net.HttpStatusCode> DeleteProductAsync(string id)
{
HttpResponseMessage response = await client.DeleteAsync($"api/products/{id}");
return response.StatusCode;
}
}
}
Yorumlar
Yorum Gönder