Integrating Web Services and Silverlight with .Net 1.1 Alpha

The Short Story:

So, I’m working on a Silverlight .net project where the main source of data is a webservice.  It’s not a huge amount of data, but it is not small either. In general it’s about 20K to 50K per download.  My original plan was to use the quickstart method (POX) and basically parse the xml using the XMLReader classes that are available on Silverlight.  That didn’t work so well for
me, so I switched to the proxy classes and did not have much more luck. The primary problem is I could not figure out how to debug the code on the Silverlight side.  Ultimately, I ended up figuring out how to do debugging and in the next few paragraphs I’ll go through the steps including screen shots showing how to do it.


The Details

The Solution

So, let’s start from the beginning.  First thing to do is create an empty solution.  In my case, I’m going to call that solution SearchLightMain.  I’m going to use Orcas rather than vs2005 because that is required for Silverlight. Ultimately, the web services project will deploy on .net 2.0 but the development envirnoment is still Orcas.  (File/New Project/Other Project Types/Empty Solution)

The Silverlight Side

Next, right mouse on the solution explorer and choose Add/New Project/C#/Silverlight.  Leave your solutions directory in the Location textbox and put the name of your silverlight project in the name field.  In my case, the name will be SearchLight.

 

After the project is created, my preference is to add a textblock to the page.xaml file and some color to the background so when I run it I can tell it is actually working.  Here is what it looks like now  after I’ve done that if right mouse and run TestPage.html.  This is what you get.

And the Xaml looksl like this:

Now you have the silverlight project done.  Let’s create the Web Service Project now inside of the same solution we made first.

The Web Service

On the solution explorer, right click on the top of the tree (solution) and say "Add/New Website".  Choose ASP.NET web site.  (remember, this is Orcas we are still in).  Make it a "File System", "C#" project. and for the location put the directory where you have your empty solution followed by the name WebService.  In my case, the name is: C:UserspkellnerDocumentsVisual Studio Codename OrcasProjectsSearchLightMainWebService  Also, change the framework to .NET Framework 2.0 in the upper right hand corner of the screen "Add New Website".

Now, your solution explorer should look like this:

And, the layout on your hard disk will look like this:

Now, we need to make the web service.  The easiest thing to do is grab the code from the quickstart and paste it into a webservice if you don’t have your own.  The URL where you can grab the code is: 

http://www.silverlight.net/QuickStarts/Remote/UsingJSON.aspx

One thing I found was that if you downgrade to .net 2.0 from .net 3.5 as we did earlier, the webservices that use the tag [System.Web.Script.Services.ScriptService] do not work. My solution was to create an Ajax enabled web site with vs2005 and copy that web.config into this project.

Continuing on, the next thing I did was to copy the files TestPage.html, TestPage.html.js and Silverlight.js from the SearchLight project into the WebService project.  This is because we will actually be running the project from the webservices project.

Finally, to complete the linking, right click on the webservice project and select "Add Silverlight Link…" (not sure what the … means).  Here is what it looks like.

 

Now, do a Build/Rebuild all and the xaml files from your silverlight project as well as the ClientBin directory will be imported (copied) into your web services project.  Here is what we have now.

Now, verify that your web service actually works by right mousing on the asmx file and pressing browse.  If it’s working, you should be able to run it and get a screen something like this.

The next step is not what you are expecting.  The quickstart says go ahead and create a web reference and run that.  That’s great as long as you don’t want to run this project on a real server (port 80).  Best I can tell, it hardwires the port to whatever the debugger is set to.  I tried without much luck to change the property in the localhost control created but
without much luck.  I believe a better solution is to run the tool called slwsdl.exe which is part of the orcas distribution.  essentially, you run it with the /SilverlightClient option and point it at your web service. for example, when I ran mine, the command was:

This created a file called WebService.cs which I put in my silverlight project.  It becomes my proxy.  The nice thing is I can modify the line that reaches out to the webservice to be whatever I want.  By default it is the local server with the debug port set, but when I deploy to a real server I can change that address to the real name.  Here is the code you
change:

Finally, now you can debug.

Go to your SearchLight project and add some code to the Page.xaml.cs file.  then, run the project from the webservice/testpage.html and vwala!  You can debug.  Here is proof (really, not bull).

Final thoughts

So, why go through all this trouble?  It think I forgot to mention that it’s to avoid the dreaded Cross-Domain issue.  That is, your Silverlight client can not call a webservice that is not in the same root domain and running on the same port as your silverlight app.  Also, while I was writing this article to help others avoid some of the pain I’ve been through, I put a project
together from scratch.  A couple things I noticed along the way.

  • When you copy xaml files from one project to another, you can no longer run them.  You need to change their property from Silverlight Page to Embedded Property or the page can not be read in it’s codebehind.
  • It’s very important to go to debug/exceptions and turn on all exceptions, otherwise you will not know what is killing your app (see
    previous item).
  • It’s a cold cruel world out there on the bleeding edge.

Good luck with your Silverlight development.  There are lots of opportunities out there.  Indeed, a target rich environment.

About Peter Kellner

Follow me:


Comments

  1. In the past I had some issues with Silverlight service but now this is all solved. Thanks man you are a treasure.

  2. I had this localhost / online sync problem too, so I gave up…

  3. I was having troubles with integrating web services and Silverlight with .Net 1.1 Alpha but after reading your article things are much clearer. Thanks!

  4. I find debugging silverlight painful :(

  5. great tutorial, I love silverlight when someone explains step by step like this ;)

  6. This solution seems to be the most stable and easy to implement. I’ve tested on the local computer and seems to work very fine. The most interesting at this tutorial is that you posted the steps necessary for implementation.

  7. What would most of us do without the wonderful thoughts you discuss on this site? Who else comes with the endurance to deal with critical topics just for common visitors like me? I actually and my buddies are very blessed to have your blog among the kinds we usually visit. It is hoped you know how significantly we appreciate your working hard! Best wishes through us all.

  8. The tree structure is very helpful for a beginner because it offers the image of the entire structure. I suppose the best option is to follow exactly these steps. Is this available for the latest version of SilverLight ?

  9. My last monthly period period began on November. 29 and so lasted 7 days. It is now December nineteenth and I am encountering quite mild, darkish bleeding together with slight cramping. I have been trying to get pregnant for some months now. Might this be implantation bleeding? If it is, in how much time can one take a test for pregnancy?

  10. You really covered this topic well. where could i follow your blog RSS feed?

  11. Mutyalanna Roddam says:

    HI,

    Currently we are working for XYZ project and have many components wich are TIM,TAM,TDI,WAS,SQL amd
    Issue:EndUsers are not getting the Usermails after clicking on the continue button in my application.

    Actually we have two Webservice in which one webservice is down then
    one was working fine henceforth some of the users are not getting the mails.

    I have verify the logs which saying that below:

    Error : A remote host refused an attempted connect operation.

    We are receiving the same error when called from the SoapUI:

    100
    java.lang.Exception: Error: A remote host refused an attempted connect operation. Error

    Can you please help us in resolving these.

  12. I think you post some prime points in this post :p

  13. Hey there,
    I cant find any Menu called add silverlight application Link.
    Mine is vs 2008, with vista os .
    Wuld that be a problem for that.
    All thet i need is to access the webservices method from page.xaml.
    But am getting cross domain error if i try to use async method
    Plz help
    Thanks in advance
    Regards
    N.Balaji

  14. Peter Kellner says:

    Tim Heuer has a great article on doing webservices that is much newer than mine here. Give it a read! Tim’s a great resource and is now on the silverlight team.

    http://timheuer.com/blog/archive/2008/04/09/silverlight-cannot-access-web-service.aspx

  15. Hi Peter,

    I have a silverlight application that communicates to Webservices

    It is running fine at my localhost but when i deploy it to my hosting server i get cross domain error

    I am not using AspXaml control due to “Click to activate this Control” but using .html file to createsilverlight .html file and .asmx files are in the same directory so why i am getting this error?

    may be the hosting server is running .asmx files at some other port than 80?

    but i tried http:// …. /mywebservice.asmx (without specifying any port) i ran and shows the wsdl


    Please help

  16. Hi,
    Maybe you can assist:
    I’m having IIS website project with webservice and silverlight project.
    The web service is using httpwebrequest\reponse and not JSON.

    When running from the same machine where the development is (and the IIS), it runs ok.
    When running from other machine the response fails to parse the XML returned, although it is the same action.
    Can you explain?
    Is there a way to debug the client machine process?
    Thanks,

  17. Hi There.

    I tried following this guide, but ran into the following error:

    System.InvalidOperationException: Operation is not valid due to the current state of the object.

    I noticed on http://silverlight.net/forums/t/732.aspx that you experienced the same problem. So I was hoping you know exactly what I’m doing wrong. Any help would be greatly appriciated.

  18. *Sigh*

    I wish you had posted the code.

    Either I can run the project, and debug, but the WS doesn’t work. Or, I can browse to the testpage.html and the WS works, but I can’t debug.

  19. Good Article.
    What wort of Web Service did you call against ? – Was it ASMX based or JSON or POX ?
    Because I am still having a problem using this process against an ASMX based .NET web service, linked into Silverlight Project. I get an JSON_IllegalPrimative ? exception in my Silverlight call, which is rather strange.
    Using VS2008 RTM, Silverlight 1.1 Alpha on Windows XP.
    Cheers Anyway

  20. Michael Kariv says:

    Great article. All works as advertised.
    My tip to the readers is that if you change your web service interface you have to re-generate WebService.cs.

    Then all nice commented out alternatives to URL will be lost. Copying them every time is tedious.
    I find mysleft switching between production (discountasp.net has 3.5 beta hosting) and debug environments.

    My solution is to derive from WebService and keep all those comments in constructor of the subclass.

    Another tip – have a batch file (or WSH script) to regenerate the file. I have. It generates and copies the file to the right place.

    If anyone is interested i can post it.

  21. sir i need to develop an application which gets the table from sql server and display in silverlight in form of chart.plz send me code for that if possible else required steps..
    thnx

  22. Hi Peter,

    There is another problem. When I try more complex thing as get objects from the WS I can’t enter the method I called in debug mode and I don’t get this object. Is it because Silverlight 1.1 alfa doesn’t include XML.Serialization, so we can’t use soap?

    PS: Can you send me a mail ?

    Regards.

  23. Hi Peter.

    I followed your example and no problem it works.You launch your project via your WS. In fact, when I start with my Silverlight project it doesn’t work anymore (“Hello Wolrd” is not printed). Do you have a solution ?

    Regards.

  24. I have followed your instructions, minus generating the web.config from vs 2005 /w ajax. Instead, I have installed the ajax from http://asp.net/ajax/ on a fresh machine that has only the requirements specified on silverlight getting started.

    I have added this to the web.config, to allow for [System.Web.Script.Services.ScriptService] attribute above the webservice class.

    (GT)compilation debug=”true”(LT)
    (GT)assemblies(LT)
    (GT)add assembly=”System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35″/(LT)
    (GT)/assemblies(LT)
    (GT)/compilation(LT)

    When I try to execute any web methods from the silverlight’s xaml.cs, using async call, the IAsyncResult results in a ‘iar.AsyncWaitHandle’ threw an exception of type ‘System.NotImplementedException’.

    I am definitely using the WebService proxy code, as the debugger tracks into the WebService.cs in the silverlight project that inherits from System.Windows.Browser.Net.SoapHttpClientProtocol.

    Any ideas would be appreciated.

    Thanks

  25. I have followed your instructions, minus generating the web.config from vs 2005 /w ajax. Instead, I have installed the ajax from http://asp.net/ajax/ on a fresh machine that has only the requirements specified on silverlight getting started.

    I have added this to the web.config, to allow for [System.Web.Script.Services.ScriptService] attribute above the webservice class.

    When I try to execute any web methods from the silverlight’s xaml.cs, using async call, the IAsyncResult results in a ‘iar.AsyncWaitHandle’ threw an exception of type ‘System.NotImplementedException’.

    I am definitely using the WebService proxy code, as the debugger tracks into the WebService.cs in the silverlight project that inherits from System.Windows.Browser.Net.SoapHttpClientProtocol.

    Any ideas would be appreciated.

    Thanks

  26. Administrator says:

    Willeus,
    What I would do if I did not have control of the web service is to make your own web service that essentially relays the information from the one yo want to your local one which you can call.
    -Peter Kellner

  27. This is good if you have control of the webservice. What should we do if the web-service is an external web service that is on a separate domain?

  28. I had this problem when my webservice was in its own project. But when I placed the web service within the Web Site that was hosting the XAML and uncommented the folling line-

    [System.Web.Script.Services.ScriptService]

    Above the WebService class it all

  29. Thank you Peter! You kept my computer from going out the window!!!

    I had downgraded the webservice to .NET 2.0 also. I used your trick of generating an ajax web project in VS 2005 and copying the web.config to my new webservice. Worked like a charm!

    Thanks again!

    Bill

  30. Thank you very much! This tutorial was very, very helpfull!

  31. mike castillo says:

    Hi Peter,
    Thanks to your article, I actually got a web service call from my silverlight application working. I am trying to understand why it works though. In particular, it seems odd that you copy the TestPage.html and silverlight.js and testpage.html.js into the web service project and then run from teh web services project. Can you explain how it can actually run my silverlight application when I run the web services project? Is this so essentially all web requests are on localhost and on teh same port?
    Another question is in a production environment, with my web service running on teh same server as what hosts the silverlight application, would I have to jump through these same hoops or is is just to make it work in the debugging environment?
    Finally, as you mentioend the system.web.script.scriptservice attricute is not valid in a asp.net 2.0 project, but it is in 3.5. Now you did a workaround creating a ajax web project and you copied the web.config form it into the asp.net 2.0 web service project. Do you know why that allowed it to work? Is there an ajax dll specified in the web.config that gets pulled in and thus make that scriptservice attribute valid?

    Thanks for your insight.
    Regards,
    Mike

  32. Great tutorial, thanks! Was pulling my hair out before reading this, now its all working :)

  33. lefnire says:

    per email correspondence we figured out the problem. Didn’t want to leave other readers hanging :)

    [Peter]
    I don’t really have a good example. I didn’t keep what I build clean because I was adding my real stuff to it.

    What kind of errors are you stuck on?

    [Lefnire]
    well i followed your steps and it didn’t really make a difference in the outcome (though it did help me understand the proxy call). Same problem: i can call the webservice created through your proxy getup through any normal .aspx, but i can’t call it through the silverlight project. i zipped up my code, don’t feel obligated to look at it, but just in case you have a spare moment.

    Thanks again, better tutorial than what’s offered on the quickstarts proxy
    (http://tyler.bugsprae.com/game.zip)

    [Peter]
    You need to uncomment the //[System.Web.Script.Services.ScriptService] line in your web service and then it works. You were very close!

    [WebService(Namespace = “http://tempuri.org/”)]

    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

    //[System.Web.Script.Services.ScriptService]

    public class Service : System.Web.Services.WebService

    {

    public Service () {

    //Uncomment the following line if using designed components

    //InitializeComponent();

    }

    [WebMethod]

    public string HelloWorld() {

    return “Hello World”;

    }

    }

    Feel free to post the answer on my blog also for others.

  34. lefnire says:

    still doesn’t work for me. could you zip up a sample solution?

Follow

Get every new post delivered to your Inbox

Join other followers: