Recommended


Silverlight Hosting

Skip Navigation LinksHome / Articles / View Article

Consuming ASMX Web Services with Silverlight 2

+ Add to SilverlightShow Favorites
25 comments   /   posted by Martin Mihaylov on Jul 02, 2008
(11 votes)

Recently I needed to use a web service in order to get some data for my Silverlight application and I found that using an ASMX web service with Silverlight 2 could be quite easy. Though, for people who have never used such service it could be not that easy. So I decided to make this “step-by-step” tutorial and I hope it could be useful to someone.

First let’s create our web service. Create a new project and add an ASMX web service to it. In my example I’ll use the service to get the current date and time, so I name it DateTimeWebService.

 

You have probably noticed the clientaccesspolicy.xml file. Basically if there isn’t such file, the Silverlight plug-in can’t access the service. You can find more about this file and the crossdomain.xml file in the FAQ section of this article. Here is how it should look in order to allow any domain to access your web service:

   1: <?xml version="1.0" encoding="utf-8"?>
   2: <access-policy>
   3:     <cross-domain-access>
   4:         <policy>
   5:             <allow-from http-request-headers="*">
   6:                 <domain uri="*"/>
   7:             </allow-from>
   8:             <grant-to>
   9:                 <resource path="/" include-subpaths="true"/>
  10:             </grant-to>
  11:         </policy>
  12:     </cross-domain-access>
  13: </access-policy>

And here are the methods that I define in the asmx.cs file:

   1: [WebMethod]
   2: public string GetDate()
   3: {
   4: 	   return DateTime.Today.ToString( "MMM dd, yyyy" );
   5: }
   6: 
   7: [WebMethod]
   8: public string GetTime()
   9: {
  10: 	   return DateTime.Now.ToString( "hh:mm:ss" );
  11: }


Now our web service is ready, so let’s create a Silverlight application, which will consume it. Add a Silverlight project to the solution.

 

In the XAML we have two TextBlocks and one Button control:

   1: <StackPanel x:Name="LayoutRoot" Background="White">
   2:         <TextBlock Width="200" Height="30"></TextBlock>
   3:         <TextBlock Width="200" Height="30"></TextBlock>
   4:   <Button x:Name="btnUpdateDate" Content="Update Date" Width="100"
   5:              Height="30"></Button>
   6: </StackPanel>

We’ll use the TextBlocks to present the date and the time and in the click event of the button we’ll consume the service. But before writing the event we must add a service reference of our service to the Silverlight project:

 

The next step:

 

Here you can see the “Go” and the “Discover” buttons. By clicking on the “Discover” button Visual Studio automatically detects the web services that are placed in the current solution. If you want to consume a web service that is placed on a web server just write its address in the address bar.

By clicking “OK” we have a reference to our service added in the Silverlight project. Visual Studio generates all the WSDL (see the FAQ section at the end of the article) you'll need to call the service in several files.

 

Now let’s create an event handler for the button click event:

   1: private void btnUpdateDate_Click( object sender, RoutedEventArgs e )
   2: {
   3:     DateTimeWebService.DateTimeWebServiceSoapClient service =
   4:       new DateTimeWebService.DateTimeWebServiceSoapClient();
   5:     service.GetDateCompleted +=
   6:       new EventHandler<DateTimeWebService.GetDateCompletedEventArgs>(service_GetDateCompleted);
   7:     service.GetTimeCompleted +=
   8:       new EventHandler<DateTimeWebService.GetTimeCompletedEventArgs>(service_GetTimeCompleted);
   9: 
  10:     service.GetTimeAsync();
  11:     service.GetDateAsync();
  12: }

In the service reference there is a SoapClient generated for our DateTimeWebService. Now it is turn to create event handlers for the Completed events of the methods we use. Subsequently, thanks to the event arguments (also generated in the service reference) we can work with the result from our methods, if they return any.

   1: public void service_GetTimeCompleted( object sender,
   2:                 DateTimeWebService.GetTimeCompletedEventArgs e )
   3: {
   4:     Time.Text = string.Format( "The time is {0}", e.Result );
   5: }
   6: 
   7: private void service_GetDateCompleted( object sender,
   8:                 DateTimeWebService.GetDateCompletedEventArgs e )
   9: {
  10:     Date.Text = string.Format( "Today is {0}.", e.Result );
  11: }

Silverlight works on the client side, so obviously we cannot call the methods synchronous. The Soap client calls our methods asynchronously. And that’s the other reason why we need event handlers for the Completed events.

