• My Silverlight application cannot access my service!


    I’ve started a dialog with a few of you about getting Silverlight and service integration working, specifically with ASP.NET web services (and even WCF ones).  A few have downloaded some of my samples, but others have started from scratch.  A few have reported getting some interesting errors, ASYNC_blahblah and NotFound errors specifically.  While this was boggling my mind (as I wasn’t getting them), a reader’s comments pointed me along the lines of something…he mentioned “maybe it is because my web service is ASP.NET 2.0 and not 3.5” – of which that shouldn’t be the case, so I went to test that.

    The Situation

    Most of the samples you are likely seeing (including mine) are implementing web services within the same project that the Silverlight host is implementing.  What I mean to say is probably you are doing File…New…Silverlight Project and then incorporating the web service into the web site project that comes with that template.  If you do so, you probably aren’t running into problems.  Also note that the target framework of that default web site project is .NET 3.5.  This doesn’t make a difference, but I’m just noting it here.

    But what if you have an existing service, or you have an existing web site project that you are running in Visual Studio and running into problems…and l think I know why…let’s investigate by doing this step-by-step.

    The Web Service

    First open an instance of Visual Studio 2008 and choose to create a new ASP.NET Web Service (I’m calling mine ‘FooService’).  Be sure to select .NET Framework 2.0 for this experiment:

    Do nothing more to the service.  We’re just going to use the HelloWorld stub for this experiment.  We know we’re going to simulate a cross-domain situation so create a clientaccesspolicy.xml file at the root of this project.  You can use my snippet to do the default public policy quickly if you’d like, it’s wickedly cool and awesomely awesome.  I recommend it ;-).  Moving on… We are done here.  CTRL+F5 this bad boy to start it running (or select Service.asmx and view in browser) – we just need to get the service running.  Make note of the URL, it is likely http://localhost:XXXXX/FooService/Service.asmx where “XXXXX” is the random port assigned by VS.  Just note that URL.  Obviously if you didn’t call yours FooService, then it will be different.

    The Silverlight Application

    Start another instance of VS2008 and choose File…New…Project…Silverlight Application.  I’m calling mine FooApp.  Now, if you don’t see any of the Silverlight templates, just change the target framework back to .NET Framework 3.5 if you haven’t done so already.  Accept the default for creating the FooApp_Web project for you, we’ll need a host here anyway under HTTP.

    Modify nothing in the Page.xaml file but add a service reference to the Silverlight application by right-clicking on the app and choosing ‘Add Service Reference.’  Put the URL of the ASP.NET 2.0 service (from previous step) in the box and click GO.  You should get it discovered and have ‘ServiceReference1’ as the name:

    Just keep the lame name because we’re just playing around remember?  Now, go to Page.xaml.cs and add the following code:

    public Page()
    {
        InitializeComponent();
        Loaded += new RoutedEventHandler(Page_Loaded);
    }
    
    void Page_Loaded(object sender, RoutedEventArgs e)
    {
        ServiceReference1.ServiceSoapClient proxy = new FooApp.ServiceReference1.ServiceSoapClient();
        proxy.HelloWorldCompleted += new EventHandler<FooApp.ServiceReference1.HelloWorldCompletedEventArgs>(proxy_HelloWorldCompleted);
        proxy.HelloWorldAsync();
    }
    
    void proxy_HelloWorldCompleted(object sender, FooApp.ServiceReference1.HelloWorldCompletedEventArgs e)
    {
        try
        {
            TextBlock tb = new TextBlock();
            tb.Text = e.Result;
            LayoutRoot.Children.Add(tb);
        }
        catch (Exception ex)
        {
            string wtf = ex.Message;
        }
    }

    What we are doing here is calling the service (asynchronously of course) and wiring up the completion event to emit a new TextBlock with the result of the web service.  The Page() constructor just adds a Loaded event so we aren’t doing anything in the constructor to the XAML before it is done loading.

    Okay, so we are done.  We have our web service with an appropriate clientaccesspolicy.xml file and it is running.  We have our Silverlight application with a service reference to that and proxy code generated.  We are using that proxy code to call the service, and use the result in a new TextBlock in our root layout element.  Sweet.  Put a breakpoint on the exception catch (should be line 37) and hit F5 (choose yes to enable debugging in web.config).

    WTF?

    Did you get ‘Async_ExceptionOccurred’ like I did?  Sonofa…  Maybe it is because I’m accessing an ASP.NET 2.0 service? No.  Maybe it is because my app is on port YYYY and my service is on port XXXX?  Nope.  Ah, cross-domain issues?  Try again.

    Investigating the Problem

    Okay, on to figuring out what is going on. 

    If you are a web developer and you aren’t using an HTTP sniffing tool, shame on you.  This should be one of your biggest assets when doing web client development like Flash, Silverlight, AJAX, whatever.  For Microsoft developers there are usually 2 tools (both free) that come to the top: Fiddler and Web Development Helper.  I’m a HUGE fan of WebDevHelper (which I just noticed is on CodePlex now, cool Nikhil!) for 2 reasons.  First, it doesn’t require me to change my proxy settings or anything, which is a pain when using Fiddler and the built-in web server with VS because of the dynamic ports it uses.  Second, it is IN THE BROWSER!  I turn it on and I get an explorer bar at the bottom that shows me everything.  Me likey.

    Ok, so using WebDevHelper I turn it on and spot the problem:

    Spot it?  Remember our service was created on http://localhost:XXXX/FooService/Service.asmx?  If you read my previous post on cross-domain access (and soon a how-do-I video will be posted on this topic), you’ll note that the client access policy file must be at the ROOT of the service site. 

    But Tim, it is!

    Well, it is according to the file system, but look at the request Silverlight is making.  The problem here is the web development server in VS.  By default it not only grabs a random port, but also serves things up under a virtual directory (i.e., /FooService/Service.asmx instead of /Service.asmx).  So even though we have our policy file in the root, the web server isn’t treating our app like a root.  Notice the web service project properties:

    The core problem was that it couldn’t find the clientaccesspolicy.xml file and thus denying the request to the service.

    The Solution

    For *this* scenario, the solution (or one of them, easiest in my opinion) is to change the service properties and just change the /FooService to “/” only.  This will restart the server for that project (browser to Service.asmx again just to make sure) and will then be operating under http://localhost:XXXX/Service.asmx

    The next thing we need to do is go back to our Silverlight application and remove the service reference (as it is now invalid because the endpoint is no longer there).  Just select it and delete.  Choose ‘Add Service Reference’ again and point to the newly updated URL.  No need to change/delete the actual code in Page.xaml.cs because it will stay the same as long as you keep the SericeReference1 default name for this example.

    Once you have that, F5 your Silverlight application again and you should see:

    If we turn on WebDevHelper again we can see the policy file being requested and found, then the service call allowed through:

    Again for this scenario (if you are playing around with Silverlight and just messing with services), this may be one of the issues you are running into.  A lot of the time cross-domain policy files may be the issue and that is why an HTTP sniffer is going to be your best friend to see what request is failing and why.  Even though this is an ASMX sample, if you were testing with a WCF service hosted in an ASPNET web site and running under VS2008 web development server, you'd likely run into the same issue.

    Hope this helps!

    Wednesday, April 09, 2008 9:32 PM

    PostTypeIcon

