Wednesday, February 1, 2012

Working with webservices ASP.Net

Web services help the business to business communication possible. the output of web services  is communicated in the form of xml data resulting platform and end user independence
following is a demonstration of web services that communicate with a database OrgDB and later functions allow conversion of temperature scales. To use web services in your application you need to add service reference to the website from the Solution Explorer. The webservices are added by using the urls

webservice.asmx:
using System;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;


namespace WebServiceGetData
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://localhost/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 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 Service1 : System.Web.Services.WebService
    {

        [WebMethod]
        public DataTable GetData()
        {
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=OrgDB;Integrated Security=True");
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("Select * From tblDepartment", conn);
            System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(cmd);
            System.Data.DataSet ds = new System.Data.DataSet();
            da.Fill(ds);
            return ds.Tables[0]; 

        }


        [WebMethod(Description = "Add a new record to the Department Table")]
        public DataTable  InsertData(string @DName,String @DLocation)
        {
            SqlConnection conn = new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=OrgDB;Integrated Security=True");
            SqlCommand cmdIns = new SqlCommand("Insert into tblDepartment(DName, DLocation) values(@DName, @DLocation)", conn);
           
            cmdIns .Parameters .Add (new SqlParameter ("@DName",@DName ));
            cmdIns.Parameters.Add(new SqlParameter("@DLocation", @DLocation));
            conn.Open();
            cmdIns.ExecuteNonQuery();
           
           
            SqlCommand cmd = new SqlCommand("Select * From tblDepartment", conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            System.Data.DataSet ds = new System.Data.DataSet();
            da.Fill(ds);conn.Close();
            return ds.Tables[0]; 
          
        }

        [WebMethod(Description="Update the Department Table") ]
        public DataTable UpdateData(int @DID, string @DName, string @DLocation)
        {
            SqlConnection conn = new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=OrgDB;Integrated Security=True");
            SqlCommand cmdupd = new SqlCommand("update tbldepartment SET  DName=@DName , DLocation=@DLocation where DeptId =@DID ", conn);
            cmdupd.Parameters.Add(new SqlParameter("@DID", @DID));
            cmdupd.Parameters.Add(new SqlParameter("@DName", @DName));
            cmdupd.Parameters.Add(new SqlParameter("@DLocation", @DLocation));
            conn.Open();
            cmdupd.ExecuteNonQuery();
          
          
            SqlCommand cmd = new SqlCommand("Select * From tblDepartment", conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            System.Data.DataSet ds = new System.Data.DataSet();
            da.Fill(ds);conn.Close();
            return ds.Tables[0];
           
        }
        [WebMethod ]
        public DataTable DeleteData(int @DID)
        {
            SqlConnection conn = new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=OrgDB;Integrated Security=True");
            SqlCommand cmdDel = new SqlCommand("Delete from tbldepartment where DeptId =@DID ", conn);
            cmdDel.Parameters.Add(new SqlParameter("@DID", @DID));
            conn.Open();
            cmdDel.ExecuteNonQuery();

            SqlCommand cmd = new SqlCommand("Select * From tblDepartment", conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            System.Data.DataSet ds = new System.Data.DataSet();
            da.Fill(ds); conn.Close();
            return ds.Tables[0];

        }

        private double Farhenheit;
        private double Celcius;
        [WebMethod(Description = "Convert Fahrenheit to Celcius")]
        public double ConvertFromFarh(double Farhenheit)
        {
            Celcius = (double)((5 * Farhenheit) / 9 - 32);
            return Celcius;

        }
        [WebMethod(Description = "Convert Celcius to Fahrenheit")]
        public double ConvertFromCelcius(double Celcius)
        {
            Farhenheit = (double)((9  * Celcius)/ 5 + 32);
            return Farhenheit;
        }


    }
}

Default.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ServiceReference1;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Service1SoapClient ob = new Service1SoapClient();
       gv.DataSource= ob.GetData();
       gv.DataBind();
    }


    protected void btnInsert_Click(object sender, EventArgs e)
    {
        ServiceReference1 .Service1SoapClient  obj = new  ServiceReference1 .Service1SoapClient();
        string Name = txtName.Text;
        string Location = txtLocation.Text;

        gv.DataSource = obj.InsertData(Name, Location );
        gv.DataBind();
    }
    protected void gv_SelectedIndexChanged(object sender, EventArgs e)
    {
        txtName.Text = gv.SelectedRow.Cells[1].Text;
        txtLocation.Text = gv.SelectedRow.Cells[2].Text;     
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        int DeptId = int.Parse (gv.SelectedRow.Cells[0].Text);
        string Name = txtName.Text;
        string Location = txtLocation.Text;
        ServiceReference1.Service1SoapClient obj = new Service1SoapClient();

        gv.DataSource = obj.UpdateData(DeptId, Name, Location);
        gv.DataBind();
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        int DeptId = int.Parse(gv.SelectedRow.Cells[0].Text);
        ServiceReference1.Service1SoapClient obj = new ServiceReference1.Service1SoapClient();

        gv.DataSource = obj.DeleteData(DeptId);
        gv.DataBind();

    }

    protected void btnConvert_Click(object sender, EventArgs e)
    {
         ServiceReference1.Service1SoapClient obj = new ServiceReference1.Service1SoapClient();
        
       

         if (txtFarenheit.Text == "" && txtCelcius.Text != "")
         {
             double Celcius =Convert .ToDouble ( txtCelcius.Text);
             txtFarenheit.Text = obj.ConvertFromCelcius(Celcius).ToString ();
             txtCelcius.Text = "";
         }

         else if (txtCelcius.Text == "" && txtFarenheit.Text != "")
         {
             double Fahrenheit = Convert.ToDouble(txtFarenheit.Text);
             txtCelcius.Text = obj.ConvertFromFarh(Fahrenheit ).ToString ();
             txtFarenheit.Text = "";
         }
         else
            lblWarn.Text = "Enter Data";
    }
}
Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="gv" runat="server" autoGenerateColumns="False"
            EnableModelValidation="True"
            onselectedindexchanged="gv_SelectedIndexChanged" BackColor="White"
            BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4">
        <Columns>
            <asp:BoundField DataField="DeptId" HeaderText="Department ID" />
            <asp:BoundField DataField="DName" HeaderText="Department Name" />
            <asp:BoundField DataField="DLocation" HeaderText="Location" />
            <asp:CommandField ShowSelectButton="True" />
        </Columns>
        <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
        <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
        <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
        <RowStyle BackColor="White" ForeColor="#003399" />
        <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
        </asp:GridView><br />
       <fieldset >
       <legend><asp:Label ID="lblTitle" runat="server" Text="Manipulate Department Data"></asp:Label></legend>
       
        <asp:Label ID="lblDName" runat="server" Text="Enter name"></asp:Label>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br /><br />
            <asp:Label ID="lblLocation" runat="server" Text="Enter Location"></asp:Label>
            &nbsp;
            <asp:TextBox ID="txtLocation" runat="server"></asp:TextBox><br /><br />
            <asp:Button ID="btnInsert" runat="server" Text="Insert Department"
               onclick="btnInsert_Click" />&nbsp;<asp:Button ID="btnUpdate" runat="server"
               Text="Update Record" />&nbsp;
       <asp:Button ID="btnDelete" runat="server" Text="Delete Record" onclick="btnDelete_Click"
                />
        </fieldset>
        <fieldset><legend><asp:Label ID="LblConversion" runat="server" Text=" Tempreture Conversion"></asp:Label ></legend>
            <asp:Label ID="lblFar" runat="server" Text="Fahrenheit Scale: "></asp:Label>
            &nbsp;&nbsp;
            <asp:TextBox ID="txtFarenheit" runat="server"></asp:TextBox><br />
            <asp:Label ID="lblCelc" runat="server" Text="Centigrade Scale: "></asp:Label>
            &nbsp;
            <asp:TextBox ID="txtCelcius" runat="server"></asp:TextBox><br />
            <asp:Button ID="btnConvert" runat="server" Text="Convert"  onclick="btnConvert_Click" />
            <asp:Label ID="lblWarn" runat="server" ></asp:Label>
              
        </fieldset>
    </div>
    </form>
</body>
</html>

No comments:

Post a Comment