Consuming ASP.NET Web Service in Silverlight

SheoNarayan
Posted by in Silverlight category on for Beginner level | Views : 39641 red flag
Rating: 5 out of 5  
 1 vote(s)

This article describes how to consume ASP.NET web service in Silverlight in easy to follow steps.
Introduction
In today's world of information technology, Web Service is the best way to share information from one application to another without thinking on which platform or language it is built on or who is going to consume it. We can consume Web Service into Silverlight application too. This article describes how to create a web service (that return list of customers data) and how to consume it in easy to follow steps.
Creating a Web Service

Let's see how to create a Web Service. To do that, right click the Web project and select Web Service from the template box, click Add. By default, you will have HelloWorld method. Delete this method and add following code.

    /// <summary>
/// Get customers data
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
[WebMethod]
public List<Customer> GetCustomers(string s)
{
return new DataAccessLayer.DataAccessLayer().GetCustomers(s);
}

Note that in order to use List<T>, you will need to use System.Collections.Generic namespace. In the above code snippet, I am using GetCustomer() method of a DataAccessLayer class to return customers data. This method (GetCustomer method) is accepting a string parameter to filter the customer whose name starts with the parameter value (This is just a method with added functionality, do not get involve into it to avoid any confusion, just assume that this will return list of customers data.) Let's see the GetCustomer() method of DataAccessLayer class code.

        /// <summary>
/// Get customers
/// </summary>
/// <returns></returns>
public List<Customer> GetCustomers(string startsWith)
{
List<Customer> list = new List<Customer>();

using (SqlConnection conn = new SqlConnection("[WriteConnectionString]"))
{
conn.Open();
using (SqlCommand dCmd = new SqlCommand("vs_GetCustomersStartingWith", conn))
{
SqlParameter prms = new SqlParameter("@startsWith", SqlDbType.VarChar, 5);
prms.Value = startsWith + "%";
dCmd.Parameters.Add(prms);
dCmd.CommandType = CommandType.StoredProcedure;
using (SqlDataReader reader = dCmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(new Customer
{
CustomerID = reader["CustomerID"].ToString(),
Address = reader["Address"].ToString(),
City = reader["City"].ToString(),
Country = reader["Country"].ToString(),
ContactName = reader["ContactName"].ToString()
});
}
}
}
conn.Close(); // lets close explicitely
}
return list;
}

Get solutions of the .NET problems with video explanations, .pdf and source code in .NET How to's.

Note: Above method is a sample method, you should customize it based on your requirement.

In the above method, I am using a stored procedure to get the data and passing parameter to filter the data. I am instantiating a Customer object that has CustomerID, Address, City, Country, ContactName as property and setting its value inside the while loop. (If you are getting confused, just understand that this method will return list of data having Customer objects into it.)

You can run the web project and try this web service. For me, the url of the web service looks like "http://localhost:1238/SilverlightApplication.Web/DataWebService.asmx"

So till now, we have our Web Service ready to be called from Silverlight. Let's design Silverlight page now.

Consuming Web Service in Silverlight

Create a .xaml file and delete all code except <UserControl> and place following code snippet inside <UserControl> tag.

<Grid x:Name="LayoutRoot" Background="White">
<Canvas>
<TextBlock Text="Search" Canvas.Left="10" Canvas.Top="12"></TextBlock>
<TextBox x:Name="txtSearch" Width="75" Height="22" Canvas.Left="55" Canvas.Top="10"></TextBox>
<Button Content=" Get Data from Web Service " Click="Button_Click" Canvas.Top="9" Canvas.Left="140"></Button>
<TextBlock x:Name="lblWaiting" Canvas.Left="375" Canvas.Top="10" Text="Status: Idle"></TextBlock>
<data:DataGrid x:Name="dataGrid1" Canvas.Left="10" Canvas.Top="35" Width="550" Height="300" IsReadOnly="True"
ItemsSource="{Binding Mode=OneWay}" AutoGenerateColumns="True" >
</data:DataGrid>
</Canvas>
</Grid>

