Sei sulla pagina 1di 66

2012

University of Greenwich
1
Introduction to Web
Services using Microsoft
VisualStudio
Dr Kevin McManus
http://staffweb.cms.gre.ac.uk/~mk05/web/dotnet/
2012
University of Greenwich
2
The Microsoft .NET Platform

Visual Studio .NET
.NET Enterprise
Servers

SQL Server 2005
Win Server 2003
.NET Framework

CLR, C#, ASP.NET,
etc.
.NET Services

e.g. Microsoft
Passport

Operating System e.g. Windows XP, Windows 2000, Linux
2012
University of Greenwich
3
The Microsoft .NET Framework

XML based
Web Services

Web Forms
ASP.NET

Windows Forms

Library classes for accessing data and XML
(ADO.NET, SQL, XML, XSLT)

Library Framework Base classes
(IO, string, collections, security)

Common Language Runtime
2012
University of Greenwich
4
Common Language Runtime

Program written in any .NET supported language
C#, VB.NET, etc.

Intermediate Language (IL) - like Java bytecode
(.exe or .dll)
compile
Common Language Runtime

Loads and executes code, garbage collects etc
2012
University of Greenwich
5
Demonstration 1
Creating a Web Service using Visual Studio
Service 1

Convert Fahrenheit to Celsius
SOAP request
SOAP response
VisualStudio 2010 has arrived
yet another new system to get to grips with
Using Visual Studio 2010 create a new project
select ASP.NET Web Service
framework 3.5 or lower
you can use either a VB or C#
C# in this example
because nobody in their right minds uses VB.NET
2012
University of Greenwich
Demonstration 1
Creating a Web Service using Visual Studio
VisualStudio 2010 has arrived
yet another new system to get to grips with
Using Visual Studio 2010 create a new project
select ASP.NET Web Service
framework 3.5 or lower
you can use either a VB or C#
C# in this example
because nobody in their right minds uses VB.NET

Service 1
Convert Farenheit to Celcius
SOAP request
SOAP response
2012
University of Greenwich
7
Creating a Web Service using
Visual Studio .NET
We used to begin by configuring Visual Studio.NET
to allow you to use the CMS student IIS web server
Tools -> Options -> Projects -> Web Settings
use Front Page Extensions to access the web server
as of Visual Studio 2005
we can't do this any more

see the lab support web
site for details of how to publish
2012
University of Greenwich
8
Creating a Web Service using
Visual Studio
Choose Create... Web Site
choose C#
put it on your I: drive so
that it can be published
choose ASP.NET Web Service
at least we can provide
names before creating
the service
choose 3.5 to be
offered a web service
on the menu
2012
University of Greenwich
9
Creating a Web Service using
Visual Studio
change the name of
Service.asmx to
something sensible
a Hello World code
template for the web
service is automatically
created for you
2012
University of Greenwich
10
Creating a Web Service using
Visual Studio
Compile and build and run the Web
Service with Cntrl F5
This will throw some errors because we
altered the name of the service
this is easily repaired by looking in
CalcTemp.asmx
View markup
VS will fire up a localhost web server and
our favourite browser for us
scaffolding is generated to test the service
2012
University of Greenwich
11
Creating a Web Service using
Visual Studio
note the URL
link to the WSDL
link to the
test page
form to test
the service
2012
University of Greenwich
12
Creating a Web Service using
Visual Studio
You will need to be very nice to our technical
support staff to get the next bit to work
note the URL
2012
University of Greenwich
13
Creating a Web Service using
Visual Studio
add a namespace
attribute definition
add a new
web method
this is web service
class definition
2012
University of Greenwich
14
Creating a Web Service using
Visual Studio
/// namespace CalcTemp {
[WebService(Namespace="http://some.name.space")]

public class CalcTemp : System.Web.Services.WebService {

public CalcTemp() {
///InitializeComponent();
}

/// wedge of code

[Web Method]
public double toCentigrade ( double dFarenheit ) {
return ( dFarenheit - 32 ) * 0.555555555555;
}

}
}
2012
University of Greenwich
15
Creating a Web Service using
Visual Studio
Re-build our Web Service - F6
no need to re-inform technical support
Refresh the browser and try the new
service
2012
University of Greenwich
16
form uses POST
to test the Web
Service
result is a
SOAP primitive
note the new tab
this does not test the
SOAP

