DEMO 1: "Hello World!"
L'esempio più semplice che si possa immaginare (ma forse non è il più fantasioso...):
» Mostra / nascondi il codice sorgente dell'esempio
Client (javascript)
function HelloWorld()
{
var pl = new SOAPClientParameters();
SOAPClient.invoke(url, "HelloWorld", pl, true, HelloWorld_callBack);
}
function HelloWorld_callBack(r)
{
alert(r);
}
Server (WebMethod - C#)
public string HelloWorld()
{
return "Hello World!";
}
DEMO 2: Parametri (base)
Passaggio di un parametro al Web Method (vedi anche DEMO 12 ):
Il tuo nome:
» Mostra / nascondi il codice sorgente dell'esempio
Client (javascript)
function HelloTo()
{
var pl = new SOAPClientParameters();
pl.add("name", document.frmDemo.txtName.value);
SOAPClient.invoke(url, "HelloTo", pl, true, HelloTo_callBack);
}
function HelloTo_callBack(r)
{
alert(r);
}
Server (WebMethod - C#)
public string HelloTo(string name)
{
return "Hello " + name + "!";
}
DEMO 3: DateTime
Restituzione di una data ("DateTime" in .NET, automaticamente convertita dal proxy javascript in "Date")
» Mostra / nascondi il codice sorgente dell'esempio
Client (javascript)
function ServerTime()
{
var pl = new SOAPClientParameters();
SOAPClient.invoke(url, "ServerTime", pl, true, ServerTime_callBack);
}
function ServerTime_callBack(st)
{
var ct = new Date();
alert("Server: " + st.toLocaleString() + "\r\n[Client: " + ct.toLocaleString() + "]");
}
Server (WebMethod - C#)
public DateTime ServerTime()
{
return DateTime.Now;
}
DEMO 4: Metodi void
Chiamata di un metodo senza tipo di ritorno e con un sensibile tempo di attesa per simulare un processo server oneroso (in attesa della risposta dal server viene visualizzato un riquadro arancione):
Immediato (0 secondi)
Attendi 5 secondi
Attendi 10 secondi
Attendi 30 secondi
Attendere...
» Mostra / nascondi il codice sorgente dell'esempio
Client (javascript)
function Wait()
{
var duration = parseInt(document.frmDemo.ddSleepDuration[document.frmDemo.ddSleepDuration.selectedIndex].value, 10);
var pl = new SOAPClientParameters();
pl.add("seconds", duration);
var ph = document.getElementById("phWait");
ph.style.display = "block";
SOAPClient.invoke(url, "Wait", pl, true, Wait_callBack);
}
function Wait_callBack(r)
{
var img = document.getElementById("phWait");
img.style.display = "none";
alert("Chiamata al metodo \"Wait\" completata");
}
Server (WebMethod - C#)
public void Wait(int seconds)
{
System.Threading.Thread.Sleep(seconds * 1000);
return;
}
DEMO 5: Exception
Gestione delle eccezioni:
» Mostra / nascondi il codice sorgente dell'esempio
Client (javascript)
function ThrowException()
{
try
{
var pl = new SOAPClientParameters();
SOAPClient.invoke(url, "ThrowException", pl, false);
}
catch(e)
{
alert("Si è verificato un errore!");
}
}
function ThrowExceptionAsync()
{
var pl = new SOAPClientParameters();
SOAPClient.invoke(url, "ThrowException", pl, true, ThrowExceptionAsync_callBack);
}
function ThrowExceptionAsync_callBack(e)
{
if(e.constructor.toString().indexOf("function Error()") != -1);
alert("Si è verificato un errore!\r\n\r\n" + e.description + "\r\n\r\n[Codice dell'errore: " + e.number + "]");
}
Server (WebMethod - C#)
public void ThrowException(int seconds)
{
throw new Exception();
}
DEMO 6: Chiamate sincrone
Esempio di chiamata sincrona (la risposta del server è volutamente ritardata di 5 secondi, invocando il metodo "Wait" già visto nella DEMO 4; si noti che finché la richiesta non è terminata il browser risulta "bloccato"):
» Mostra / nascondi il codice sorgente dell'esempio
Client (javascript)
function SyncSample()
{
var pl = new SOAPClientParameters();
pl.add("seconds", 5);
var starttime = (new Date).toLocaleTimeString();
var r = SOAPClient.invoke(url, "Wait", pl, false);
alert("Operazione avviata alle " + starttime + "\r\nOperazione completata alle " + (new Date).toLocaleTimeString());
}
Server (WebMethod - C#)
public void Wait(int seconds)
{
System.Threading.Thread.Sleep(seconds * 1000);
return;
}
DEMO 7: Tipi di ritorno complessi (classi)
Ritorno di classi custom. Lasciando la casella di testo vuota il web metod restituirà null ; inserendo qualunque altro valore verrà restituito un oggetto User (le proprietà saranno valorizzate in modo casuale):
Username:
» Mostra / nascondi il codice sorgente dell'esempio
Client (javascript)
function GetUser()
{
var username = document.frmDemo.txtUsername.value;
var pl = new SOAPClientParameters();
pl.add("username", username);
SOAPClient.invoke(url, "GetUser", pl, true, GetUser_callBack);
}
function GetUser_callBack(u)
{
if(u == null)
alert("Nessun utente trovato.\r\n\r\nInserire uno username e riprovare ad effettuare la ricerca.");
else
alert(
"ID: " + u.Id + "\r\n" +
"USERNAME: " + u.Username + "\r\n" +
"PASSWORD: " + u.Password + "\r\n" +
"SCADENZA ACCOUNT: " + u.ExpirationDate.toLocaleString());
}
Server (WebMethod - C#)
public User GetUser(string username)
{
if (username.Trim().Length == 0)
return null;
int id = DateTime.Now.Millisecond;
string password = "PWD_" + DateTime.Now.Ticks.ToString();
DateTime expirationdate = DateTime.Now.Add(new TimeSpan(1, 0, 0, 0));
return new User(id, username, password, expirationdate);
}
User class:
[Serializable]
public class User
{
private int _id = -1;
private string _username = "";
private string _password = "";
private DateTime _expirationdate = DateTime.MinValue;
public User() { }
public User(int id, string username, string password, DateTime expirationdate)
{
this.Id = id;
this.Username = username;
this.Password = password;
this.ExpirationDate = expirationdate;
}
public int Id
{
get { return _id; }
set { _id = value; }
}
public string Username
{
get { return _username; }
set { _username = value; }
}
public string Password
{
get { return _password; }
set { _password = value; }
}
public DateTime ExpirationDate
{
get { return _expirationdate; }
set { _expirationdate = value; }
}
}
DEMO 8: Array
Array di oggetti. Il web method restituisce un array di 4 classi User (vedi il codice server della DEMO 7): User[]
» Mostra / nascondi il codice sorgente dell'esempio
Client (javascript)
function GetUsers()
{
var pl = new SOAPClientParameters();
SOAPClient.invoke(url, "GetUsers", pl, true, GetUsers_callBack);
}
function GetUsers_callBack(ul)
{
alert("Trovati " + ul.length + " utenti:");
for(var i = 0; i < ul.length; i++)
alert(
"Utente nr. " + (i + 1) + "\r\n\r\n" +
"ID: " + ul[i].Id + "\r\n" +
"USERNAME: " + ul[i].Username + "\r\n" +
"PASSWORD: " + ul[i].Password + "\r\n" +
"SCADENZA ACCOUNT: " + ul[i].ExpirationDate.toLocaleString());
}
Server (WebMethod - C#)
public User[] GetUsers()
{
User[] ul = new User[4];
Random r = new Random();
for (int i = 0; i < ul.Length; i++)
{
int id = r.Next(100);
string username = "USR_" + id.ToString();
string password = "PWD_" + id.ToString();
DateTime expirationdate = DateTime.Now.Add(new TimeSpan((i + 1), 0, 0, 0));
ul[i] = new User(id, username, password, expirationdate);
}
return ul;
}
DEMO 9: ICollection
Collection di oggetti (System.Collections.ICollection). Il web method restituisce un oggetto di tipo UserList , collection tipizzata di classi User (vedi il codice server della DEMO 7) con 3 elementi.
» Mostra / nascondi il codice sorgente dell'esempio
Client (javascript)
function GetUserList()
{
var pl = new SOAPClientParameters();
SOAPClient.invoke(url, "GetUserList", pl, true, GetUserList_callBack);
}
function GetUserList_callBack(ul)
{
alert("Trovati " + ul.length + " utenti:");
for(var i = 0; i < ul.length; i++)
alert(
"Utente nr. " + (i + 1) + "\r\n\r\n" +
"ID: " + ul[i].Id + "\r\n" +
"USERNAME: " + ul[i].Username + "\r\n" +
"PASSWORD: " + ul[i].Password + "\r\n" +
"SCADENZA ACCOUNT: " + ul[i].ExpirationDate.toLocaleString());
}
Server (WebMethod - C#)
public UserList GetUserList()
{
UserList ul = new UserList();
Random r = new Random();
for (int i = 0; i < 3; i++)
{
int id = r.Next(100);
string username = "USR_" + id.ToString();
string password = "PWD_" + id.ToString();
DateTime expirationdate = DateTime.Now.Add(new TimeSpan((i + 1), 0, 0, 0));
ul.Add(new User(id, username, password, expirationdate));
}
return ul;
}
UserList class:
[Serializable]
public class UserList : System.Collections.CollectionBase
{
public UserList() { }
public int Add(User value)
{
return base.List.Add(value as object);
}
public User this[int index]
{
get { return (base.List[index] as User); }
}
public void Remove(User value)
{
base.List.Remove(value as object);
}
}
DEMO 10: Applicazione concreta
Popolare una select in funzione di un valore selezionato:
Selezionare una casa automobilistica...
Volkswagen
FIAT
BMW
» Mostra / nascondi il codice sorgente dell'esempio
Client (javascript)
function GetCars()
{
var cid = document.frmDemo.ddCompany[document.frmDemo.ddCompany.selectedIndex].value;
if(cid != "")
{
// clear car list
while(document.frmDemo.ddCar.options.length > 0)
document.frmDemo.ddCar.remove(0);
// add waiting element
var o = document.createElement("OPTION");
document.frmDemo.ddCar.options.add(o);
o.value = "";
o.innerHTML = "Caricamento in corso...";
// disable dropdown
document.frmDemo.ddCar.disabled = true;
// invoke
var pl = new SOAPClientParameters();
pl.add("companyid", cid);
SOAPClient.invoke(url, "GetCars", pl, true, GetCars_callBack);
}
}
function GetCars_callBack(cl)
{
// clear car list
var c = document.frmDemo.ddCar.options.length;
while(document.frmDemo.ddCar.options.length > 0)
document.frmDemo.ddCar.remove(0);
// add first (empty) element
var o = document.createElement("OPTION");
document.frmDemo.ddCar.options.add(o);
o.value = "";
o.innerHTML = "Selezionare un modello...";
// fill car list
for(var i = 0; i < cl.length; i++)
{
var o = document.createElement("OPTION");
document.frmDemo.ddCar.options.add(o);
o.value = cl[i].Id.toString();
o.innerHTML = cl[i].Label;
}
// enable dropdown
document.frmDemo.ddCar.disabled = false;
}
Server (WebMethod - C#)
public Car[] GetCars(string companyid)
{
Car[] cl;
switch (companyid.Trim().ToLower())
{
case "vw":
cl = new Car[]
{
new Car(1, "Passat"),
new Car(2, "Golf"),
new Car(3, "Polo"),
new Car(4, "Lupo")
};
break;
case "f":
cl = new Car[]
{
new Car(1, "Stilo"),
new Car(2, "Punto"),
new Car(3, "500")
};
break;
case "bmw":
cl = new Car[]
{
new Car(1, "X5"),
new Car(2, "520")
};
break;
default:
cl = new Car[0];
break;
}
return cl;
}
Car class:
[Serializable]
public class Car
{
private int _id = -1;
private string _label = "";
public Car() { }
public Car(int id, string label)
{
this.Id = id;
this.Label = label;
}
public int Id
{
get { return _id; }
set { _id = value; }
}
public string Label
{
get { return _label; }
set { _label = value; }
}
}
DEMO 11: Utilizzare la risposta SOAP (xml)
Utilizzare la risposta XML del Web Service (ricevuta come secondo parametro dalla funzione di callback).
Nell'esempio viene semplicemente mostrato in un alertbox l'XLM della risposta SOAP completa.
A fini pratici potrebbe essere utile disporre lato client della risposta SOAP per manipolarla in modo completo (ad esempio effettuando trasformazioni con XSL)
» Mostra / nascondi il codice sorgente dell'esempio
Client (javascript)
function GetSoapResponse()
{
var pl = new SOAPClientParameters();
SOAPClient.invoke(url, "HelloWorld", pl, true, GetSoapResponse_callBack);
}
function GetSoapResponse_callBack(r, soapResponse)
{
if(soapResponse.xml) // IE
alert(soapResponse.xml);
else // MOZ
alert((new XMLSerializer()).serializeToString(soapResponse));
}
Server (WebMethod - C#)
public string HelloWorld()
{
return "Hello World!";
}
DEMO 12: Inviare parametri al Web Service (avanzato)
Inviare parametri complessi al Web Service.
Esempio 1: string, int, float, bool, Date
Esempio 2: string[]
Esempio 3: int[]
Esempio 4: User (custom object)
Esempio 5: User[] (custom object list)
» Mostra / nascondi il codice sorgente dell'esempio
Client (javascript)
function User(id, username, password, expirationdate)
{
this.Id = id;
this.Username = username;
this.Password = password;
this.ExpirationDate = expirationdate;
}
function SendSamples_callBack(r)
{
if(r.constructor.toString().indexOf("function Error()") != -1)
alert("ERROR\r\n\r\n" + r.description + "\r\n\r\n[" + r.number + "]");
else
alert(r);
}
function SendSample1()
{
var p1 = "This is a string";
var p2 = 34654;
var p3 = 3.14159;
var p4 = true;
var p5 = new Date();
var pl = new SOAPClientParameters();
pl.add("p1", p1);
pl.add("p2", p2);
pl.add("p3", p3);
pl.add("p4", p4);
pl.add("p5", p5);
SOAPClient.invoke(url, "SendSample1", pl, true, SendSamples_callBack);
}
function SendSample2()
{
var list = new Array();
list[0] = "element 1";
list[1] = "element 2";
list[2] = "element 3";
list[3] = "element 4";
var pl = new SOAPClientParameters();
pl.add("list", list);
SOAPClient.invoke(url, "SendSample2", pl, true, SendSamples_callBack);
}
function SendSample3()
{
var list = new Array();
list[0] = 235;
list[1] = 9876;
list[2] = 124;
list[3] = 79865;
list[4] = 53;
var pl = new SOAPClientParameters();
pl.add("list", list);
SOAPClient.invoke(url, "SendSample3", pl, true, SendSamples_callBack);
}
function SendSample4a()
{
var u = new User(34, "Administrator", "p@ss01!", new Date());
var pl = new SOAPClientParameters();
pl.add("user", u);
SOAPClient.invoke(url, "SendSample4", pl, true, SendSamples_callBack);
}
function SendSample4b()
{
var u = new Object();
u.Id = 5271;
u.Username = "Guest1";
u.Password = "GuestP@ss!";
u.ExpirationDate = new Date();
u.ExpirationDate.setMonth(u.ExpirationDate.getMonth() + 1);
var pl = new SOAPClientParameters();
pl.add("user", u);
SOAPClient.invoke(url, "SendSample4", pl, true, SendSamples_callBack);
}
function SendSample4c()
{
var u = new Array();
u["Id"] = 654;
u["Username"] = "Guest2";
u["Password"] = "GuestP@ss!";
u["ExpirationDate"] = new Date();
u["ExpirationDate"].setMonth(u["ExpirationDate"].getMonth() + 1);
var pl = new SOAPClientParameters();
pl.add("user", u);
SOAPClient.invoke(url, "SendSample4", pl, true, SendSamples_callBack);
}
function SendSample5()
{
var ul = new Array();
ul[0] = new User(52342, "User1", "User1P@ss!", new Date());
ul[1] = new User(453, "User2", "User2P@ss!", new Date());
ul[2] = new User(5756, "User3", "User3P@ss!", new Date());
ul[3] = new User(5431, "User4", "User4P@ss!", new Date());
var pl = new SOAPClientParameters();
pl.add("userlist", ul);
SOAPClient.invoke(url, "SendSample5", pl, true, SendSamples_callBack);
}
Server (WebMethod - C#)
public string SendSample1(string p1, int p2, double p3, bool p4, DateTime p5)
{
return
"P1 - string = " + p1 + "\r\n" +
"P2 - int = " + p2.ToString() + "\r\n" +
"P3 - double = " + p3.ToString() + "\r\n" +
"P4 - bool = " + p4.ToString() + "\r\n" +
"P5 - DateTime = " + p5.ToString() + "";
}
public string SendSample2(string[] list)
{
return
"Length = " + list.Length.ToString() + "\r\n" +
"First element = " + list[0] + "\r\n" +
"Last element = " + list[list.Length - 1] + "";
}
public string SendSample3(int[] list)
{
return
"Length = " + list.Length.ToString() + "\r\n" +
"First element = " + list[0].ToString() + "\r\n" +
"Last element = " + list[list.Length - 1].ToString() + "";
}
public string SendSample4(User user)
{
return
"Id = " + user.Id.ToString() + "\r\n" +
"Username = " + user.Username + "\r\n" +
"Password = " + user.Password + "\r\n" +
"ExpirationDate = " + user.ExpirationDate.ToString() + "";
}
public string SendSample5(User[] userlist)
{
string s = "Length = " + userlist.Length.ToString() + "\r\n\r\n";
for (int i = 0; i < userlist.Length; i++)
s +=
"Id = " + userlist[i].Id.ToString() + "\r\n" +
"Username = " + userlist[i].Username + "\r\n" +
"Password = " + userlist[i].Password + "\r\n" +
"ExpirationDate = " + userlist[i].ExpirationDate.ToString() + "\r\n\r\n";
return s;
}