You are on page 1of 129

Practical 1

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

Step 1 select java web application

Open Netbeans 8/8.2 --- file --- new project --- java web (left) --- web application(right)

Give name – tempwebservice

Step 2 select web service

Right click on project name tempwebservice –new –other –web service


Step 3

Go to Design page ---- add operation


tempservice.java

package mypack;

import javax.jws.WebService;

import javax.jws.WebMethod;

import javax.jws.WebParam;

@WebService(serviceName = "tempservice")

public class tempservice {

@WebMethod(operationName = "hello")

public String hello(@WebParam(name = "name") String txt)

return "Hello " + txt + " !";

@WebMethod(operationName = "F_to_C")

public Double F_to_C(@WebParam(name = "val") double val)

return ((val-32)*5/9);

@WebMethod(operationName = "C_to_F")

public Double C_to_F(@WebParam(name = "val") double val) {


return (val*9/5)+32;

Step 4 run

Right click on project name tempwebservice--- deploy

Right click on tempservice---test web service


in output window go to WSDL File and copy the url from address bar

URL http://localhost:8080/tempwebservice/tempWebService?WSDL

Steps to create Web Service Client:

• File-> New Project


Right click on project->New->Web Service Client-> Add the WSDL URL
Explore Web services References->and drag drop method which you want to call

//TempClient.java

package tempclient;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

public class TempClient {

public static void main(String[] args) throws IOException {

Double t;

int ch;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("1. Celcius to Fahreheit");

System.out.println("2. Fahrenheit to celcius");

System.out.println("Enter your Choice");

ch=Integer.parseInt(br.readLine());

System.out.println("Enter temperature");

t=Double.parseDouble(br.readLine());

if(ch==1)
System.out.println("temperature in fahrenheit="+cToF(t));

else

System.out.println("Temperature in celcius="+fToC(t));

private static Double cToF(double val) {

mypack.TempWebService_Service service = new mypack.TempWebService_Service();

mypack.TempWebService port = service.getTempWebServicePort();

return port.cToF(val);

private static Double fToC(double val) {

mypack.TempWebService_Service service = new mypack.TempWebService_Service();

mypack.TempWebService port = service.getTempWebServicePort();

return port.fToC(val);

O/P:

1. Celcius to Fahreheit

2. Fahrenheit to celcius
Enter your Choice

1
Enter temperature

25
temperature in fahrenheit=77.0
Practical-02
Aim: Write a program to implement the operation can receive request and will return a response
in two wayspr. a) One - Way operation b) Request –Response Factorial program

Right Click on FactorialWebService project->New->Web Service


Now type the code below in Factorialwebservice.java file

@WebMethod(operationName ="factorial")

public Double factorial(double num){

double f=1;

int i;

for(i=1;i<=num;i++){

f= f*i;

return f;

Right click on project->clean and build

Right click on project->deploy


Explore the project and go to the web services folder ->Right click on NewWebService ->Test Web

Service –in output window copy URL : http://localhost:14188/FactorialWebservice/Factorialwebservice?WSDL

To create java client refer to practical no 1 ‘s step

Then right click and on the project and select “New webservice Client” option and paste the WSDL url
link

Explore Web services References->and drag drop method which you want to call

Now add the code below inside the “main” method


package factorialclient;

import java.util.Scanner;

public class FactorialClient {

public static void main(String[] args) { Scanner scan = new Scanner(System.in);


System.out.print("Enter a number to find factorial : ");

double num = scan.nextDouble();

System.out.println(factorial(num));

private static Double factorial(double arg0) {

abc.com.Factorialwebservice_Service service = new abc.com.Factorialwebservice_Service();


abc.com.Factorialwebservice port = service.getFactorialwebservicePort(); return port.factorial(arg0);

Result
Practical-03

Aim: Write a program to create a web service to perform ceaser cipher encryption.
First create a new project→ Web project
Right click on project→ New→ Web Service

Open CCipherService.java and type:

package com.abc;

import java.util.Random;

import javax.jws.WebService;

import javax.jws.WebMethod;

import javax.jws.WebParam;

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

@WebMethod(operationName="encrypt")

public String encrypt(@WebParam(name="name") String msg){

String ct="";

Random rd=new Random();

for(int i=0;i<msg.length();i++){

ct+=(char)(msg.charAt(i)+rd.nextInt(26));

return ct;

}
Then clean and build the project→ deploy→ Right Click on CCipherService in Web Services
and Click on Test Web Service

Test the web service in the browser

Now, Create a java application. It’s purpose would be to create the java client for the above web
service.

Now, Right Click on the Client application→ New→ Web Service Client and paste the WSDL URL of
the web service which was previously deployed and tested
Now, drag and drop the encrypt method from Web Service References into
the CcipherClient.java and use the below code

CCipherClient.java

package ccipherclient;

import java.util.Scanner;

public class CCipherClient {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

System.out.println("Enter message");

String msg=sc.next();
System.out.println("Encrypted message: "+encrypt(msg));

private static String encrypt(java.lang.String name) {

com.abc.CCipherService_Service service = new com.abc.CCipherService_Service();

com.abc.CCipherService port = service.getCCipherServicePort();

return port.encrypt(name);

}
Clean and build CcipherClient→ Run the project

O/P:

Enter message

abc

Encrypted message: ewp


Practical-04
Aim: Develop client which consumes web services developed in different
platform. Create a webservice in netbean and use it in .NET

Open Netbeans 8.2 – file—new- progect


Right Click on FactorialWebService project->New->Web Service

Go to design page--Add operation

Give method name as factorial

Return type double

Parameter num

Type double

Go to source page and Now type the code below in Factorialwebservice.java file

@WebMethod(operationName ="factorial")

public Double factorial(double num){

double f=1;

int i;

for(i=1;i<=num;i++){

f= f*i;
}

return f;

Right click on project name FactorialWebService->clean and build

Right click on project name FactorialWebService ->deploy

Right click on FactorialWebService ---test web service

Copy the WSDL Link of the web service.

http://localhost:14188/FactorialWebservice/Factorialwebservice?WSDL

Steps to create the Client app in .NET

Open Visual Studio 2010 ----file—new project

1:- Create a New Project in C# Empty Web Application


Steps to create the Client app in .NET

1:- Create a New Project in C# Empty Web Application

2:- Add a new Empty Web


3:- Design the interface and give the appropriate name and id's

4:- clean and build , and deploy the webservice created in the java and Test the WebService

Copy the WSDL Link of the web service.

http://localhost:14188/FactorialWebservice/Factorialwebservice?WSDL

5:- Now RightClick on Progect name and add (Service Reference in Client app) and paste the WSDL url
6:- Now doubleclick the button and then type the following cod in the aspx.cs file

protected void Button1_Click(object sender, EventArgs e)

ServiceReference1.FactorialwebserviceClient client =
new ServiceReference1.FactorialwebserviceClient();

Label1.Text = "Factorial is : " +


client.factorial(Convert.ToDouble(TextBox1.Text)).ToString();

Note:- here the name of the web service "factorialWebserviceClient" is created in


java.
output:-
Practical-05
Aim: Write a JAX-WS web service to perform the following operations. Define a Servlet / JSP that
consumes the web service.

Step 1 select java web application

Open Netbeans 8/8.2 --- file --- new project --- java web (left) --- web application(right)

Give name – calcwebservice

Step 2 select web service

Right click on project name calcwebservice –new –other –web service


Step 3

Go to Design page ---- add operation


calservice.java

package mypack;

import javax.jws.WebService;

import javax.jws.WebMethod;

import javax.jws.WebParam;

@WebService(serviceName = "calcservice")

public class calcservice {

@WebMethod(operationName = "hello")

public String hello(@WebParam(name = "name") String txt) {

return "Hello " + txt + " !";

@WebMethod(operationName = "Addition")

public Integer Addition(@WebParam(name = "a") int a, @WebParam(name = "b") int b) {

//TODO write your implementation code here:

return a+b;

@WebMethod(operationName = "Subtract")
public Integer Subtract(@WebParam(name = "a") int a, @WebParam(name = "b") int b) {

//TODO write your implementation code here:

return a-b;

Step 4 run

Right click on project name calcwebservice--- deploy

Right click on calservice---test web service


Copy the URL as shown below
http://localhost:8080/calcserviceproject/CalcWebService?WSDL
Steps to create Servlet/Jsp

Go to file – new—project
Give name as calcclient
Right click on calcclient –new --- web service client and paste the URL copied above

Right click on calcclient –new ---jsp


Give name as index
Place your cursor below hello world or line 16 as shown in figure below
Now right click below hello world
Click addition

Write code in 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 action="index.jsp">
Enter n1 <input type="text" name="n1">
Enter n2<input type="text" name="n2">
<input type="submit" value="submit">
</form>
</body>
</html>

Write code in index.jsp

Repeat the same steps for subtract place cursor below hello world and select

subtract then add code in index .jsp


Right click on calcclient project---deploy

Run index,html
Practical-06
Aim: Write a JAX-WS web service for finding Armstrong no. Define a Servlet / JSP that consumes
the web service.

File->New->Project
Right click on project and select Web servic
Right click on code and selet Add Web Service operation to add method in web services
Right click on project name and deploy the webservices

Right click on webservice folder and test the webservices

Create Servlet client to consume web services

Create a new web application and add servlet

Right click on project name ->New->Web Service Client


Explore web services references and drag drop armstrong method in

servlet.java. //index.html

<html>

<head>

<title>Armstrong number</title>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">


</head>

<body>

<form name="f1" method="GET" action="Armstrong">


Enter number: <input type="Text" name="t1">

<input type="submit" value="submit">

</form>

</body>

</html>
//Armstrong.java

package com.abc;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.xml.ws.WebServiceRef;

@WebServlet(name = "Armstrong", urlPatterns = {"/Armstrong"})

public class Armstrong extends HttpServlet {

@WebServiceRef(wsdlLocation =
"WEB-INF/wsdl/localhost_8080/ServletService/ServletService.w
sdl")

private ServletService_Service service;

protected void processRequest(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-
8"); try (PrintWriter out = response.getWriter()) {

/* TODO output your page here. You may use following sample code. */

out.println("<!DOCTYPE html>");

out.println("<html>");

out.println("<head>");
out.println("<title>Servlet Armstrong</title>");

out.println("</head>");

out.println("<body>");

out.println("<h1>Servlet Armstrong at " + request.getContextPath() + "</h1>");

int n=Integer.parseInt(request.getParameter("t1"));

out.println(armstrong(n));

out.println("</body>");

out.println("</html>");

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {

processRequest(request, response);

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
processRequest(request, response);

@Override

public String getServletInfo() {

return "Short description";


}// </editor-fold>

private String armstrong(int n) {

// Note that the injected javax.xml.ws.Service reference as well as port objects are not thread

safe.

/ If the calling of port operations may lead to race condition some synchronization is
required. com.abc.ServletService port = service.getServletServicePort();

return port.armstrong(n);

Enter number:
153

153 is armstrong
Practical-07
Aim: Define a web service method that returns the contents of a database in a XML string.

Go to the services tab and create a database by using either javaDB or Mysql.if creating by using
mysql then first register mysql server by right clicking on Database.

• Create a java web application.

• Right click on project ->new select RestFul Web services from database.
Note: The name of JNDI and user should be same eg. Here its abc.
Deploy restful web services by right clicking on project name.
Practical-08
Aim: Define a RESTful web service that accepts the details to be stored in a database and performs
CRUD operation.

Go to the services tab and create a database by using either javaDB or Mysql.if creating by using
mysql then first register mysql server by right clicking on Database.

• Create a java web application.

• Right click on project ->new select Entity class from database.


Right click on project ->new select JSF pages Entity class.
Right click on project ->new select RestFul Webservices from Entity class.
Deploy the Web Service and Run the project.
Practical-9
Define a web service method that returns the contents of a database in a JSON
string.

Steps

Open Microsoft SQL Server Management studio Express

Write Code
create database db1;
use db1;

CREATE TABLE Emp (Id INT IDENTITY(1,1), Name VARCHAR(25), Gender


VARCHAR(25), Salary INT);

INSERT INTO Emp(Name ,Gender ,Salary )VALUES('ram','male',7000);


INSERT INTO Emp(Name ,Gender ,Salary )VALUES('sham','male',8000);
INSERT INTO Emp(Name ,Gender ,Salary )VALUES('ramesh','male',9000);
INSERT INTO Emp(Name ,Gender ,Salary )VALUES('tarun','male',6000);
INSERT INTO Emp(Name ,Gender ,Salary )VALUES('john','male',5000);

select * from Emp;

CREATE PROCEDURE RecDb


AS
BEGIN
SELECT * FROM Emp;
END

Open Microsoft Visual Studio 2010

File –new—project
Right click on project name ie jsonproject—add—new item
Drag and Drop Emp in the center
Right click on project name ie jsonproject—add—new item—select webservice

Emp1.asmx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;

namespace jsonproject
{
/// <summary>
/// Summary description for Emp1
/// </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 Emp1 : System.Web.Services.WebService
{

[WebMethod]
public string HelloWorld()
{
return "Hello World";
}

DataClasses1DataContext mydc = new DataClasses1DataContext();

[WebMethod]
public string GetEmplyees(int Id)
{
var json = "";
var name = from result in mydc.Emps
where result.Id==Id
select result;
JavaScriptSerializer jss = new JavaScriptSerializer();
json = jss.Serialize(name);
return json;
}

}
}

Right click on project name ie jsonproject----build

Right click on project name ie jsonproject---view in browser


Practical 10

Implement a typical service and client using WCF


1)create WCF Service

2)Open Microsoft visual studio---go to file---new---project----select WCF(on left side)----select


WCF Service Application (on right side)---give name as MathService1.

3)Delete IService1.cs and Service.svc from right side(from solution explorer)

4) Right click on MathService1(from solution explorer)---add---new item---select WCF


service-----give name as MathService.

5) Write code for MathService.svc.cs and MathService.cs

WCF service
MathService.svc.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace MathService1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class
name "MathService" in code, svc and config file together.
public class MathService : IMathService
{
public Int32 add(Int32 n1, Int32 n2)
{
return n1 + n2;
}

public Int32 subtract(Int32 n1, Int32 n2)


{
return n1 - n2;
}

public Int32 multiply(Int32 n1, Int32 n2)


{
return n1 * n2;
}
public Int32 divide(Int32 n1, Int32 n2)
{
return n1 / n2;
}
}
}

IMathService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace MathService1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the
interface name "IMathService" in both code and config file together.
[ServiceContract]
public interface IMathService
{
[OperationContract]
Int32 add(Int32 n1, Int32 n2);

[OperationContract]
Int32 subtract(Int32 n1, Int32 n2);

[OperationContract]
Int32 multiply(Int32 n1, Int32 n2);

[OperationContract]
Int32 divide(Int32 n1, Int32 n2);
}
}
6)Test the service (click run)

7)Now we have to create WCF Client

8) Right click on Solution ‘MathService1’

9)click add----new project----select windows(left side)-----select windows form application(on


right side)---give name as MathServiceTestApp1.

10)create design on form1


3 textbox

3 label

1 button--- in properties window click on text ---write calculate

1 combobox---in properties window click on items then insert(add,subtract,multiply,divide)

WCF Client
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MathServiceTestApp1.MathService1;
namespace MathServiceTestApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void calculate_Click(object sender, EventArgs e)


{
MathServiceClient loclient = new MathServiceClient();
Int32 num1 = Convert.ToInt32(textBox1.Text.Trim());
Int32 num2 = Convert.ToInt32(textBox2.Text.Trim());

if (comboBox1.Text == "add")
{
textBox3.Text = loclient.add(num1, num2).ToString();
}

else if (comboBox1.Text == "subtract")


{
textBox3.Text = loclient.subtract(num1, num2).ToString();
}
else if (comboBox1.Text == "multiply")
{
textBox3.Text = loclient.multiply(num1, num2).ToString();
}
else

{
textBox3.Text = loclient.divide(num1, num2).ToString();
}

}
}
}

11)now we have to add reference

Right click on reference as shown below---click add service reference


12) click on discover button----select IMathService.
13)Give namespace as given in picture
14)write using statement as shown below
15)double click on calculate button and write code

private void calculate_Click(object sender, EventArgs e)


{

MathServiceClient loclient = new MathServiceClient();


Int32 num1 = Convert.ToInt32(textBox1.Text.Trim());
Int32 num2 = Convert.ToInt32(textBox2.Text.Trim());

if (comboBox1.Text == "add")
{
textBox3.Text = loclient.add(num1, num2).ToString();
}

else if (comboBox1.Text == "subtract")


{
textBox3.Text = loclient.subtract(num1,
num2).ToString();
}
else if (comboBox1.Text == "multiply")
{
textBox3.Text = loclient.multiply(num1,
num2).ToString();
}
else

{
textBox3.Text = loclient.divide(num1,
num2).ToString();
}

16) Right click on MathServiceTestApp1---click set as startup project.


17) now run the project

18)output is as follows
Practical 11

Use WCF to create a basic ASP.NET Asynchronous JavaScript and XML(AJAX) service

Step 1 : Open Visual Studio 2010.

 Go to File->New->WebSite
 Select ASP.NET Empty WebSite

Step 2 : Go to Solution Explorer and right-click.

 Select Add->New Item


 Select WebForm
 Default.aspx page will open

Define WCF Service :

Step 3 : Go to Solution Explorer and right-click.

 Select Add->New Item


 Select AJAX Enabled WCF Service and give name as GreetingService.
 Open GreetingService.cs and define the function Greeting as shown below
Step 4 : Open Default.aspx page and click in [Design option].

 From Toolbox, Drag and drop 1)Scriptmanager Control 2)Button


 Set value property of button as greet from properties window

Step 5 : In [Design] page right-click on Scriptmanager Control

 Select Properties option


 select Services
Step 6:

 set path
 write GreetingService (which is the name of ajax enabled web services )

Step 7:

Open Default.aspx page and click in [Source option].


Step 8:

Write code (write the bold black text )

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="sm1" runat="server">
<Services>
<asp:ServiceReference Path="~/GreetingService.svc" />
</Services>
</asp:ScriptManager>
<input type="button" value="greet" onclick="showgreeting()" />
</div>
</form>
</body>
</html>

<script language="javascript" type="text/javascript">

function showgreeting()
{

GreetingService.Greeting(onSuccess);
}

function onSuccess(response)
{
alert(response);
}

</script>

Step 9: run by right click on default.aspx in solution explorer ---select view in browser
Practical 12
Aim: Demonstrate using the binding attribute of an endpoint element in WCF
(Program for WCF TCP-Binding)

1)create WCF Service

2)Open Microsoft visual studio---go to file---new---project----select WCF(on left


side)----select WCF Service Library (on right side)---give name as SampleCalcSvc
3)Delete IService1.cs and Service.svc from right side(from solution explorer)

4)Go to app.config (from solution explorer)and delete the selected code


After delete this code will b displayed

5)right click on SampleCalcSvc (from solution explorer)-----add---new


item---interface ----give name ICalcService.cs

6)write code in ICalcService.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace SampleCalcSvc
{
[ServiceContract]
public interface ICalcService
{
[OperationContract]
int GetSum(int a, int b);
}
}

7)right click on SampleCalcSvc (from solution explorer)--- ---add---new


item---class ----give name CalcService.cs

8) write code ICalcService.cs


using System.Text;

namespace SampleCalcSvc
{
public class CalcService : ICalcService
{
public int GetSum(int a, int b)
{
return a + b;
}
}
}
9)right click on SampleCalcSvc (from solution explorer)------build