You see that there is nothing complicated to consume an ASMX service using Silverlight. Here is a live demo of the example with the date. If you are interested you can also find the source code here.

 

Another example for a Silverlight application consuming an ASMX web service is Silvester ( a Silverlight Twitter widget ), created by Emil Stoychev. You can read the article and take a look at the awesome live demo here.

FAQ

What is a web service?

By the definition of W3C a web service is “a software system designed to support interoperable Machine to Machine interaction over a network”.

What is the client access policy file?

This is a Silverlight Policy file – clientaccesspolicy.xml. Before connecting to a network resource, the Silverlight runtime will try to download this file. It can be used by the sockets class as well.

What is the cross domain file?

This is the Flash policy file – crossdomain.xml. It can be used by the Silverlight runtime like the client access policy file, but it cannot be used along with a sockets class.

Which file is used by the Silverlight runtime?

First the Silverlight runtime tries to download the Silverlight policy file (clientaccesspolicy.xml). If it’s missing, the runtime tries to download the Flash policy file (crossdomain.xml). If none of the files is found, the runtime cannot establish a connection with the network resource.

What is WSDL?

The Web Services Description Language is an XML-based language, which is used for describing web services.

I get error (404) – Not Found, when trying to consume my web service. Why?

When there is a problem with the service, the response will always be 404. So check carefully the code, make sure that the reference, you’ve added, matches the service you want to use and last but not least, don’t forget the clientaccesspolicy.xml and the crossdomain.xml files.

References

http://en.wikipedia.org/wiki/Web_service

http://en.wikipedia.org/wiki/Web_Services_Description_Language

http://msdn.microsoft.com/en-us/library/bb552919.aspx - ASP.NET XML Web Service Basics

http://msdn.microsoft.com/en-us/library/cc645032(VS.95).aspx - Network Security Access Restrictions in Silverlight 2

http://quickstarts.asp.net/QuickStartv20/webservices/default.aspx - ASP.NET Web Services QuickStart Tutorial

http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2008/06/30/10548.aspx - Silverlight 2 and ADO.NET Data Services

Share


Comments

Comments RSS RSS
  • RE: Consuming ASMX Web Services with Silverlight 2  

    posted by redzer0 on Aug 20, 2008 05:06

    Hi, Ive tried your code but im getting this error in this line:

    Dim service As New ServiceReference1.Service1SoapClient()

     

    Could not find default endpoint element that references contract 'SilverlightApplication2.ServiceReference1.Service1Soap' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.

    What else im a missing here?

  • RE: Consuming ASMX Web Services with Silverlight 2  

    posted by Enrai on Aug 20, 2008 08:45

    When adding a Service reference the studio also automatically creates a ServiceReferences.ClientConfig file, where the end points and the bindings are defined.

    See if if you have this file in the project where you have added your service reference, if not, delete the reference and add it again it should be created automatically. If the file is available but there are no settings for the particular service in it, try to update the service or delete the reference and the file and than to add the reference again.

     

     

    The code in the client config file should look like that:

     

    <configuration>
        <system.serviceModel>
            <bindings>
                <basicHttpBinding>
                    <binding name="DateTimeWebServiceSoap" maxBufferSize="65536"
                        maxReceivedMessageSize="65536">
                        <security mode="None" />
                    </binding>
                </basicHttpBinding>
            </bindings>
            <client>
                <endpoint address="http://localhost:54602/DateTimeWebService.asmx"
                    binding="basicHttpBinding" bindingConfiguration="DateTimeWebServiceSoap"
                    contract="DateTimeServiceSample.DateTimeWebService.DateTimeWebServiceSoap"
                    name="DateTimeWebServiceSoap" />
            </client>
        </system.serviceModel>
    </configuration>

     

    The end point is defined in the client element. I've tried to run the application without the information for the end point and it threw the same exception. So I think that the problem is in this file.

  • RE: Consuming ASMX Web Services with Silverlight 2  

    posted by Angelina on Aug 26, 2008 07:31

    I am getting this error:

    Error 3 The type or namespace name 'schema' could not be found (are you missing a using directive or an assembly reference?) D:\SilverLight Practice Using VS\TestWCF\TestWS\Service References\ServiceReference2\Reference.cs 41 17 TestWS
     

  • RE: Consuming ASMX Web Services with Silverlight 2  

    posted by Angelina on Aug 26, 2008 07:32

    What should i do for the above error?

  • RE: Consuming ASMX Web Services with Silverlight 2  

    posted by emil on Aug 26, 2008 22:24

    Hi Angelina,

    Could you paste the source code the gives you this error so I can help you?

  • RE: Consuming ASMX Web Services with Silverlight 2  

    posted by Angelina on Aug 26, 2008 22:51

    Hi Martin!

    I am  consuming simple web service of ASP.Net which has System.Web.Services.Protocols namespace. Whereas silvelright  supports System.ServiceModel and hence tell me whether i can do this kind of consumption. Source code that gives me that error is as follows:

    public partial class FetchResponseFetchResult : object, System.ComponentModel.INotifyPropertyChanged {private schema schemaField;private System.Xml.Linq.XElement anyField;/// <remarks/>XmlElementAttribute(Namespace="http://www.w3.org/2001/XMLSchema", Order=0)]public schema schemaget {return this.schemaField;set {this.schemaField = value;this.RaisePropertyChanged("schema");

     

     

     

     

     

     

     

     

     

    [System.Xml.Serialization.

     

    {

     

     

    }

     

     

     

    }

    }

     

  • RE: Consuming ASMX Web Services with Silverlight 2  

    posted by Angelina on Aug 26, 2008 23:32

    Hi Emil!

    I am  consuming simple web service of ASP.Net which has System.Web.Services.Protocols namespace. Whereas silvelright  supports System.ServiceModel and hence tell me whether i can do this kind of consumption. Source code that gives me that error is as follows:

    public partial class FetchResponseFetchResult : object, System.ComponentModel.INotifyPropertyChanged {private schema schemaField;private System.Xml.Linq.XElement anyField;/// <remarks/>XmlElementAttribute(Namespace="http://www.w3.org/2001/XMLSchema", Order=0)]public schema schemaget {return this.schemaField;set {this.schemaField = value;this.RaisePropertyChanged("schema"); }}

     

  • RE: Consuming ASMX Web Services with Silverlight 2  

    posted by Angelina on Aug 27, 2008 03:11

    Is it possible to consume WSE 3.0 enabled webservice from Silverlight Application? If so, how?

  • RE: Consuming ASMX Web Services with Silverlight 2  

    posted by Angelina on Sep 19, 2008 05:10

    I want to know more about the security in silverlight Application as i have come across something called silverlight spy which can get all the details from the xap file of any silverlight application. Do share your thoughts on this.

  • RE: Consuming ASMX Web Services with Silverlight 2  

    posted by Enrai on Sep 19, 2008 08:26

    I don't think that this article can be connected with the security in SIlverlight, so it's not very proper to post it as a comment here, but expect an article soon that will be focused on that. ;)

    And about your question about the WSE 3.0 web services and Silverlight, which I have missed, I'll try to figure out how it's done when I have some time and will gladly share it with you ;)

  • RE: Consuming ASMX Web Services with Silverlight 2  

    posted by Angelina on Oct 06, 2008 04:58

    Thank you for your reply. Now i am able to get in connect with WSE enabled WS through WCF by taking  the proxy of the WS in the Silverlight host.

  • RE: Consuming ASMX Web Services with Silverlight 2  

    posted by Fiannolo on Oct 06, 2008 09:02

    Hi, first really thanks for your great work. I'm trying to  modify your code and i have a big exception and i dont have idea. Can you help me?

     

    this is the exception:

     [Xml_CannotFindFileInXapPackage]

    Argumentos:ServiceReferences.ClientConfig

    Las cadenas de recursos de depuración no están disponibles. La clave y los argumentos suelen proporcionar suficiente información para diagnosticar el problema. Vea http://go.microsoft.com/fwlink/?linkid=106663&Version=2.0.30523.8&File=System.Xml.dll&Key=Xml_CannotFindFileInXapPackage.

     

    I create a new silverlight class library and try to implement MVP pattern.  calling the presenter method in the onclick button event and cut the code of the call to the web service and paste it in the presenter method.

    This error throw the exception when the system call de constructor of the web service proxy class.

     

    Sorry for my poor english. i'm trying to speak english to write it. and thanks for your work again. From venezuela.  

  • RE: Consuming ASMX Web Services with Silverlight 2  

    posted by Enrai on Oct 07, 2008 07:01

    Looking at the error message I think that the problem might be in the ServiceReferences.ClientConfig file. Check if it's not missing in the project where you reference your services.