Comments.

  • RadioX said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    I wish you could release this post about two months ago...I already learned how to fix this problems but your way could have been easier.

    4/10/2008 3:03 AM
  • Maciek said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    Good read, since we're talking webservices, I'm having serious trouble with WCF Services - let's use Jesse's WCF Service + LINQ tutorial to illustrate the case.

    void Search_Click(object sender, RoutedEventArgs e)
    {

    ServiceReference1.Service1Client webService =
    new SQLData.ServiceReference1.Service1Client();

    webService.GetCustomersByLastNameCompleted +=
    new EventHandler<SQLData.ServiceReference1.
    GetCustomersByLastNameCompletedEventArgs>
    (webService_GetCustomersByLastNameCompleted);


    webService.GetCustomersByLastNameAsync(LastName.Text);
    }

    After running the debugger it turned out that :

    ServiceReference1.Service1Client webService =
    new SQLData.ServiceReference1.Service1Client();

    is null and thus throwing an exception.

    I believe I've managed to follow everything that was said in the tutorial but I fail to understand why this occurs. Your insight would be apreciated.

    Sincirely.
    Maciek

    4/10/2008 8:03 AM
  • timheuer said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    maciek: were you able to successfully add the service reference and it still is returning null?!

    4/10/2008 8:32 AM
  • Faisal said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    Super post. My Silverlight application is now accessing my Service.
    Great stuff Tim.

    4/10/2008 6:47 PM
  • Hemant said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    spot on. silverlight app was not getting clientaccesspolicy.xml.

    4/11/2008 7:43 AM
  • chase said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    I would like to thank you for your large amount of work in explaining how to solve a difficult problem (albeit, it should be an easy one). I only wish I could get it to work for myself. I have built the FooApp and the FooService as described so eloquently. I have used the fooService address in the FooApp Service Reference and .cs. I have a single development computer with two instances of Visual Studio 2008 running each instance of FooApp and FooService. I have attempted a number of http address in setting up the ServiceReference to no avail. But the result is the same -- I end up with the cross-domain problem each and every time. Unfortunately the WebDevHelper shows no URL or status information as your images display. I am at a loss -- but will keep trying.

    Thanks for your substantial effort...

    4/15/2008 8:56 PM
  • timheuer said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    chase: if you want to send me your solution i'll take a look

    4/15/2008 9:51 PM
  • chase said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    Tim,

    I found that when I build the new project -- C# -- Silverlight Application -- and on the following page, allow the default "Web Site" as project type, none of the above works. It only works (for me) if I select project type of "Web Application Project." The project type of "Web Site" can cause hours of pulling hair out whereas, the project type "Web Application Project" can be running in 5 minutes or less. As well, the WebDevHelper could not return any URL's with "Web Site" project type whereas it worked perfectly with "Web Application Project" project type. So, if you have readers dismayed by all of this, it may be due to this simple difference.

    Now I can see "Hello World"...seem like a trip around the world to get there...

    Thanks for your help

    4/16/2008 8:18 PM
  • timheuer said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    chase: weird. i use web site projects exclusively and no problems with running or using webdev helper.

    4/16/2008 9:17 PM
  • timheuer said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    remember to open the web service project using Open Web Site or you won't be able to see the port/virtual root settings to change

    4/16/2008 9:24 PM
  • chase said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    Tim,
    Did that...done that...Opened it under "Open Web Site..." ...changed virtual directory to / ...matched up ports on both FooApp and FooService... rebuilt the Service Reference...got rid of all temp files...rebuilt again... same error- "cross-domain"

    Your directions are explicit and in detail. Now I just have to figure out how to get Silverlight to work under "Web Application Project" instead of "Web Project"...another set of problems.

    Bruce

    4/17/2008 6:05 PM
  • chase said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    Tim,

    I moved the development environment from Windows Server 2003 x64 to 32bit Windows XP Professional, and the example worked like a charm. I am convinced (albeit I would love to be proved wrong) that mixing web service, Silverligt and ASP.NET derived from "Web Site" (vs. "Web Site Application") option just does not work under x64.


    chase

    4/20/2008 9:45 AM
  • Chili said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    Tim,

    I,ve tried your example but my problem is that my silverlight application won't let me add a service reference.

    Do you know how to solve that?

    Best regards
    Chili

    5/28/2008 1:35 PM
  • Ajay said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    I tried out as you have written in your blog but i am still getting this error when i run the silverlight application:

    An exception of type 'System.ServiceModel.ProtocolException' occurred in System.ServiceModel.dll but was not handled in user code

    Additional information: [UnexpectedHttpResponseCode]
    Arguments:Not Found
    Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=2.0.30226.2&File=System.ServiceModel.dll&Key=UnexpectedHttpResponseCode

    My web service is working fine...

    Could you find a solution??

    6/9/2008 3:24 AM
  • timheuer said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    @Ajay: It sounds like you need a cross-domain policy file in place.

    6/9/2008 7:57 AM
  • Ajay said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    I have the crossdomainpolicy.xml file but i donot know where to put under which project The FOOAPP Silverlight host project or the WebApplication project which implements the Silverlight control...

    6/10/2008 12:15 AM
  • timheuer said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    @Ajay: you would put the policy file in the location where the SERVICE is being hosted -- the root of that domain.

    6/10/2008 8:56 AM
  • M.R.Kannan said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    Hi Tim,
    My project structture is as follows. I have the service and the silverlight project in D: in folders silverlight and sampleservice.

    I have made the sampleservice folder as the root and i have the clientaccesspolicy.xml and crossdomain.xml

    I still getting the error

    An exception of type 'System.ServiceModel.ProtocolException' occurred in System.ServiceModel.dll but was not handled in user code

    Additional information: The remote server returned an unexpected response: (404) Not Found.

    As you have stated, i have places the clientaccesspolicy.xml and crossdomain.xml in the root of the service. I am not able to retrieve the response from the ASMX service.

    Please let know what else should be done to get the response from the web service.

    Kannan

    6/11/2008 7:46 AM
  • timheuer said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    @Kannan: have you used a tool like Web Dev Helper? See: http://timheuer.com/blog/archive/2008/06/10/silverlight-services-cross-domain-404-not-found.aspx

    6/11/2008 8:32 AM
  • M.R.Kannan said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    Yes i did use the web development helper tool. I was able to see the status of 404 when the xml files were not found. I placed the xml files in the root and when i ran the silverlight solution, i kept getting the error that i had mentioned in my previous post.
    The web development helper screen is empty.

    Kannan

    6/11/2008 9:02 PM
  • timheuer said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    @Kannan: even with the policy files in place are you seeing a 200 status request to them in web dev helper? and then the web service call fails? if you can send me a reproduction offline i can take a look. hard to troubleshoot with guessing at this point.

    6/11/2008 9:34 PM
  • M.R.Kannan said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    Hi Tim,
    i see a success status of 200 in the web development helper logging screen. I have the images with me, but how can i upload them in this blog post, i am not sure. "Send me a reproduction offline", what does this mean? I am sorry i am not able to understand. I will send a mail of the images and may be a zip of the source code. Please let know what else i can do to get this resolved

    Kannan

    6/11/2008 9:47 PM
  • Simon H said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    This all makes sense - but what if I do not have control over the service? I have the situation where I have to use a third party service - it has a crossdomain.xml file, but not in the root of the server - it is in the services root folder.

    6/30/2008 1:15 AM
  • timheuer said:
    Gravatar
    # re: My Silverlight application cannot access my service!


    @Simon: For this version of Silverlight, the policy files must be in the root :-(

    6/30/2008 8:54 AM

Your Reply.

  Comment Form  

Fields denoted with a "*" are required.

*Your name:
Subject:
Your blog:
Your email:  (will not be displayed)
*Your message:

 
Please add 2 and 2 and type the answer here: