7. Working With Web Services - Temple Fox MIS

voraciousdrabSoftware and s/w Development

Dec 14, 2013 (3 years and 5 months ago)

54 views

Working with
Web Service
s


What is
a web service
?


A web service is a software component specially designed to be accessed through web
-
based messaging protocols.

It is essentially a “wrapper” around an object class that makes
it accessible over the
Internet.


Think about a simple object, like
DateTime
. Recall that if we’d like to retrieve the
current year and store it in variable
y
, all we have to do is this:


int y = DateTime.Now.Year;


The
DateTime

object is stored on the local computer within the
class library of
the .NET Framework.
It’s a simple
example

of a request and response from the
DateTime

class.

But really it’s a client/server relationship; the application is the client
and the
DateTime

object is the server (serving data about the current
date and time).




The difference between a regular object and a web service is that the web service does
not have to reside on the local computer. As long as the calling application knows where
to find the remote object, the application can treat the object as if it’s local
.


Consuming a Simple Web Service: TemperatureConversion


As an example, we’re going to create a little application that consumes (uses) an existing
web service running on our course server (class1.sbm.temple.edu).
We’re not going to
worry about how that
web service was coded yet.

However, it is important to know that
there are
three

important
methods in the TemperatureConversion service:



p
ublic
TempConvert
()

Creates an instance of the web service

public double ToCelsius(double f)

Converts temperature
from Fahrenheit to
Celsius

public double ToFahrenheit(double c)

Converts temperature from Celsius to
Fahrenheit



Build the
basic application interface


1)

In Visual Studio 200
8
, create a new web site (File/New/Web Site…)


2)

Select the “ASP.NET Web Site” template.


3)

Make sure the “File System” is the value in the Location drop
-
down box and “Visual
C#” is the “Language.”


4)

C
hange the location
of the application
to wherever you want, but the directory should
end with “TempConsume
” (for example C:
\
VSProjects
\
TempConsume).


5)

Click on the “Design” tab. You may also need to make the Toolbox visible
(View/Toolbox)


6)

Type “Temperature Conversion Client” as the first line on the web page.


7)

Drag two textboxes and
two

button
s

to the web page
. Type “Input:” before the first
textbox and “Output:” before the second textbox. Change the text of the
first
button to
“Convert

to Celsius

and the second button to “Convert to Fahrenheit.”
Your page
should look something like this:



Create the

reference

to the TemperatureConversion web service


1)

From the Website menu, select “Add Web Reference…”


2)

In the URL textbox, type


http://class1.sbm.temple.edu/
3502
/TemperatureConversion
/
TempConvert
.asmx


a
nd click “Go.”


3)

Under “Web reference name” you’ll

see the value “edu.temple.edu.sbm.class1.”

Change the name to
TCReference

and c
lick “Add Reference.”

You’ll see
the web
reference

added to the Solution Explorer:




Use a method of the web service


To use the method of the web service, we need to create
an instance of the web service to
work with.
That instance will give us access to the two methods of the web service
(
ToFahrenheit()

and
ToCelsius()
).


This instance is truly a “reference”


it is a pointer to web service running on the class1
server.
When you invoke a method of the web service, it sends data to the server for
processing. The return value of the method is sent back to the application running on the
local

(client) machine
.






1)

Double
-
click on the

Convert to Celsius


button.


2)

Complete
the
Button1_Click()

method

as follows
:


protected

void

Button1_Click(
object

sender,
EventArgs

e)

{


double

inputValue =
Convert
.ToDouble(TextBox1.Text);



TCReference.
TempConvert

tcs =
new

TCReference.
TempConvert
();



double

convertedValue = tcs.ToCelsius(inputValue);



TextBox2.Text = convertedValue.ToString();

}


So here’s what’s happening in this method. First, we just retrieve the value from the first
TextBox

(
TextBox1.Text
) and convert it to a
double
.


The next step is to
create an instance of

the
TempConvert()

web service.
Just as with
a regular object, we
use the constructor:


TCReference.
TempConvert

tcs =



new

TCReference.
TempConvert
();



The namespace for the
TempConvert

class is
TCReference

(
the name of the
WebReference that we created
).
Y
ou could also just add a using statement at the
beginning of the class:


using

TCReference
;



If you do that, then you could use the following statement to instantiate a
TempConvert

object:


TempConvert

tcs =
new

TempConvert
();


Either way, now that we have the tcs object, we can invoke the
ToCelsius()

method:


double

convertedValue = tcs.ToCelsius(inputValue);


Remember, this is sending
inputValue

to the web service on
class1.sbm.temple.edu
. The server executes the
ToCelsius()

method using
inputValue
, and sends
a double back to the client, where it is assigned to the local
convertedValue

variable
.


Finally, we just convert
convertedValue

to a
string

and place it in the second
TextBox

(
TextBox2
).


TextBox2.Text = convertedValue.ToString();


Problem

1
:


Complete the application
by adding the code to the
“Convert to Fahrenheit” button (the
Button2
_Click()

method
). You’ll need to use the
ToFahrenheit()

method.



Creating
a Simple Web Service:
CarPayment


Now we’re going to create a web service that calculates the
monthly payment for a car
loan (well, it’s really for any type of loan with monthly payments).
The formula is:


Payment =

P × (r / 12)

(1


⠱‫⁲ ‱㈩

m
)


Where:



P is the principal of the loan


r is the interest rate


m is the number of payments


Our web service (hosted on class1.sbm.temple.edu) will have a method that takes P, r,
and m and returns the amount of the monthly payment.

Once we build the web s
ervice,
we’ll build another application (on our local computer) to consume it.


Create the web service


1)

In Visual Studio
2008
, create a new web site (File/New/Web Site…)


2)

Select the “ASP.NET Web
Service
” template.


3)

Make sure the “
HTTP
” is the value in th
e Location drop
-
down box and “Visual C#”
is the “Language.”


4)

Use the following URL to specify the location of the web service:


http://class1.sbm.temple.edu/
testuser
/carpayment


NOTE:

When you try
this yourself, you’ll need to use your own ID instead of
testuser
.

Then click “OK.”


5)

You’ll be asked to provide a user name and password to connect to class1. Provide
the username and password associated with your class1 account.


6)

You’ll see a shell of the web service. The web service will have two methods


Ser
vice()

and
HelloWorld()
.


Service()

is the constructor method for your web service (remember that a web
service i
s just another type of object).
HelloWorld()

is just for testing purposes.


The
HelloWorld()

method
has
the
[WebMethod]

header before the actu
al
method header. This is used to designate which methods are visible to clients
accessing the web service.

The exception to that is the constructor, which is
always
visible
by default
anyway.


7)

Change the name of the web service from
Service

to
CarPayment

by making a
few changes. First, change the class header like so:


public class CarPayment : System.Web.Services.WebService


This means the
CarPayment

class is a subclass of the
WebService

class.
Essentially, this is what makes our class a “web service” in
stead of an ordinary object.


Second, change the name of the constructor from
Service()

to
CarPayment()
.
T
he name of the constructor has to match the name of the class.


Save the
Service.cs
file. You’ll need to make one more change, this time to the
Servic
e.asmx

file. Double click on that file to edit it. It will have one line:


<%
@

WebService

Language
="C#"

CodeBehind
="~/App_Code/Service.cs"

Class
="Service"

%>


Change the
Class

parameter from “Service” to “CarPayment
.


Now save
Service.asmx and switch batch

to the Service.cs file.

You should be able to compile
the project (Build/Build Solution) without errors.


8)

Now we need to add the method that calculates the monthly payment. Add this
method to the class:


[
WebMethod
]

public

double

calcMonthlyPayment(
double

principal,




double

interestrate,
int

numpayments)

{


double

numerator = principal * (interestrate / 12);


double

denominator =



1

-

Math
.Pow(1 + interestrate / 12,
-
1 * numpayments);


double

mpayment = numerator / denominator;


return

mpayment;

}


Compare this to the formula on page 5 to make sure you understand how the code relates
to the formula.
Don’t forget to include
[WebMethod]

as the first line of the method.


9)

Rebuild the solution.
Y
ou’ve successfully created the web service.


Test the CarP
a
yment web service


1)

Visit

the following URL

in your web browser
:


http://class1.sbm.temple.edu/
testuser
/carpayment/Service.asmx


(Remember, use your own user name instead of
testuser
.)


You’ll see the following:




This is a
description of the
web service
, generated by the .NET Framework running
on class1,

presented as a web page.
Notice that the two “operations”


HelloWorld

and
calcMonthlyPayments



are the methods that had the
[WebMethod]

header.


2)

Click on “calcMonthlyPayme
nt.”

You’ll see the SOAP message associated with that
method:




Remember, SOAP stands for Simple Object Access Protocol.
It is
the
XML specification
for the exchange of data between a client and a web service.
Basically, SOAP specifies
the format of the
message.
So to call the method
calcMonthlyPayment()

with the
following values:

Principal



$15,000

Interest Rate



8%

Number of
payments


36


T
he following XML message is sent to the web service:


<?xml version="1.0" encoding="utf
-
8"?>

<soap:Envelope
xmlns:xsi="http://www.w3.org/2001/XMLSchema
-
instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">


<soap:Body>


<calcMonthlyPayment xmlns="http://tempuri.org/">


<principal>
15000
</principal>


<interestrate>
0.08
</interestrate>


<numpayments>36
</numpayments>


</calcMonthlyPayment>


</soap:Body>

</soap:Envelope>


And the following XML message is returned:


<?xml version="1.0" encoding="utf
-
8" ?>

<double xmlns="http://tempuri.org/"
>470.04548192146694</double>


The .NET platform determines

the format of the SOAP message using another “language”
called WSDL, which stands for Web Service Definition Language.

WSDL, in turn, is
created by Visual Studio at
compile