need to do a little more
to test the SOAP
2012
University of Greenwich
17
Creating a Web Service using
Visual Studio
The same application can be implemented
using VB.NET
VB.NET is remarkably similar to C#

<WebService(Namespace := "http://some.name.space")>

Public Class CalcTemp Inherits System.Web.Services.WebService

<WebMethod(Description:="Converts degrees Farenheit to Celsius.")>

Public Function toCentigrade(ByVal dFahrenheit As Double) As Double
toCentigrade = (dFahrenheit - 32) * 0.555555555555
End Function

End Class
2012
University of Greenwich
18
Accessing a Web Service using
Visual Studio
This demo creates a VB.NET program (standard
windows program) to access the Web Service
The principle is the same for accessing any Web
Service made available over the Web.
CalcTemp

Convert Fahrenheit to Celsius
SOAP request
SOAP response
2012
University of Greenwich
19
Accessing a Web Service using
Visual Studio
Create a Windows Application project - a standard windows executable
2012
University of Greenwich
20
Accessing a Web Service using
Visual Studio
If you see this you need to persuade your .NET
install to trust you
part of the new M$ paranoid approach
just a configuration problem
2012
University of Greenwich
Trust in VS 2010
even more annoying than previously
On your local machine
Control Panel -> System and Security -> Administrative Tools -> Microsoft .NET Framework Configuration
2012
University of Greenwich
22
Accessing a Web Service using
Visual Studio
Add GUI elements to the form in usual VB style
toolbox of GUI
components
2012
University of Greenwich
23
Accessing a Web Service using
Visual Studio
add a Web Reference to the
project - this will allow your code
to access the remote Web
Service

from the Project menu choose
Add Web Reference

enter the URL to which the Web
Service was deployed. The
WSDL will be displayed

2012
University of Greenwich
24
Accessing a Web Service using
Visual Studio
tooled up approach
helps with using the
web reference
web references
appear in the
project browser
2012
University of Greenwich
25
Accessing a Web Service using
Visual Studio
Private Sub btnConvert_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs)
Handles btnConvert.Click

Dim webServ As New uk.ac.gre.cms_stu_iis.calcTemp()
Dim dF As Double
Dim dC As Double
dF = Convert.ToDouble(txtFarenheit.Text)
dC = webServ.toCentigrade(dF)
lblCel.Text = dF.ToString() + " degrees Fahrenheit
is " + dC.ToString() + " degrees Celcius"

