In Silverlight application since version 2 appeared to
establish communication with a server became very convenient. For receiving
some data through HTTP protocol in Silverlight, it is possible to use two
mechanisms - WebClient and HttpWebRequest.
The WebClient allows easier access to a server, but it is
less flexible. The example of WebClient usage is shown in listing 1.
Listing 1 - Sample of usage WebClient
private void Communicate()
{
var client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadProgressChanged += client_DownloadProgressChanged;
client.DownloadStringAsync(new Uri(@"http://localhost/mydata.xml"));
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
// inform client about progress
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
var data = e.Result;
// use the variable "data"
}
else
{
// error
}
}
Other ways consist of using the HttpWebRequest/HttpWebResponse
object. An example of WebRequest usage is shown in listing 2.
Listing 2 - Sample of usage WebRequest
private void Communicate()
{
var webRequest = WebRequest.Create("http://localhost/mydata.xml") as
HttpWebRequest;
webRequest.Method = "GET";
webRequest.BeginGetResponse(ResponseCallback, webRequest);
}
void ResponseCallback(IAsyncResult ar)
{
var webRequest = ar.AsyncState as HttpWebRequest;
var webResponse = webRequest.EndGetResponse(ar);
var responseStream = webResponse.GetResponseStream();
// reading the stream
}
These two ways can be used when it is necessary to obtain
any data via HTTP protocol. However, if we work with web-services, it is more
convenient to use a proxy-class and to do calls through it. This approach hides
details of receiving data through WebRequest object, parsing and XML generation
in SOAP/REST format.
It is necessary to use "Add Service Referece" item
in popup menu of "References" item to create proxy-class.
Figure 1: Adding service reference
After proxy-class generation one can use it easily. The
example of the access to service is shown in listing 3.
Listing 3 - An accessing to the service
private void Button_Click(object sender, RoutedEventArgs e)
{
WebService1SoapClient client = new WebService1SoapClient();
client.HelloWorldCompleted += client_HelloWorldCompleted;
client.HelloWorldAsync();
}
void client_HelloWorldCompleted(object sender, HelloWorldCompletedEventArgs e)
{
var result = e.Result;
// do something
}