In the above code snippet, I have done following:

  1. Placed a TextBlock to keep a label called "Search".
  2. Placed a TexttBox to enter filter criteria.
  3. Placed a button that will fire Button_Click event upon clicking.
  4. Again placed a TextBlock that will show Status of what is happening (Please wait ... message when getting data from database).
  5. Placed a DataGrid control that will show the data into tabular format.
Adding reference to the web service

Now, lets try to consume the web service. To consume the web service, first we need to reference it into our application, so let's do that.

In the SilverlightApplication project, right click and click "Add Service Reference ....", Place the url of the web service in the Address box and click Go. You should see your Web Service in the Services box. You can keep the default namespace or change it as per your need. Click OK. You will notice that the reference of your web service will be done (look out the Service References folder). Also notice that ServiceReferences.ClientConfig file will be created. This ClientConfig file contains other necessary tag to reference the web service and apart from that it also contains the endpoint tag that has address attribute. This attribute has the url of the web service (we need to change this url when hosting our application on the server, we shall talk about it later in this article).


Now let's see how to use this web service in the code. See following code snippet.

        

// Fires on click event
private void Button_Click(object sender, RoutedEventArgs e)
{
// call data web service
ServiceReference2.DataWebServiceSoapClient dataService = new SilverlightApplication.ServiceReference2.DataWebServiceSoapClient();
dataService.GetCustomersCompleted += new EventHandler<SilverlightApplication.ServiceReference2.GetCustomersCompletedEventArgs>(dataService_Completed);
dataService.GetCustomersAsync(txtSearch.Text.Trim());

// call simple web service
lblWaiting.Text = "Status: Waiting ...";
}



// event that will fire after completion of the web service call
private void dataService_Completed(object sender, ServiceReference2.GetCustomersCompletedEventArgs e)
{
ServiceReference2.Customer[] list = e.Result;

dataGrid1.ItemsSource = list;

lblWaiting.Text = "Status: Done";

if (list.Length.Equals(0))
lblWaiting.Text = "No records found.";
else
lblWaiting.Text = list.Length + " records found.";

}

In the Button_Click method, I have instantiated the web service first. Then attaching method dataService_Completed method with the GetCustomersCompleted event handler. Note that this event handler name is based on your web service method name. (If you web service method name will be GetMyData, this event handler name will become GetMyDataCompleted, same applies to then following line, GetCustomersAsync in this case this method will become GetMyDataAsync). In the next line, I am passing filter parameter to the GetCustomersAsync method.

As specified above, once the method call will be completed, dataService_Completed method will fire. In this method, I am getting the result into the array of Customer object and specifying the ItemsSource property of the DataGrid. Just to display the status of what is happening in between, I have also set the value of lblWaiting (TextBlock) in this as well as Button_Click method.

Thats it!, just run your application and try clicking the "Get Data From Web Service" button after entering filter criteria, you will see that data will be populated to the DataGrid.

Hosting your application on Live Server

To host your Silverlight application on the server, you need to place the ClientBin/xxx.xap file on your server. Create the subdirectory "ClientBin" under root and place your .xap file. But notice that the web service address on your development machine (local) and live server will be different. So if you directly put your local .xap file on the server, it will not work. Lets see what sort of things are necessary to do here.

  1. Host your web service on the server (Simply copy paste the web service file on the server and try accessing the url.
  2. Open the ServiceReferences.ClientConfig file from your local Silverlight project and change the endpoint/address value to the url of the live server web service.
  3. Build the application again.
  4. Now copy your ClientBin/xxx.xap file from your local machine to the server and try to access run your server application. Hope this will work.


Cool !!! so in this article, we learnt how to create and consume ASP.NET web service in Silverlight. Please let me know your feedback or suggestions. Thanks for reading and happy coding !!!

Page copy protected against web site content infringement by Copyscape

About the Author

SheoNarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)