End Sub
write VB code that accesses the service
double click the button to get the event handler template
note the big-
endian format
2012
University of Greenwich
26
Accessing a Web Service using
Visual Studio
Build and test by running the VB program
2012
University of Greenwich
27
Same thing in C#
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnConvert_Click(object sender, EventArgs e)
{
uk.ac.gre.cms_stu_iis.calcTemp webService = new uk.ac.gre.cms_stu_iis.calcTemp();
double dF = Convert.ToDouble(txtFahrenheit.Text);
try
{
double dc = webService.toCentigrade(dF);
lblCelsius.Text = Convert.ToString(dF) + " degrees Farenheit is " +
Convert.ToString(dc) + " degrees Celsius";
}
catch(Exception ex)
{
lblCelsius.Text = "Sorry: service is offline";
}
}
}
take a slightly better
programmatic
approach with C#
2012
University of Greenwich
28
Accessing a .NET web service using PHP
This form POSTs to itself and forwards the temperature in
Fahrenheit as a GET parameter to the temperature
conversion web service
The SOAP free XML result is flattened into a string that is
read into a DOM model
2012
University of Greenwich
29
<body>
<h1>Temperature Conversion</h1>
<h2>Using ASP.NET Web Service</h2>
<form method="post" action="CalcTempGETclient.php">
<p>
<input type="text" name="dFarenheit" value="32"/>
<input type="submit" value="Convert"/>
</p>
</form>
<p>
<?php
$dF = '32';
if ( isset($_POST['dFarenheit']) ) $dF = $_POST['dFarenheit'];
$WS = 'http://cms-stu-iis ... /CalcTemp.asmx/toCentigrade?dFarenheit=' . $dF;
$doc = new DOMDocument();
loadDOM($doc, $WS) or die('<p>Unable to contact Web Service</p>');
$dC = $doc->documentElement->firstChild->textContent;
echo "$dF degrees Farenheit is $dC degrees Celsius\n";
?>
</p>
</body></html>
CalcTempGETclient.php
receive dFarenheit as
POST from the form
forward dFarenheit
as GET to the web
service
contact the Web Service
and read result into
DOM object
(not a builtin)
read the DOM to access
degrees Celsius
2012
University of Greenwich
30
<?php
function loadDOM(&$dom, $url) {
$xmlString = "";
if ( $xmlArray = file($url) ) {
foreach ( $xmlArray as $node ) {
$xmlString .= trim($node);
}
$dom->loadXML($xmlString);
return true;
} else {
return false;
}
}
?>
CalcTempGETclient.php
Function to read XML from
a URL into a DOM object
Would be better if this could
be added as a method to the
DOM class currently
experimental in PHP?
remember that nasty
business of having to
remove whitespace from
the XML
2012
University of Greenwich
31
PHP SOAP Client
Spot the difference
Much the same but using a SOAP transport
2012
University of Greenwich
32
<body>
<h1>Temperature Conversion</h1>
<h2>Using ASP.NET Web Service</h2>
<form method="post" action="CalcTempSOAPclient.php">
<p>
<input type="text" name="dFarenheit" value="32"/>
<input type="submit" value="Convert"/>
</p>
</form>
<p>
<?php
$dF = '32';
if ( isset($_POST['dFarenheit']) ) $dF = $_POST['dFarenheit'];
$dF = (double)$dF;
try {
$client = new SoapClient("http://cms-stu-iis ... /CalcTemp.asmx?WSDL");
$dC = $client->toCentigrade(array('dFarenheit'=>$dF))->toCentigradeResult;
echo "$dF degrees Farenheit is $dC degrees Celsius\n";
} catch ( Exception $e ) {
echo '<p>Unable to contact Web Service</p>';
echo '<p>Caught exception: ', $e->getMessage(), "</p>\n";
}
?>
</p>
</body></html>

CalcTempSOAPclient.php
receive dFarenheit as
POST from the form
instantiate a SOAP
client with the
WSDL
pass an array containing
dFarenheit to the Web
Service
2012
University of Greenwich
33
Asynchronous Consumption of a
.NET Web Service using JavaScript
This AJAX example passes the value from the text box
to the web service as a GET parameter
no need to send the form back to a server
uses DOM programming to access the returned value
Has to be on cms-stu-iis
Why?
2012
University of Greenwich
34
<head>
<title>JavaScript Web Service AJAX Example</title>
<script type="text/javascript"><!--

var dF = null;
var xmlDoc = null;
if ( document.implementation.createDocument ) {
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.onload = DoIt;
} else if ( window.ActiveXObject ) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.onreadystatechange = function () {
if (xmlDoc.readyState == 4) DoIt()
}
} else {
alert('Your browser can\'t handle this script');
}

function DoIt() {
var output = dF + ' degrees Farenheit is ';
var dC = xmlDoc.documentElement.firstChild.nodeValue;
output = output + dC + ' degrees Celsius';
document.getElementById("data").innerHTML = output;
}
useCT.html
instantiate an XML
document and assign
a callback function
Mozilla style
IE style
callback function
2012
University of Greenwich
35
function useCT() {
dF = document.getElementById('dFarenheit').value
var url = '../calcTempWS/calcTemp.asmx/toCentigrade?dFarenheit=' + dF;
xmlDoc.load(url);
}
//--></script>

</head>
<body>
<h1>JavaScript Web Service AJAX Example</h1>
<p>
<input type="text" name="dFarenheit" id="dFarenheit"/>
<input type="button" onclick="useCT()" value="Convert" />
</p>
<div id="data"></div>
</body>
useCT.html
function passes the value
from the form to web service
as a GET parameter
span used to write the
output from DoIt()
onClick event calls the
web service
2012
University of Greenwich
36
function getHTTPobject() {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
alert('Not an ActiveXObject');
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
alert('ActiveXObject');
}
return xmlhttp;
}

var http = getHTTPobject();

// Send request asynchronusly
function requestXML(ServiceURL) {
http.open("GET",ServiceURL,true);
http.onreadystatechange = handleHttpResponse; //assign callback function
http.send(null);
}

// Event handler for the XML response
function handleHttpResponse() {
if (http.readyState == 4) {
xmlDoc = http.responseXML; // returns a DOM object
DoIt();
}
}
useCT-XMLHttpRequest.html
instantiate an
XMLHttpRequest
object
assign callback
function
callback function
XMLHttpRequest object returns a DOM object
2012
University of Greenwich
useCT-XMLHttpRequest.html
function DoIt() {
var output = dF + ' degrees Farenheit is ';
var dC = xmlDoc.documentElement.firstChild.nodeValue;
output = output + dC + ' degrees Celsius';
document.getElementById("data").innerHTML = output;
}

function useCT(theForm) {
dF = theForm.dFarenheit.value;
var CTurl = 'CalcTemp/CalcTemp.asmx/toCentigrade?dFarenheit=' + dF;
requestXML(CTurl);
}
//--></script>

</head>
<body>
<h1>JavaScript Web Service AJAX Example</h1>
<form action="dummy">
<p>
<input type="text" name="dFarenheit" value="32"/>
<input type="button" onclick="useCT(this.form)" value="Convert" />
</p>
</form>
<div id="data"></div>

parse result and output
form URL and call the service
handle the onclick event
the output goes here
2012
University of Greenwich
38
Creating Web Applications using
Visual Studio
Client
machine
Server machine
Browser
Web
server
ASP
code
database
HTTP
HTML
Web Services may be important but there will still be a need for human
facing web applications i.e. code on the web server that dynamically
generates web pages
ASP.NET replaces ASP for delivering
dynamically generated web pages
2012
University of Greenwich
39
Problems with ASP
Easy to end up with hideous spaghetti code
HTML + VBScript + CSS + JavaScript all intertwined
But a good programmer would separate these into
files
No easy way to cope with browser compatibility
problems when generating client-side code
Although browser compatibility issues are reducing as
standards become more mature
Script code interpreted at run-time
inefficient
not very robust
Preserving state using the ASP Session object is
inefficient
2012
University of Greenwich
40
ASP.NET
Development is totally forms-based (called Web Forms)
everything is drag and drop
GUI controls that know how to render themselves for a range of
clients
rather better on IE than other browsers if you are not careful
Create event code (e.g. for a button) in a VB fashion
Application code can be written in any Microsoft .NET language
C#, VB.NET, etc.
full programming languages, not scripting languages
Server-side code and presentation code (HTML) are separated
application code stored in a code behind file
can be fully compiled managed code
increased efficiency
Session handling improved
echoing back data entered in a form is made automatic.
ASP.NET addresses the problems of ASP
2012
University of Greenwich
41
Creating Web Applications using
Visual Studio
Create an ASP.NET Web Site project
-can use C# or VB.NET
Creating Web Applications using
Visual Studio
The form layout goes in a .aspx file
The C# (or VB) code goes in a .aspx.cs file - called a code behind file
Creating Web Applications using
Visual Studio
Drag and drop GUI elements from the ToolBox onto the form
Creating Web Applications using
Visual Studio
Clicking the Source tab reveals all is not quite as it seems
the GUI elements are Server
controls also called Web Form
controls.

code is executed at the server end
which results in appropriate (you
hope) HTML being sent to the
client to render the control
Creating Web Applications using
Visual Studio
Double click the button and enter the code in its event procedure
Label1.Text = TextBox1.Text + TextBox2.Text;
2012
University of Greenwich
46
Creating Web Applications using
Visual Studio
Build and run the application
not exactly the result
we had in mind
2012
University of Greenwich
47
Creating Web Applications using
Visual Studio
Look at the code sent to the client
not a pretty sight but
not as bad as things
used to be with
VS.NET
note the hidden
form fields
2012
University of Greenwich
48
Creating Web Applications using
Visual Studio
Add a style sheet to the project
2012
Creating Web Applications using
Visual Studio
Either type style rules into the style sheet - with tool tips
Or use the wizard...
possibly the best CSS
tool currently
available!!
2012
University of Greenwich
50
Creating Web Applications using
Visual Studio
fix that code in
the code behind
2012
University of Greenwich
51
Creating Web Applications using
Visual Studio
so far so good
but what if we try to
add 'three' to 'four'?
2012
University of Greenwich
52
Adding Validation
The data expectation for the calculator is
two integers
will get a runtime error if
input is missing
the strings do not parse as integers
Add validators to check for
empty fields
invalid strings data type check
Other validation is possible with regular
expressions
2012
University of Greenwich
53
Adding Validation
drag required field
validators from the
toolbox onto the
design surface
add a suitable message
and assign the validator
to a text box
2012
University of Greenwich
54
Adding Validation
this seems to do what
we wanted
note: this validation
is client side
better look at the
page source
2012
University of Greenwich
55
Adding Validation
CSS keeps the
validation message
hidden
tests the DOM to use either
document.all or
document.getElementById
2012
University of Greenwich
56
Adding Validation
drag comparison validators
from the toolbox onto the
design surface
choose the data type
check comparison
operator and select
integer type
2012
University of Greenwich
57
Adding Validation
hurrah!
it could be a little more elegant
but do you really want to start
messing around with that tool
generated code?
2012
University of Greenwich
58
Adding Validation
we should get both client and
server side validation from these
controls...
but if JavaScript is turned off in
the client the server throws an
exception
2012
University of Greenwich
59
Adding Validation
Need to persuade the server to validate
Test the isValid property of the page
causes the page.Validate() method to execute
private void Button1_Click(object sender, System.EventArgs e)
{
if ( this.IsValid )
{
int i = int.Parse(TextBox1.Text) + int.Parse(TextBox2.Text);
Label2.Text = TextBox1.Text + " plus " +
TextBox2.Text + " = " + i.ToString();
} // no need to do anything else
}
2012
University of Greenwich
60
Adding Validation
looks just the same
but now the form has been sent
back to the server
look at the source to see the
change
2012
University of Greenwich
61
Adding Validation
those styles have been
changed so the validation
messages default to visible
2012
University of Greenwich
62
Is that it?
Clearly there is an awful lot more
Data binding
View state
Sessions
AJAX
Cache control
Exception handling
Assemblies
Sign up for the MCAD certification programme
Kalani
MCAD/MCSD Training Guide 70-315: Developing and Implementing
Web Applications with Visual C#.NET and Visual Studio.NET
2012
University of Greenwich
63
Possible disadvantages to using
ASP.NET
The spaghetti is untangled and the code behind looks nice and tidy
but would you want to mess about with those web forms without a tool
like VS05
and that JavaScript - if it doesn't do exactly what you want are you
brave enough to mess with it?
tools are fantastic but they are not as flexible as code
they stifle creativity
Tempting to write code that requires lots of postbacks
Rather different from current ASP coding
a different way of thinking
Hosting is more expensive than open source solutions
although this may reduce with the advent of Mono
Danger of becoming trapped in a Microsoft universe
although this may reduce with the advent of Mono
2012
University of Greenwich
64
References
Thai T., Lam H. Q., (2002), .NET Framework
Essentials, 2nd edition, OReilly

Liberty J., Hurwitz D., (2002), Programming ASP.NET,
OReilly

Microsoft Research, (2001), .NET Crash course for
Faculty and PhDs

Kalani, A., (2002), MCAD/MCSD Developing and
Implementing Web Applications with Visual C# .NET and
Visual Studio .NET
2012
University of Greenwich
65
Summary
Visual Studio can be used by complete novices to create
web services, web applications and service oriented
windows applications
three mouse clicks and youre all soaped up and ready to roll
powerful tools in the hands of the inexperienced can be dangerous
do we really need all that SOAP?
The .NET vision assumes high bandwidth
all those trips back to the server
little regard for standards and accessibility
although much better now
you can still do things the good old fashioned way
but then you dont benefit from the tooled up environment
2012
University of Greenwich
Questions?

Potrebbero piacerti anche