28 July 2013

Creating and Consuming Web Services (C#)

Step 1. Create a Web Service file.

New --> Website --> ASP.NET Empty Website

Add New Item --> Web Service (MyService.asmx).

Modify the MyService.cs

using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class StockService : System.Web.Services.WebService
    public DataTable GetKampung()
        var con = new SqlConnection("Data Source=HACK3R;Initial Catalog=KampungDB;Integrated Security=True");
        string str = "SELECT * FROM KampungTbl";
        var cmd = new SqlCommand(str, con);
        var tbl = new DataTable();
        var da = new SqlDataAdapter(cmd);
        return tbl;

Step 2. Create a Proxy (disco and wsdl).

Add Web Reference --> Select "Web Services in this solution"

Select Services, then Add Reference

Step 3. Consume the Service.

using System;

public partial class Default2 : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            var service = new MyService();
            GridView1.DataSource = service.GetKampung();

NOTE: I didn't use the best practice in my codings in this example to make it as simple as possible just to give you the idea how easy to create and consume web services in Visual Studio 2010.

No comments:

Post a Comment