10) right click on App.config(from solution explorer)------


EditWcfConfiguration

11)select create new service and select


Browse ---bin-----debug----- SampleCalcSvc.dll--- SampleCalcSvc. CalcService
Click next ---SELECT TCP----

empty the text box----click yes


Click next

Finish
Give name as SampleCalcSvcNetTcpEndpoint
Address –mex

Binding –mexTcpBinding

Contract –Select IMetadataExchange from list

12) select host------new button ----enter base address


net.tcp://localhost:8080/SampleSvc---------ok
Click host---new button ---give base address
Click advanced ---right click service behavior –new service behavior configuration
Click add button
Select and Click add

Select and Click add


Select service debug
File --save
Save the project

20)save project and run (debug)

21) click sum----give value


Practical-13
Aim: Develop a WCF service and consume by using Console application.

1) Open new project and select WCF Service Application.


2) Delete the IService1.cs, AppData and Service1.svc and again add the WCF Service by
right clicking the project-> Add WCF Service
3)Type in the following files.

IService1.cs
using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace WCFConsole

NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name
"IService1" in both code and config file together.

[ServiceContract]

public interface IService1

[OperationContract]

double circle(int r);

[OperationContract]

int square(int s);

}
Service1.svc.cs
using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace WCFConsole

/ NOTE: You can use the "Rename" command on the "Refactor" menu to change the
class name "Service1" in code, svc and config file together.

