Rabu, 02 Mei 2012

Web Service Database dengan C#.NET

Web Service - C#.NET 

Buat WebService dengan cara klik File - New - Web Site. Pilih ASP.NET Web Service. Pilih Language : Visual C#.

Kemudian masukkan database, misalnya db.mdb ke direktori App_Data.

Tuliskan kode program berikut ini pada file App_Code/Service.cs :

using System;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.Xml.Linq;

using System.Data;

using System.Data.OleDb;



[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

// [System.Web.Script.Services.ScriptService]

public class Service : System.Web.Services.WebService

{

public Service () {



//Uncomment the following line if using designed components

//InitializeComponent();

}



//[WebMethod]

//public string HelloWorld() {

// return "Hello World";

//}



[WebMethod]

public DataSet getTb() {

OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~\\App_Data") + "\\db.mdb");

cn.Open();

OleDbCommand cm = new OleDbCommand("SELECT * FROM tb", cn);

OleDbDataReader rd = cm.ExecuteReader();

DataSet ds = new DataSet();

ds.Tables.Add(new DataTable("tb"));

ds.Load(rd, LoadOption.Upsert, ds.Tables["tb"]);

return ds;

}



[WebMethod]

public String insertTb(String id, String nm, String dsc, String dt, String prc) {

OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~\\App_Data") + "\\db.mdb");

cn.Open();

OleDbCommand cm = new OleDbCommand("INSERT INTO tb (id, nm, dsc, dt, prc) VALUES ('" + id + "', '" + nm + "', '" + dsc + "', #" + dt + "#, " + prc + ")", cn);

cm.ExecuteNonQuery();

return "Succeed";

}



[WebMethod]

public String updateTb(String id, String nm, String dsc, String dt, String prc) {

OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~\\App_Data") + "\\db.mdb");

cn.Open();

OleDbCommand cm = new OleDbCommand("UPDATE tb SET nm = '" + nm + "', dsc = '" + dsc + "', dt = #" + dt + "#, prc = " + prc + " WHERE id = '" + id + "'", cn);

cm.ExecuteNonQuery();

return "Succeed";

}



[WebMethod]

public String deleteTb(String id) {

OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~\\App_Data") + "\\db.mdb");

cn.Open();

OleDbCommand cm = new OleDbCommand("DELETE FROM tb WHERE id = '" + id + "'", cn);

cm.ExecuteNonQuery();

return "Succeed";

}



}


Hasilnya dapat dilihat dengan cara klik Debug - Start Debugging (Run - F5)