Tuesday, January 4, 2011

How to Create a sample ASP.NET Web Service and retrieve values from the database :

Step 1:

Create a database table by name

doctormaster(DoctorID,Doctor_Name,Specialist,Gender,Phone as columns)in MSSQL
Server database with some data.
Open Microsoft Visual Studio 2008--->>>File--->>> New--->>>
Web Site--->>>Select ASP.NET Web Service--->>>
Choose language to "visual c#"

Step 2:

In the Service.cs File--->>>
Copy paste the given code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
[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
{
    SqlConnection con = new SqlConnection("Data

Source=VIJAYVIGNESH\\SQLEXPRESS2008;Initial Catalog=hospital1;Integrated

Security=True");
    SqlCommand cmd = new SqlCommand();
    SqlDataReader dr;
    public Service () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
    [WebMethod]
    public List<Doctor> getDoctorDetails()
    {
        var doclist = new List<Doctor>();
        Doctor doc;
        con.Open();
        cmd.Connection = con;
        cmd.CommandText = "SELECT * from doctormaster";
        dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            doc = new Doctor
            {
                DoctorID = dr["DoctorID"].ToString(),
                Doctor_Name = dr["Doctor_Name"].ToString(),
                Specialist = dr["Specialist"].ToString(),
                Gender = dr["Gender"].ToString(),
                Phone = dr["Phone"].ToString()
            };
            doclist.Add(doc);
        }
        return doclist;
    }
   
}
public class Doctor
{
    public string DoctorID = string.Empty;
    public string Doctor_Name = string.Empty;
    public string Specialist = string.Empty;
    public string Gender = string.Empty;
    public string Phone = string.Empty;
}

thats it...!!!!Now you can run the program and click the "getDoctorDetails" Web
Method link in the browser--->>> press invoke.
Output will be in XML Format.Now you can use this web service in any front end
applications.

[Note: Make Your Own Connection String Instead Of "Data

Source=VIJAYVIGNESH\\SQLEXPRESS2008;Initial Catalog=hospital1;Integrated

Security=True"]