/ NOTE: In order to launch WCF Test Client for testing this service, please
select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.

public class Service1 : IService1


{
public double circle(int r)
{
return (3.14 * r * r);
}

public int square(int s)

{
return (s * s);
}

}
}

4)Test the WCF service and copy the WSDL URL.


5)Create a new Project and Select Console Application for consuming the WCF Service.
6)Add the Web Service Reference by Right clicking the project-> Add Service Referenc
7)Type in the following file

Program.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace ConsoleWCFApp

class Program

static void Main(string[] args)

ServiceReference1.Service1Client ser = new ServiceReference1.Service1Client(); int r, s;

Console.WriteLine("Enter radius of Circle: "); r=Int32.Parse(Console.ReadLine());


Console.WriteLine("Enter side of Square: "); s = Int32.Parse(Console.ReadLine());
Console.WriteLine("Area of Circle: " + ser.circle(r)); Console.WriteLine("Area of Square: " +
ser.square(s)); Console.ReadLine();

}
8)Run the project.

O/P
Practical-14
Aim: Develop a WCF and consume by using MVC application.

First create a WCF Service Application in Visual Studio

Delete the IService1.cs and Service1.svc files and then Right click on project -> Add WCF
Service
Select IService1.cs and type in the [Operation Contract]

IService1.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace WcfGcd

NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name
"IService1" in both code and config file together.
[ServiceContract]

public interface IService1

[OperationContract]

int gcd(int n1,int n2);

}
Service1.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace WcfGcd

NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name
"Service1" in code, svc and config file together.

NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or
Service1.svc.cs at the Solution Explorer and start debugging.

public class Service1 : IService1

public int gcd(int n1,int n2)

int r;
while (n2 != 0)

r = n1 % n2;

n1 = n2;

n2 = r;

return n1;

Select and Run the Service1.cs and test the Web Service. Also, copy the WSDL url for Service
Reference.

Now, open a new project and Choose MVC Application


Select Internet Application(In Visual Studio 2013 this worked for me).

Now, add the Service Reference by Right Clicking the Project-> Add Service Reference
Paste the WSDL url which we copied earlier.
Now, go in Controllers folder of project and type in the HomeController.aspx

HomeController.aspx

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace GCDMVC3.Controllers
{

public class HomeController : Controller

public ActionResult Index()

ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

ServiceReference1.Service1Client s = new ServiceReference1.Service1Client();

ViewData["GCD"] = "GCD of numbers 12 and 24 "+s.gcd(12,24);

return View();

public ActionResult About()

{
ViewBag.Message = "Your app description page.";
return View();
}

public ActionResult Contact()


{
ViewBag.Message = "Your contact page.";

return View();
}
}
}
After this, open the Views folder and type in the Index.aspx. Add the line in any of the
ContentID tags

Index.aspx

<h2><%: ViewData["GCD"] %></h2>

Run the project


o/p:

You might also like