jump to navigation

Using ASP.Net web services in Silverlight 4 applications November 20, 2011

Posted by fofo in Silverlight, Silverlight 4.
Tags: , ,
trackback

In this post I would like to present in detail how we can consume .asmx web services from a Silverlight 4 application. Silverlight supports and “recognises” web services in a similar way that ASP.Net applications can “talk” to web services. One might say that .asmx web services are considered by Microsoft legacy software. I will not disagree with that. Sometimes we do not have the luxury (time or budget) to create the services from scratch. It is very difficult to convince your boss or client to create a WCF service that does something when the functionality already exists in a web service (.asmx). So if now, I have the chance to write a whole Silverlight application from scratch I would not use .asmx web services, I would use WCF. But as I said before we have to use and maintain legacy code.

All the tools you need to get you started with Silverlight ( and to follow this example) can be found here. Make sure you download and install everything. You will need Visual Studio 2010 or Visual Web Developer Express edition with Microsoft Silverlight 4 Tools for Visual Studio 2010.

I have Visual Studio 2010 Ultimate edition installed in my machine and that is I am going to use.

1) Launch Visual Studio and create a new project a Silverlight application.Give it an appropriate name.I have named it SilverlightWebService. Make sure you click the option where you host the Silverlight application in a new web site.The Silverlight version should be 4.I will use C# as the development language.

2) Add a new web service to the asp.net hosting project (SilverlightWebService.Web). I have named it CategoryProducts.asmx. If you notice in the .asmx.cs  file that inherits from the WebService class there are web methods that can be executed over the web.

3) Obviously we need to add a data source, a database. I will use the Northwind database.If you need the installation scripts for the sample Northwind database, click here

4) We will need an ADO.Net Entity Data model to our project. In order to see how I am going to accomplish that, have a look in this post (this is my other blog).You can follow steps 5-9. The only difference is that you should pick Northwind database instead of AdventureWorksLT.In the model we only need the Categories,Suppliers,Products tables.My model in the Entity Designer looks something like this

5) So let’s write a method in our service class that gets the Products By Category.

[WebMethod]
public List<Product> GetProductsByCategory(string categoryname)
{
var ctx = new NorthwindEntities();

var query = from product in ctx.Products
where product.Category.CategoryName == categoryname
select product;
return query.ToList();

}

This is a very easy to follow code.I am creating a method that returns a List of Product entities that takes as an input parameter the category that the product belongs.I am just building a simple Linq to Entities query.

Make sure you test the web service and that it functions correctly.

6) Now we need to add a reference from our silverlight application to the web service.Select the Silverlight project and right click on it. Choose Add Service Reference.Click Discover to find available services. You will find the available service and then select it.You will see all the methods available in it.I choose to have a new namespace “MyServices”.Finally click OK. This whole process generates the necessary proxy classes that are necessary to talk to the web service.

In my case it looks like the picture below.

Have a look at the files being generated.You can have a look at the Reference.cs file.You should see that some classes are generated and the interfaces they support.

7) Now we have to design our user interface. We have to open the MainPage.xaml file and type the following.

<Grid
Background="Cyan">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="3*" />
</Grid.ColumnDefinitions>
<ListBox x:Name="ProductList"
Margin="12 12 12 12 "
DisplayMemberPath="ProductName" />
<Border BorderBrush="#D92B2B"
Background="Gray"
BorderThickness="3"
Padding="10"
Margin="10 10"
Grid.Column="1">

<StackPanel DataContext="{Binding SelectedItem, ElementName=ProductList}" Background="#FF47CE52">
<TextBlock>Product Name</TextBlock>
<TextBox Text="{Binding ProductName, Mode=TwoWay,
NotifyOnValidationError=True,
ValidatesOnExceptions=True}" />
<TextBlock>Unit Price</TextBlock>
<TextBox Text="{Binding UnitPrice, Mode=TwoWay,
NotifyOnValidationError=True,
ValidatesOnExceptions=True}" />
<TextBlock>Discontinued</TextBlock>
<TextBox Text="{Binding Discontinued, Mode=TwoWay,
NotifyOnValidationError=True,
ValidatesOnExceptions=True}" />

</StackPanel>
</Border>
</Grid>

I have a ListBox control and displays the names of the Products.In a seperate StackPanel element I have 3 textblock and 3 textbox elements.Inside the textbox elements I am going to bind data.More specifically I am interested in the ProductName,UnitPrice,Discontinued properties/fields.

I am not going to go into details as far as Data binding is concerned. We have the FrameworkElement (StackPanel) that we want to link it to the datasource.The DataContext property sets the data context for that element.

If you want to learn more  about the issue click here .

8) Now we need to write the code in the MainPage.xaml.cs file.We have to populate the ProductList element with data.We are going to write some code in the MainPage_Loaded event handling routine.


public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();

Loaded +=new RoutedEventHandler(MainPage_Loaded);
}

void MainPage_Loaded(object sender , RoutedEventArgs e)
{

var clnt = new GategoryProductsSoapClient();

clnt.GetProductsByCategoryCompleted += (t, r) =>
{

if (!r.Cancelled && r.Error == null)
{

var result = r.Result;
ProductList.ItemsSource = result;

}

else
{
MessageBox.Show("There is no data");
}
};

clnt.GetProductsByCategoryAsync("Refreshments");

}

}

We instaniate the web service proxy before we can use the service ( var clnt = new GategoryProductsSoapClient(); ).

The web service calls in Silverlight are asynchronous.We have two members for the GetProductsByCategory operation. We have the asynchronous method and the completed event.I am handling the completed event first. I am going to use a lambda expression. First I check that the operation has not been cancelled.Then I bind the results to the ProductList element.

Finally I hard code the category,  I execute the call  in which the products I am interested to bring into the silverlight client  belong ( clnt.GetProductsByCategoryAsync(“Refreshments”); ).

Build and Run your application and see all the products appearing in the silverlight client from the web service.

That is all folks. Stay tuned because I am going to post more examples on Silverlight 4.

Email me if you need the source code.

Hope it helps!!!

Comments»

1. Dot Net Rules : Using ASP.Net web services in Silverlight 4 applications - November 20, 2011

[…] .asmx web services, I would use WCF. But as I said before we have to use and maintain legacy code. (read more) Share Posted: Κυριακή, 20 Νοεμβρίου 2011 6:56 μμ από το μέλος […]

2. Using WCF Services in Silverlight 4.0 applications « DOT NET RULES - November 21, 2011

[…] WCF services from a Silverlight 4 application.I strongly suggest that you have a look in this post of mine where I talk about using web services – .asmx services and how we consme them in our […]

3. hire dot Net Developer - November 21, 2011

Thanks for information regarding Using ASP.Net web services in Silverlight 4 applications


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: