(X) Hide this
    • Login
    • Join
      • Generate New Image
        By clicking 'Register' you accept the terms of use .

Consuming ASMX Web Services with Silverlight

(17 votes)
Martin Mihaylov
>
Martin Mihaylov
Joined Oct 29, 2007
Articles:   50
Comments:   71
More Articles
33 comments   /   posted on Jul 02, 2008
Tags:   asmx , martin-mihaylov
Categories:   Data Access , Line-of-Business

This article is compatible with the latest version of Silverlight.


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 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:

 <?xml version="1.0" encoding="utf-8"?>
 <access-policy>
     <cross-domain-access>
         <policy>
             <allow-from http-request-headers="*">
                 <domain uri="*"/>
             </allow-from>
             <grant-to>
                 <resource path="/" include-subpaths="true"/>
              </grant-to>
          </policy>
      </cross-domain-access>
  </access-policy>

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

 [WebMethod]
 public string GetDate()
 {
 	 return DateTime.Today.ToString( "MMM dd, yyyy" );
 }
 
 [WebMethod]
 public string GetTime()
 {
  	   return DateTime.Now.ToString( "hh:mm:ss" );
  }

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:

 <StackPanel x:Name="LayoutRoot" Background="White">
      <TextBlock Width="200" Height="30"></TextBlock>
      <TextBlock Width="200" Height="30"></TextBlock>
    <Button x:Name="btnUpdateDate" Content="Update Date" Width="100"
              Height="30"></Button>
 </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:

 private void btnUpdateDate_Click( object sender, RoutedEventArgs e )
 {
     DateTimeWebService.DateTimeWebServiceSoapClient service =
       new DateTimeWebService.DateTimeWebServiceSoapClient();
     service.GetDateCompleted +=
       new EventHandler<DateTimeWebService.GetDateCompletedEventArgs>(service_GetDateCompleted);
     service.GetTimeCompleted +=
       new EventHandler<DateTimeWebService.GetTimeCompletedEventArgs>(service_GetTimeCompleted);
 
      service.GetTimeAsync();
      service.GetDateAsync();
  }

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.

 public void service_GetTimeCompleted( object sender,
                 DateTimeWebService.GetTimeCompletedEventArgs e )
 {
     Time.Text = string.Format( "The time is {0}", e.Result );
 }
 
 private void service_GetDateCompleted( object sender,
                 DateTimeWebService.GetDateCompletedEventArgs e )
 {
      Date.Text = string.Format( "Today is {0}.", e.Result );
  }

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


Subscribe

Comments

  • -_-

    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?

  • Enrai

    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?

  • emil

    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 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.

  • Enrai

    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.  

  • Enrai

    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.

  • -_-

    RE: Consuming ASMX Web Services with Silverlight 2


    posted by Dee on Oct 14, 2008 11:06

    I am getting the same problem mentioned by Angelina.
    Added Service Reference to an existing Web Service and tried to compile. Thats all - nothing else. And I get this error:
    "The type or namespace name 'schema' could not be found (are you missing a using directive or an assembly reference?) ".
    Should any special settings be applied ?
    It seems like Angelina solved the problem "by taking  the proxy of the WS in the Silverlight host." in the post above. What does that mean ??

  • -_-

    RE: Consuming ASMX Web Services with Silverlight 2


    posted by Dee on Oct 14, 2008 12:45

    Found the reason - Silverlight does not support Dataset class - Does not allow one to add System.Data as a reference. Once I commented out the web methods that used the Dataset class, the compile worked.

  • -_-

    RE: Consuming ASMX Web Services with Silverlight 2


    posted by Angelina on Oct 14, 2008 21:38

    Hi Dee!

                You are exactly correct w.r.t. that error.  What i mentioned was related to WSE Web Service consumption by Silverlight Application.

  • -_-

    RE: Consuming ASMX Web Services with Silverlight 2


    posted by Lazaro on Nov 18, 2008 14:39

    Hello...great article...but I have some problems with security....

    An error occurred while trying to make a request to URI 'http://localhost:54602/DateTimeWebService.asmx'. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. Please see the inner exception for more details.

    I download your code and open it in Visual Studio and build....nothing more....do you iluminate me...

     

    Thanks

  • Enrai

    RE: Consuming ASMX Web Services with Silverlight 2


    posted by Enrai on Nov 19, 2008 10:18

    I have downloaded the code, build it and run it without problems. Make sure that you set one of the test pages in the WebSite project as start page. If you use the automatically generated TestPage in the Bin/Debug directory it would throw this exception, the automatically generated pages just don't work with services and not only with them and the reason is that they are opened not as http://, but as file:///. Also I tried to run it without starting the ASP.NET Development Server (Port 54602) - the service is hosted there, and it raised the exception that you have encountered. So look if both development servers (port 54602 for the service and port 55461 for the web site) are running and if not, maybe this is the key to your problem. ;)

  • -_-

    RE: Consuming ASMX Web Services with Silverlight 2


    posted by Frazer on Dec 15, 2008 05:47

    Great article - thanks.  I would like to call asmx web services which require basic authentication (username/password) - however I am not sure how to set the credentials when calling the web services from the WCF client in Silverlight.  Can you povide and guidance?

  • -_-

    RE: Consuming ASMX Web Services with Silverlight 2


    posted by steve on Dec 31, 2008 06:30

    Hi i'm really confused on silverlight 2 and the webservice endpoint address.

    When you add a reference in a silverlight project in visual studio to a webservice it uses the localhost address

    eg.  http://localhost/Application.Web/Webservice.svc

    Now because the silverlight app is running on the client this means the client will try to access the service on their machine (not the server address). If i change this to a dns address then the service asks for the username and password. I cant seem to get around this. Can anyone help please? Thanks Steve

  • -_-

    RE: Consuming ASMX Web Services with Silverlight 2


    posted by Neal on Jan 18, 2009 14:18

    Your step by step is incomplete and makes a lot of assumptions. Please do a better job  next time. From my experience and other comments here, you have left out a lot of details .-(

  • -_-

    RE: Consuming ASMX Web Services with Silverlight 2


    posted by GaryB on Mar 02, 2009 12:26

    Every article I see (starting with WCF and now this Silverlight/ASMX) uses localhost for the service domain.  That is just not complete or real-world. Could someone post a sample of working code that uses two domains, one for the service and one for the client?  Isn't that how services are supposed to work?

    Nevertheless I am getting the same message Lazaro pasted above even on localhost.  After figuring the client web config and the clientaccesspolicy I am stuck with that message.

    Is this thread still active??

  • -_-

    RE: Consuming ASMX Web Services with Silverlight 2


    posted by K on Apr 12, 2009 18:25

    Good example, thanks. I only needed a hint to put 2 and 2 together.

    Lazaro and GaryB

    I also had a same problem and solved it by telling VS to use Local IIS Web Server instead of built in Cassini. It looks to me ports needs to be defined in the policy files. My files are as follows:

    clientaccesspolicy.xml
    <?xml version="1.0" encoding="utf-8" ?>
    <access-policy>
      <cross-domain-access>
        <policy>
          <allow-from http-request-headers="SOAPAction">
            <domain uri="http://*/>
            <domain uri="https://*" />
          </allow-from>
          <grant-to>
            <resource include-subpaths="true" path="/"/>
          </grant-to>
        </policy>
      </cross-domain-access>
    </access-policy>
    crossdomain.xml
    <?xml version="1.0"?>
    <!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
    <cross-domain-policy>
      <allow-http-request-headers-from domain="*" headers="*"/>
    </cross-domain-policy>

    PS. I am using Win7 with IIS7.5 (default with Win7).

    Hope it helps.

    K

     

  • -_-

    RE: Consuming ASMX Web Services with Silverlight 2


    posted by Art on May 05, 2009 11:28
    Thank you for this interesting article.  I have what is probably more of a Visual Studio question than a Silverlight question, so I hope it is appropriate here.  In the screen grab after you added the service reference, we see all the leaf nodes of the DateTimeWebService in the Solution Explorer tree.  I only see the parent node in my view.

     How is it possible to enable viewing of the leaf nodes in Visual Studio?  I explored for this feature but could not find it.  Thanks in advance!

    Art

     


  • -_-

    RE: Consuming ASMX Web Services with Silverlight 2


    posted by Peter on Aug 02, 2009 13:37

    Martin, thank you for this quick start. This thread is very informative, especially K's contribution.

    Peter

  • -_-

    RE: Consuming ASMX Web Services with Silverlight 2


    posted by vinod on Sep 11, 2009 12:31
    clientaccesspolicy.xml is needed only if ur web service is gonna be accessed by some other domains right.....or do we need it everytime??
  • -_-

    RE: Consuming ASMX Web Services with Silverlight 2


    posted by Angel on Oct 27, 2009 18:38

    Hi, I have a aplication runing with VS 2008, and silverligth and i want to use a web service, but when i put the direction like ip address the aplication try to use the name of the server, did you know how i can force to use the ip and not the name of the server?

    Thanks

     

     

     

  • -_-

    RE: Consuming ASMX Web Services with Silverlight 2


    posted by Narglix on Mar 24, 2010 15:50
    Hi,

    I just have this question :

    Is it possible to obtain the SOAP result in the XML format ?


    Thx for your future answer.

    Narglix
  • -_-

    RE: Consuming ASMX Web Services with Silverlight 2


    posted by Samba on Apr 14, 2010 13:36
    I would like to know whether is there any property called IsCompleted property for the web service method.I want to show progress bar till the web method execution is completed?
  • -_-

    RE: Consuming ASMX Web Services with Silverlight 2


    posted by LoveNuqui on Aug 04, 2010 05:20
    Is this thread still active?
  • lnikolov

    RE: Consuming ASMX Web Services with Silverlight


    posted by lnikolov on Jan 11, 2011 12:05
    The article has been updated to the latest version of Silverlight and Visual Studio.
  • -_-

    RE: Consuming ASMX Web Services with Silverlight


    posted by Sharepoint Coder on Feb 17, 2011 12:17

    Where Should I put that ClientAccessPolicy and crossdomain files.

    I got an error massage related to crossdomain policy file.

    Please help me ASAP.As I am Stuck on this from last few hours

  • -_-

    RE: Consuming ASMX Web Services with Silverlight


    posted by Raghu Marwah on May 08, 2011 21:37

    It works....

    Good Work...

  • MarcoBet

    Re: Consuming ASMX Web Services with Silverlight


    posted by MarcoBet on Apr 02, 2015 04:13

    That is very interesting Smile I love reading and I Cipto Junaedy always searching for informative information like this Jadwal MotoGP 2015. This is exactly what I was looking for Cara Upload Video ke Youtube.  Really this system so amazing. Cipto Junaedy  so happy to browsing this BBM Untuk Android Versi Terbaru. Simply fill out a quick and easy application, and you'll be on your way to getting your new Cara Membuat Email  and Cara Instal Windows 7 avoiding Thanks for sharing this great article . Don't forget for reading the articles about Jinpoker.com Agen Judi Poker Online dan Domino Online Indonesia Terpercaya. And I encourage you to bookmark the following page if Cahayapoker.com Agen Judi Poker Dan Domino Uang Asli Online Terpercaya Indonesia considered important ... Regards ituDewa.net Agen Judi Poker Domino QQ Ceme Online Indonesia

    | Nusantarapoker.com Agen Texas Poker Dan Domino Online Tanpa Robot Terpercaya

Add Comment

Login to comment:
  *      *