time by looking at the code (specifically, it looks at
the methods marked with the
[WebMethod]

header).

The WSDL specifies the
parameters and return values for each method.


To see the WSDL
, view this URL in your browser:


http://class1.sbm.temple.edu/tes
tuser/CarPayment/Service.asmx?wsdl


This is part of what you’ll see:


<s:element name="calcMonthlyPayment">

<s:complexType>

<s:sequence>

<s:element minOccurs="1" maxOccurs="1" name="principal"


type="s:double" />

<s:element minOccurs="1" maxOccurs="1"
name="interestrate"

type="s:double" />

<s:element minOccurs="1" maxOccurs="1" name="numpayments"


type="s:int" />

</s:sequence>

</s:complexType>

</s:element>

<s:element name="calcMonthlyPaymentResponse">

<s:complexType>

<s:sequence>

<s:element minOccur
s="1" maxOccurs="1" name="calcMonthlyPaymentResult"

type="s:double" />

</s:sequence>

</s:complexType>

</s:element>


You can see that the parameters and the return values are specified in the WSDL
(in bold).



Create an application that consumes the
CarPayment Web Service


1)

In Visual Studio
2008
, create a new web site (File/New/Web Site…)


2)

Select the “ASP.NET Web Site” template.


3)

Make sure the “File System” is the value in the Location drop
-
down box and “Visual
C#” is the “Language.”


4)

Look at the dire
ctory where the application will be stored. It probably looks
something like this:


C:
\
Documents and Settings
\
David Schuff
\
My Documents
\
Visual Studio
2008
\
WebSites
\
WebSite1


change the location to wherever you want, but the directory should end with

Payme
ntCalc
” (for example C:
\
VSProjects
\
PaymentCalc
).


5)

Click on the “Design” tab. You may also need to make the Toolbox visible
(View/Toolbox)


6)

Type “
Loan Payment Calculator
” as the first line on the web page.


7)

Drag four textboxes and one button to the web
page. Type “Amount of loan:” before
the first textbox, “Interest rate:” before the second textbox, “Number of payments:”
after the third textbox, and “Monthly payment:” after the fourth textbox. Change the
text of the button to “Calculate payment amount.”
Your page should look something
like this:




8)

Add the web reference to the CarPayment web service by
selecting “Add Web
Reference…” from the Website menu. Use the following URL:


http://class1.sbm.temple.edu/testuser/CarPayment/Service.asmx


When Visual S
tudio indicates the service has been found,
rename the WebReference
CPReference

and
click the “Add Reference” button.


9)

Double
-
click on the “Calculate payment amount” button to add code to the event
associated with the button.

10)

Add code to the
Button1_Click()

method like this:


protected

void

Button1_Click(
object

sender,
EventArgs

e)

{


CPReference
.
CarPayment

cpws =

new

CPReference
.
CarPayment
();



double

principal =
Convert
.ToDouble(TextBox1.Text);


double

intrate =
Convert
.ToDouble(TextBox2.Text);


int

numpayments =
Convert
.ToInt16(TextBox3.Text);




double

pmt = cpws.calcMonthlyPayment





(principal, intrate, numpayments);



TextBox4.Text = pmt.ToString();

}


You’ll notice

this is very similar to our previous example where we consumed the
TemperatureConversion

web service. First, we create a
CarPayment

object:


CPReference
.
CarPayment

cpws =



new

CPReference
.
CarPayment
();


Next, we convert the values in the first three textboxes


these correspond to the
parameters to be sent to the
calcMonthlyPayment()

method.


double

principal =
Convert
.ToDouble(TextBox1.Text);

double

intrate =
Convert
.ToDouble(TextBox2.Text);

int

numpaym
ents =
Convert
.ToInt16(TextBox3.Text);


Then we call that method:


double

pmt = cpws.calcMonthlyPayment




(principal, intrate, numpayments);


Finally, we take the value returned by the method (and assigned to the variable pmt)
and place it in the last
textbox:


TextBox4.Text = pmt.ToString();


11)

Finally, build and execute the application. You’ll see the following in your web
browser:




Test the application by entering
15000

for the loan amount,
0.08

for the interest
rate, and
36

for the number of payments. Click the button and you should see
470.04548192146694

appear in the last textbox (the calculated monthly
payment).


Problem 2:


Create a web service using your webspace on class1. Call the web service
“gradeService.” The serv
ice should have a single method called
calcLetterGrade()
. The method should take a single
double

value and return the
corresponding letter grade (a
string
) according to these rules:


90
-
100


A

80
-
89


B

70
-
79


C

60
-
69


D

0
-
59


F


The method should first
round the grade to the nearest whole number and then perform
the calculation.


Once the web service is complete, write an application on your local computer called
“gradeClient” that uses your new web service.
The application should look something
like thi
s:




The application should send the number the user types in the first textbox to the
gradeService
’s
calcLetterGrade()

method.
The return value of that method
should be placed in the second textbox.