# WS Prac

```java
*Practical 1-A*

Aim: Write a program to implement to create a simple web service that converts the temperature from Fahrenheit to Celsius and vice a versa.

Steps:
1.	Create a Web Application (Name: TemperatureConverter)  
2.	Create a Web Service (Name: WebService1)
3.	Right Click on the Web Service and select Add Operation
4.	Add 2 operations for the conversion of Celsius to Fahrenheit and vice versa
    CtoF & FtoC
    [Name            Type        Final]
    [parameter       double        []  ]
5.	Write the following code:

TempConverter.java
package com;	
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;

@WebService(serviceName = "TempConverter")
public class TempConverter {
    /**
     * Web service operation
     */
    @WebMethod(operationName = "CtoF")
    public double CtoF(@WebParam(name = "parameter") double parameter) {
        //TODO write your implementation code here:
        double f;
        f = (parameter *9/5)+32;
        return f;
    }
    /**
     * Web service operation
     */
    @WebMethod(operationName = "FtoC")
    public double FtoC(@WebParam(name = "parameter") double parameter) {
        //TODO write your implementation code here:
        double c;
        c = (parameter - 32)*5/9;
        return c;
    }
}

6.	Run the Web Service by right clicking on Web Service and choosing Test 
    Web service


OUTPUT:
Celsius to Fahrenheit
 
Fahrenheit to Celsius
 
 
*Practical 1-B*

Aim:Calculate the Square of Number

Steps: 
1.	Create a New Project -> Web Application
2.	Right Click on the Web Application -> Click on Add -> New Item
3.	Search for Web Service -> Select Web Service
4.	Write the following codes: 

*************WebForm1.aspx*****************
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication9.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
        <form id="form1" runat="server">
            <div style="height:287px">
                &nbsp;&nbsp;
                <asp:Label ID="Label1" runat="server" style="font-weight:700" Text="Enter the Number:"></asp:Label>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
                &nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
                <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Calculate" />  
                <br />
&nbsp;&nbsp; <strong> 
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
                <asp:Label ID="Label2" runat="server" Text="Square :"></asp:Label>                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
                </strong>&nbsp;<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> 
            </div>
        </form>
</body>
</html>

*************************WebForm1.aspx.cs**************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication9
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            WebService1 w = new WebService1();
            TextBox2.Text = w.square(Convert.ToDouble(TextBox1.Text)).ToString();
        }
    }
}

******************WebService1.asmx.cs*******************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebApplication9
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [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 WebService1 : System.Web.Services.WebService
    {
        [WebMethod]
       public double square(double a)
        {
            return (a * a);
        }
    }
}

OUTPUT:

*Practical 2*

Aim: Write a program to implement the operation can receive request and 
will return a response in two ways. a) One - Way operation b) Request –Response

Step 1: Open NetBeans IDE 8.2 -> Go to Services -> Expand Databases -> Right click on JavaDB and start the server
Step 2: Right click on jdbc:derby://localhost:1527/sample [app on APP] and click on Connect..
Step 3: Expand the connection -> Expand APP -> Right click on Table and Create Table
Step 4: Name the table “friends” -> Click on Add column and add columns id and name -> Click on OK
Step 5: A table called FRIENDS got created -> Now create a New Project -> Choose Java Web -> Web Application
Step 6: Name it as Service21 -> Click on Next -> Next -> Finish
Step 7: Right click on Service21 -> Create a new Web Service
Step 8: Name it as myws and click on Finish
Step 9: Right click on Service21 -> New -> Other -> Select GlassFish -> Select JDBC Connection Pool
Step 10: Click on Next -> Next -> Finish
Step 11: Right click on Service21 -> New -> Other -> Select GlassFish -> Select JDBC Resource
Step 12: Click on the dropdown and choose connectionPool (the connection pool you just made). Give the JNDI name as jdbc/mydb. Click on Next. Then click on Finish.
Step 13: In myws.java file right click and click on Insert Code -> Choose Use Database
Step 14: Click on Add -> Add the Reference Name as mydsn -> Click on OK -> OK
Step 15: Go to Design in myws.java -> Click on Add Operation -> Add operations getName and insert
Step 16: Go to myws.java and add the following code
package ws;

import java.sql.*;
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.sql.DataSource;

@WebService(serviceName = "myws")
public class myws {

    @Resource(name = "mydsn")
    private DataSource mydsn;

    /**
     * This is a sample web service operation
     */
    @WebMethod(operationName = "hello")
    public String hello(@WebParam(name = "name") String txt) {
        return "Hello " + txt + " !";
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "getName")
    public String getName(@WebParam(name = "id") int id) {
        try{
            Connection c = mydsn.getConnection();
            PreparedStatement ps=c.prepareStatement("select * from friends where id=?");
            ps.setInt(1, id);
            ResultSet r=ps.executeQuery();
            if(r.next())
                return r.getString(2);
            else
                return "No name found";
            }catch(Exception e)
            {return "error";}
        }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "insert")
    public String insert(@WebParam(name = "id") int id, @WebParam(name = "name") String name) {
        try{
            Connection c = mydsn.getConnection();
            PreparedStatement ps=c.prepareStatement("insert into friends (id,name)values(?,?)");
            ps.setInt(1, id);
            ps.setString(2, name);
            ps.executeUpdate();
        }catch(Exception e){}      
        return null;
    }
}


Step 17: Right Click on Service21 -> Deploy -> The output should be BUILD SUCCESSFUL
Step 18: Go to File -> New Project -> Java Web -> Web Application
Step 19: Name it as ServiceClient21 -> Click on Next -> Finish
Step 20: Right Click on ServiceClient21 -> New -> Other -> Select Web Services -> Web Service Client
Step 21: Choose Project -> Click on Browse -> Expand Service21 -> Select myws -> Click on OK
Step 22: In Package write ws -> Click on Finish
Step 23: Right Click on Service21 -> New -> Other -> Web -> JSP -> Name it as getData -> Finish
Step 24: Similarly make another JSP file insertData
Step 25: In ServiceClient21 -> Go to index.html and write the following code
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
    <form>
        <h2> One Way Operation</h2>
        <input type="text" name="txt1" placeholder="Enter ID"><br>
        <input type="text" name="txt2" placeholder="Enter Name"><br>
        <input type="submit" formaction="insertData.jsp" value="insert"><br>
        
        <h1>------------------------------------</h1>
        
                <h2> Request-Response </h2>
            <input type="text" name="txt3" placeholder="Enter ID"><br>
            <input type="submit" formaction="getData.jsp" value="Get Data"><br>
    </form>
    </body>
</html>

Step 26: Go to getData.jsp -> Remove the part between the <body> tag -> Right click -> Select Web Service Client Resource -> Call Web Service Operation -> Expand ServiceClient21 -> Expand myws -> Expand myws -> Expand mywsPort -> Select getName -> Click on OK
Step 27: A try-catch block will be added -> Add another line of code before the try-catch block -> And remove the int id=0; line from the try-catch block
Step 28: Similarly do for insertData.jsp but this time select insert and click on OK
*for getData : int id = Integer.parseInt(request.getParameter("txt3")); 
*for inserData : int id = Integer.parseInt(request.getParameter("txt1"));
                 String name = request.getParameter("txt2");
Step 29: Make sure your code looks like this in insertData.jsp
Step 30: Right click on ServiceClient21 -> Deploy -> The output should be BUILD SUCCESSFUL
Step 31: Go to Services -> Tables -> Right click on FRIENDS -> View Data
Step 32: In SELECT * FROM APP.FRIENDS -> Click on Insert Records icon -> Insert a record manually
Step 33: Run ServiceClient21 and try and see if the record gets fetched 

The record is getting fetched from database. Hence our Request-Response is working Successfully!

Step 34: Now enter a new record and check if it’s getting inserted

The data got inserted now let’s see if it’s showing in the database
This is our old data showing. In order to see the new records we will run the statement again.

Step 35: Click on the Run Statement icon to refresh the records
The data has been inserted in the database. Hence our One Way Operation is Working Successfully!


*Practical 4*

Aim: Develop client which consumes web services developed in different platform.
Step 1: Create a new project.
Step 2: Select ASP.NET Empty Web Application and give a name to your project.
Step 3: Click on project->add->new item->Web services (ASMX).
Step 4: remove the default “Hello World” code and Add the following code.

public double add(double a, double b)
{
double sum = a + b;
return sum;
}

Step 5: Run the project.
Step 6: click on “Add”.
Step 7: Enter two values for a and b and click on “Invoke”
Step 8: Go back and click on “Service Description”.
Step 9: Now, copy the URL at the top.
Step 10: Open Netbeans, create new project (Web Application). Name it as (ServiceClient28) 
Step 11: Right click on the project and add web service client.
Step 12: Now add the WSDL URL and click on finish.
Step 13: Create a new JSP File -> Right click on the project -> New -> JSP -> Name the file (clientservice28)
Step 14: Right click on the form ->Web Service Client Resources-> Call Web Service Operation.
Step 15: click on add -> click on OK.
Step 16: Add the following codes in their respective files

****************clientservice21.jsp*********************
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>

<%-- start web service invocation --%><hr/>
<%
double num1 = Double.parseDouble(request.getParameter("text1")); 
double num2 = Double.parseDouble(request.getParameter("text2"));
try {
com.ak.WebService1 service = new com.ak.WebService1(); com.ak.WebService1Soap port = service.getWebService1Soap();
// TODO initialize WS operation arguments here double a = num1;
double b = num2;
// TODO process result here double result = port.add(a, b); out.println("Result = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}
%>
<%-- end web service invocation --%><hr/>
</body>
</html>

******************************index.html****************************
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form>
First Number<input type="text" name="text1"> Second Number<input type="text" name="text2">
<input type="submit" formaction="clientservice21.jsp" value="submit">
</form>
</body>
 
Step 17: Run the project after deploying the project

OUTPUT:

*PRACTICAL 5 *
AIM: Write a JAX-WS web service to perform the following operations. Define a Servlet / JSP that consumes 
the web service. 
Step 1: Create a new project-> New web application-> Give an appropriate name-> Click “Next”. 
Step 2: Right click on project-> New-> Web Service-> Click Next. 
Step 3: Give web service name as “operation” and package name as “com.kk”-> Click Finish. 
Step 4: Right click on web service and Add Operation. 
Step 5: Give name “Addition”-> Return Type “int”-> Add the following parameters along with their type-> 
Click OK. 
    [Name             Type             Final]
    [  a               int                [] ]
    [  b               int                [] ]

***************************Operation.java*******************************
package com.kk; 
import javax.jws.WebService; 
import javax.jws.WebMethod; 
import javax.jws.WebParam; 
@WebService(serviceName = "operation") 
public class operation { 
@WebMethod(operationName = "addition") 
public int addition(@WebParam(name = "a") int a, @WebParam(name = "b") int b) { 
int c = a + b; 
return c; 
} 
} 

Step 6: Right click on your project-> New-> JSP-> Click Next-> Give it a name and click Finish. (tycsJSP) 

*****************************tycsJSP.jsp***********************************
<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>JSP Page</title> 
</head> 
<body> 
<% 
com.kk.WS_PRACTICAL_5 obj = new com.kk.WS_PRACTICAL_5(); 
out.println("<h1>The addition of two numbers is: " + obj.addition(5,5)); 
%> 
</body> 
</html> 

Step 7: Right click on project-> Clean and Build. 
Step 8: Right click on project-> Deploy. 
Step 9: Right click on JSP file and run it. 
 
OUTPUT: 
 
 
*PRACTICAL 6*
AIM: Define a web service method that returns the contents of a database in a JSON string. The contents should be displayed in a tabular format. 
 
STEP 1: Go to Services. Select Databases – JavaDB. Click on it. Start the Server and connect the server 
STEP 2: Expand the url below. Select APP – Tables –Right Click to Create Table. Name the table as Friends 
STEP 3: Now click on Add Column.Enter details as in below images.Click OK. 
    ADD COLUMN                            ADD COLUMN
    Name: first_name                    Name: id
    Type: VARCHAR                       Type: INTEGER
    Size: 20                            Size: 
STEP 4: Right click on FRIENDS – View Data then insert records. Insert a record then click on Add Row button to insert more record. Next click OK. 
STEP 5: Now create a New Project – Java Web – Web Application with name Server. After that click 
STEP 6: Right Click on Project (Server) - New – RESTful Web Services from Database. 
STEP 7: Select the datasource and add the table Friends. Set the package name as com.kk 
STEP 8: Now create a New Project – Java Web – Web Application with name Client. After that click on Next and then Finish button. 
STEP 9: To the index.html page of the Client project add the following code. Once the code is added 
Deploy the Server project. Next Clean and Build – Run the Client project to see the output 
 
*******************************index.html**************************** 
<!DOCTYPE html> 
<!-- 
To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Templates and open the template in the editor. 
--> 
<html> 
<head> 
<title>Extracting Content of DB</title> 
<meta charset="UTF-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<style> table { 
font-family: arial, sans-serif; 
 
} 
td, th { 
border: 2px solid #000000; text-align: center; padding: 10px; 
} 
</style> <script> var request = new XMLHttpRequest(); 
request.open('GET','http://localhost:8080/Server-WS/webresources/com.kk.friends/',true); request.onload = function () { 
// begin accessing JSON data here var data = JSON.parse(this.response); 
for (var i = 0; i < data.length; i++) { 
var table = document.getElementById("myTabl e"); 
var row = table.insertRow(); 
var cell1 = row.insertCell( 0); 
var cell2 = row.insertCell(1); 
cell1.innerHTML = data[i].id; 
cell2.innerHTML = data[i].firstname; 
} }; 
request.send(); 
</script> 

</head> 
<body> 
<table id="myTable"> 
<tr> 
<th>ID</th> 
<th>NAME</th> 
</tr> 
</table> 
</body> 
</html> 
 
OUTPUT: 
 
 *PRACTICAL 7*
AIM: Define a RESTful web service that accepts the details to be stored in a database and performs CRUD operation.

Step 1: Create a new project-> New web application-> Give it a suitable name (TYCS)-> Next and Finish.
Step 2: Right click on your project-> New-> Entity class.
Step 3: Give class name as “Student” and package name as “com.kk”-> Click Next. And Finish.
Step 4: Right click on project-> New-> JSF pages from entity classes.
Step 5: Click on available class and add it into selected entity classes-> Click Next -> Change the session bean package (add com.kk), JSF classes package (add com.kk) and JSF pages folder as shown in the screenshot below-> Click Next and Finish.
Step 6: Right click on project-> New-> RESTful web services from entity classes.
Step 7: Click on available class and add it into selected entity classes-> Click Next.
Step 8: Write the resource package as “com.kk.service”-> Click Finish.
Step 9: Press Enter after “private Long id” and right click-> Insert Code-> Add Property.
Step 10: Give Name as “firstid” and Type as String-> Press OK.
 

*******************************Index.xhtml*********************************
<?xml version='1.0' encoding='UTF-8' ?>
<!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"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
        <title>TYCS07 Practical 7</title>
        <h:outputStylesheet name="css/jsfcrud.css"/>
    </h:head>
    <h:body>
        Hello from Facelets
        <br />
        <h:link outcome="/c/student/List" value="Show All Student Items"/>
    </h:body>

</html>

**************************Student.java********************************
package com.kk;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.xml.bind.annotation.XmlRootElement;

@Entity
@XmlRootElement
public class Student implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String firstid;

    public String getFirstid() {
        return firstid;
    }
    
    public void setFirstid(String firstid) {
        this.firstid = firstid;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        if (!(object instanceof Student)) {
            return false;
        }
        Student other = (Student) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.kk.Student[ id=" + id + " ]";
    }
    
}

Step 11: Right click on project-> Clean and Build.
Step 12: Right click on project-> Deploy.
Step 13: Right click on project-> Run.
 
OUTPUT:
 
  
*PRACTICAL 8*  
AIM: Use WCF to create a basic ASP.NET Asynchronous JavaScript and XML 
(AJAX) service 
STEP 1: Create a new ASP .Net Web Application project. Name it and Create 
STEP 2: Click on PROJECT – Add New Item – WCF Service (Ajax enabled) – Add.
Add the code to it 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.ServiceModel.Activation; 
using System.ServiceModel.Web; 
using System.Text; 
namespace MyService 
{ 
[ServiceContract(Namespace = "")] 
[AspNetCompatibilityRequirements(RequirementsMode = 
AspNetCompatibilityRequirementsMode.Allowed)] 
public class Service1 
{ 
[OperationContract] 
public double sum(double a, double b) 
{ 
double result = a + b; 
return result; 
} 
} 
} 

STEP 3: Right Click on project name – Add – Existing Item and attach the jquery file 
STEP 4: Rename Service1.svc to MyAJAXService.svc 
STEP 5: Click on PROJECT – Add New Item – Web Form. Rename as default. Add two text 
boxes to input number, a button to submit and a label to display the result. Add the code to make 
use of the service. 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
Inherits="Pract9_MyService.Default" %> 
<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title></title> 
<script type="text/javascript" src="jquery-1.2.js"></script> 
<script type="text/javascript" > 
$(document).ready(function() 
{ 
$("#Button1").click(function () 
{ 
var num1 = $("#TextBox1").val(); var num2 = $("#TextBox2").val(); 
$.ajax 
({ 
url: "MyAjaxService.svc/Sum", type: "POST", 
contentType: "application/json; charset=utf-8", data: JSON.stringify({ a: num1, b: num2 }), 
dataType: "json", success: function (data) 
{ 
$("#TextBox3").val(data.d); 
} 
,error: function (err) 
{ 
alert(err); 
} 
}); 
}); 
}); 
</script> 
</head> 
<body> 
<form id="form1" runat="server"> 
<div> 
<asp:Label ID="Label1" runat="server" Text="Number 1"></asp:Label> &nbsp; 
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
<asp:Label ID="Label2" runat="server" Text="Number 2"></asp:Label> &nbsp; 
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> 
<br /> 
&nbsp;&nbsp;&nbsp; 
<br /> 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> 
<br /> 
<br /> 
<asp:Label ID="Label3" runat="server" Text="Result"></asp:Label> 
&nbsp;&nbsp; 
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox> 
</div> 
</form> 
</body> 
</html> 

OUTPUT:


*PRACTICAL 9*
AIM: Use WCF to create a basic ASP,NET Asynchronous javascript and XML(AJAX).
Step 1: Add -> New Project -> ASP .NET Web Application ->Give name->Create empty.
Step 2: Right click on Project -> Add -> Web Forms-Give name->ok
Step 3: Right click on Project -> Add -> New Item -> WCF Service(AJAX-Enabled) ->add
Step 4: Open AJAX File add the following code by replacing DoWork() method.

public double Sum(double a, double b)
{
double result = a + b;
return result;
}
Step 5: Go to web browser->Download JQuery->(Download uncompressed.development
jquery
Step 6: Code appears on screen->Copy and Paste the code in NotePad->Save file as
jquery.js
Step 7: Right click on Project -> Add -> Existing Item->select the jquery.js file
Step 8: Open MyPage.aspx->Design the page->Add the code .
Step 9: Build & Run the Project

CODE:
Service1.svc.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
namespace AJAXwebservice1
{
 [ServiceContract(Namespace = "")]
 [AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
 public class Service1
 {
 [OperationContract]
 public double Sum(double a, double b)
 {
 double result = a + b;
 return result;
 }
 }
}
*****************************TYCS28_Mypage.aspx*****************************
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TYCS28_Mypage.aspx.cs"
Inherits="AJAXwebservice1.TYCS28_Mypage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title></title>
 <script src="jquery.js"></script>
 <script type="text/javascript">
 $(document).ready(function () {
 $("#Button1").click(function () {
 var num1 = $("#TextBox11").val();
 var num2 = $("#TextBox2").val();
 $.ajax({
 url: "Service1.svc/Sum",
 type: "POST",
contentType: "application/json; charset=utf-8",
 data: JSON.stringify({ a: num1, b: num2 }),
dataType: "json",
success: function (data) { $("#TextBox3").val(data.d); },
 error: function (err) {
 alert(err);
 }
 });
 });
 });
 </script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
 <br />
 <br />
 <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
 <br />
 <br />
 <asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Button" />
 <br />
 <br />
 <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
 </div>
 </form>
</body>
</html>
OUTPUT:

******************************PRACTICAL 10***********************************
AIM: Demonstrates using the binding attribute of an endpoint element in WCF.
Step1: Create a WCF Service Library as shown below
Step2: Open App.config and replace the original code with the one given below. Build
and Run the application.
TYCS28_Prac10

CODE:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <appSettings>
 <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
 </appSettings>
 <system.web>
 <compilation debug="true" />
 </system.web>
 <!-- When deploying the service library project, the content of the config file
must be added to the host's
 app.config file. System.Configuration does not support config files for
libraries. -->
 <system.serviceModel>
 <services>
 <service behaviorConfiguration="NewBehavior" name="TYCS28_Prac10.Service1">
 <host>
 <baseAddresses>
 <add baseAddress = "net.tcp://localhost:8733/Samplesrc" />
 </baseAddresses>
 </host>
 <!-- Service Endpoints -->
 <!-- Unless fully qualified, address is relative to base address supplied
above -->
 <endpoint address="" binding="netTcpBinding" bindingConfiguration=""
name="tcp" contract="TYCS28_Prac10.IService1">
 <!--
 Upon deployment, the following identity element should be removed
or replaced to reflect the
 identity under which the deployed service runs. If removed, WCF
will infer an appropriate identity
 automatically.
 -->
 <identity>
 <dns value="localhost"/>
 </identity>
 </endpoint>
 <!-- Metadata Endpoints -->
 <!-- The Metadata Exchange endpoint is used by the service to describe
itself to clients. -->
 <!-- This endpoint does not use a secure binding and should be secured or
removed before deployment -->
 <endpoint address="mex" binding="mexTcpBinding" bindingConfiguration=""
name="mextcp" contract="IMetadataExchange"/>
 </service>
 </services>
 <behaviors>
 <serviceBehaviors>
 <behavior name="NewBehavior">
 <!-- To avoid disclosing metadata information,
 set the values below to false before deployment -->
 <serviceMetadata />
 <!-- To receive exception details in faults for debugging purposes,
 set the value below to true. Set to false before deployment
 to avoid disclosing exception information -->
 <serviceDebug />
 </behavior>
 </serviceBehaviors>
 </behaviors>
 </system.serviceModel>
</configuration>

OUTPUT:
```
