Silverlight Cross Domain Web Service Access Error - This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place

by Naveen 9. March 2010 08:37

Here is some error that most of Silverlight developers run into at some point.


An error occurred while trying to make a request to URI 
'http://nave-pc/SilverGridWeb/GridDataService.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. This error may also be caused by using internal types 
in the web service proxy without using the InternalsVisibleToAttribute attribute. 
Please see the inner exception for more details.

I had developed cross-domain access web services for Silverlight in the past and all work like a charm. This morning I ran into this issue again while developing a new web service for a new Silverlight application. I knew that I needed to add CrossDomain.xml or ClientAccessPolicy.xml at root of my web application. So I copied those files from existing application to this new one. To my surprise it did not resolve the issue. I tried all kind of tricks and options but nothing seemed to help. Finally I decided to look at Silverlight documentation and see if there is anything new that has been done for Silverlight 3. Last time I did this was for a Silverlight 2.0 application. I could not find anything different in the description of what needed to be done. But then there was something in the sample XML file content for these files that caught my eye and looked different that what I had.


<allow-from http-request-headers="SOAPAction" >

Notice the underlined section. Previously the value in the allowed headers used to be *. Well, that does not seem to work any more. So I replaced it and everything worked fine.

There are some other important points I am going to discuss in this post. A lot of users do not seem to be clear where these cross domain policy files should be placed.

Location of CrossDomain.xml and ClientAccessPolicy.xml

As the documentation states, these should be placed at the root of the application. Although the statement is very clear but it causes lot of confusion about what is root? There are two ways you create a site in IIS, Virtual Directory and Web Application. So if you have a web site foo.com created as a web site in IIS, then the folder containing the content of this site is root of the application. So your policy files go in that folder. If you have created a virtual directory Bar under this web site where your web service is hosted, then the root of the site is still foo.com and not foo.com/bar. To verify it, open IIS log of your application and look for entries for Crossdomain.xml and ClientAccessPolicy.xml. From those entries you can figure out where those files should be located. If the caller is not finding those files, then you should 404 errors in your log file. For example here are entries from my log file.


1.17.30.170 GET /clientaccesspolicy.xml - 80 - 1.17.30.162  404 0 2 1
1.17.30.170 GET /crossdomain.xml - 80 - 1.17.30.162 404 0 2 1

This is very important. If you are hosting your web service in a web application that is created as a virtual directory in Default Web Site then you need to copy these files in wwwroot folder or whatver folder is configured to be default folder for your IIS installation. Copying policy files in your virtual directory is not going to help. You can also verify the location by looking at traffic in fiddler for your web service access.

Content for CrossDomain.xml and ClientAccessPolicy.xml

I have copied the content of these two files below. These files work for me on my my servers for cross domain access from silverlight.

ClientAccessPolicy.xml


<?xml version="1.0" encoding="utf-8"?>
<access-policy>
	<cross-domain-access>
		<policy>
			<allow-from http-request-headers="SOAPAction ">
				<domain uri="*"/>
			</allow-from>
			<grant-to>
				<resource path="/" include-subpaths="true"/>
			</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="SOAPAction,Content-Type"/>
</cross-domain-policy>

Views: 59

Tags: , ,

Silverlight | WCF | Web Service

WCF Error - The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state

by Naveen 15. January 2010 11:37

While working on a WCF service, I ran into the following error.


The communication object, System.ServiceModel.Channels.ServiceChannel,
cannot be used for communication because it is in the Faulted state.

This occurred when called Close method on instance of my WCF service client object. For a moment it took me by surprise. The code has been working fine and I was doing the right thing of closing connection to my WCF service after I was done using it. When I looked at the stack trace, I realized that it got thrown from a finally block of a method where I was calling a method on my WCF object. And before that there was an exception thrown. After further investigation it turned out that my WCF service was not running. So when I called method on the object, I got EndpointNotFoundException exception thrown when method was called. And in the same exception handling block I tried to call Close on client object. Since the client was already in bad state so next exception was thrown. So as a best practice, before you call Close method on your service object, check if its in Open state or not. This is exactly like a database connection object where you can check if its in open state or not. The following code snippet shows the change that I made to check for state of the WCF client object.


if (_serviceClient.State == CommunicationState.Opened)
{
 _serviceClient.Close();
}

Views: 945

Tags:

WCF

Error: ServiceHost only supports class service Types

by Viper 17. March 2009 11:53

While adding service reference to a IIS hosted WCF service in Silverlight application, I ran into the following error.

ServiceHost only supports class service Types

In your WCF service if you look at markup .svc file of your service, you will notice from where reference to ServiceHost came. In my service, it looks like as below.


<%@ ServiceHost Language="C#" Debug="true" 
Service="SearchService.SearchServer" CodeBehind="SearchServer.svc.cs" %>

You can see that there are only 2 things that can go wrong in this declaration. One, the service class that implements your service does not match with the declaration in this mark up. This is usually the cause of this error because most of the time you modify the wizard generated interface and service class names and you forget to modify the declarations in this SVC file. Make sure that all entries in mark up file match with actual class and interface names.

Views: 1935

Tags: ,

Silverlight | WCF

Custom tool warning: No endpoints compatible with Silverlight 2 were found

by Viper 10. March 2009 18:40

When you use Add Service Reference wizard to add a reference to existing WCF service to your silverlight application, you may run into this warning. The description of the warning has all the details about the issue and also tells you what to do to fix it. Now you are wondering why this happened. When you use Visual Studio to create WCF project, you will notice that it generates a configuration file for your service as well where you can configure endpoint, bindings etc. for your WCF service. If you have not modified your configuration file, you may notice something like below set as endpoint.

<endpoint address="" binding="wsHttpBinding" 
contract="ByteBlocks.ForExService.ICurrencyService">

Notice that binding is set to wsHttpBinding. This is the binding that provides you connectivity over HTTP/HTTPS with features like reliability, security etc. as specified in WS* protocol. The problem is that Silverlight 2 applications can only connect with ASMX-based web services or services that conform to WS-I Basic Profile 1.1. What that means is that Silverlight applications can only create BasicHttpbinding. So if you modify your service to expose an endpoint that implements basicHttpBinding you are good to go. If your existing WCF service is not tightly coupled with any of WS* features then you can change the existing configuration file as below.

<endpoint address="" binding="basicHttpBinding" 
contract="ByteBlocks.ForExService.ICurrencyService">

Now if you try Add Service Reference tool to add reference to your WCF service, you will not see such warning and a nice set of proxy classes will be created for you to start communicating with WCF service.

Views: 4257

Tags: ,

Silverlight | WCF

The type provided as the Service attribute value in the ServiceHost directive could not be found

by Viper 10. March 2009 15:07

Some time when you use Add Service Reference to add reference to your WCF service, you may run into error like:

The type 'ForExService.Service1', provided as the Service attribute value in the ServiceHost directive could not be found

This error is very self explanatory telling that some type could not be found. Well if that type is missing in my service, how did the tool know about it. Well this exactly is the cause of this error. The tool looks at .svc file. And it found the following line in markup.


ServiceHost Language="C#" Debug="true" Service="ForExService.Service1" CodeBehind="CurrencyService.svc.cs

You probably can see the problem in line above. The service type is set to "ForExService.Service1" where the code behind was modified to name the service classes differently. So if you run into this kind of error, make sure that you check mark up of your service file as well to make sure that it matches the implementation in code.

Views: 9285

Tags:

.Net | WCF

Connect to Amazon.com web service using WCF

by Viper 3. February 2009 08:39

In my previous post WCF Error I discussed adding app.config to your application to get Amazon.com web service client to work. I also mentioned in that post that you can provide Binding and EndPoint parameters programatically to send search request to Amazon.com web service. Here is the sample code that demonstrates how you can do that.


using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;
using AmazonClient.AmazonData;
namespace AmazonClient
{
  class Program
  {
    static void Main(string[] args)
    {
       System.ServiceModel.BasicHttpBinding httpBinding = new BasicHttpBinding();
       httpBinding.Name = "AWSECommerceServiceBinding";
       BasicHttpSecurity security = httpBinding.Security;
       security.Mode = BasicHttpSecurityMode.None;
       EndpointAddress addr = 
         new EndpointAddress("http://soap.amazon.com/onca/soap?Service=AWSECommerceService");
       AWSECommerceServicePortTypeClient client = 
        new AWSECommerceServicePortTypeClient(httpBinding,  addr);
            
       try
       {
         ItemSearch srch = new ItemSearch();
         srch.AssociateTag = "xxxxxxx";
         srch.AWSAccessKeyId = "xxxxxx";
         ItemSearchRequest req = new ItemSearchRequest();
         req.Keywords = "silverlight";
         req.SearchIndex = "Books";
         srch.Request = new ItemSearchRequest[1]{req};
         ItemSearchResponse resp = client.ItemSearch(srch);
         if (null != resp)
         {
           Console.WriteLine("It works!");
         }
       }
       catch(Exception ex)
       {
         Console.WriteLine(ex.Message);
       }
    }
   }
}

Views: 3771

Tags:

WCF | ECommerce

Could not find default endpoint element that references contract error

by Viper 1. February 2009 20:43

I am working on an API to consume Amazon.com web services to search product. Previously I had consumed Amazon.com web services as a web reference. This time I decided to use .Net 3.5 WCF service reference for this web service. After implementing a simple book search API, I wrote a console application to test it out. As soon as the library tried to create instance of web service client, I got the following error.

Could not find default endpoint element that references contract 'AmazonData.AWSECommerceServicePortType' 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.

I looked at the consuming application's BIN folder. I did not see any configuration file. Then I looked at BIN folder of my class library. I found that ServiceModel Metadata Utility Tool (Svcutil.exe) generated app.config file in the project and it got compiled into MyApi.dll.config. This configuration contains binding, endpoint etc. definitions that default constructor of AWSECommerceServicePortTypeClient object was looking for. There are couple of options you have to fix this problem.

  • In app.config file of consuming application, create the required entries.
  • Copy config file (MyApi.dll.config) from class library to bin folder of consuming application and rename it to MyApp.config
  • Programatically create instances of Binding and RemoteAddress objects and use the constructor that takes these 2 parameters.
    
     public AWSECommerceServicePortTypeClient
      (System.ServiceModel.Channels.Binding binding,
       System.ServiceModel.EndpointAddress remoteAddress) : 
                    base(binding, remoteAddress) {}
    
    

Views: 9029

Tags:

WCF

Powered by BlogEngine.NET 1.4.6.1
Theme by Naveen Kohli

Recent

By Categories