How to use WCF in Windows 7 Phone Applications?

by Naveen 19. July 2010 05:27

When you are building a data driven Windows 7 Phone application, use a web service or WCF service comes as natural choice. If you have been using WCF for your Silverlight and ASP.Net or any other applications, you will find that use of WCF for Windows 7 Phone is similar to what you have been doing so far. It is easy to the extent that you can simply cut and paste the code from your existing Silverlight to Phone application and it will work like a charm. This holds true if you are not using any namespaces or APIs that are not supported in Windows 7 Phone SDK. Otherwise you are golden. In this post, I will show you how to use WCF in Windows 7 Phone applications.

I will be using project from my previous post Using Bing Map Silverlight Control. In that project, I used a WCF service to pull data from server and associated it with bing map silverlight control. I am going to develop the same application but for Windows 7 Phone. In this post I will just focus on using WCF in Windows 7 Phone.

Create Windows 7 Phone Project

I am assuming that you have installed all development tools needed for Windows 7 Phone application development. Create a new Windows 7 Phone project in Visual Studio 2010. Since I want to display list of users on main page of application, so I picked Windows Phone List Application project. This provides boiler plate code to quickly set up your pages to display list on main page and then a details page to display details when user clicks on an item in the list.

Add Service Reference

Yes, it is the same Add Service Reference menu items in your project that you have seen in Silverlight, ASP.Net or any other .Net application projects. You will follow the same procedure of adding reference to WCF service in Windows 7 Phone application.

Call WCF Service To Fetch Data

It is exactly the same asynchronous model that gets used in Silverlight application. Well that makes sense because Windows 7 Phone development uses Silverlight as well. I copied the code from Silverlight application and used it in Windows Phone application without any change and it worked. The following code snippet shows async call to WCF service to which I added reference to my project.


 public void GetUserConnectionData(int sinceLastId, int maxResults, 
    Action<IEnumerable<UserConnectionDataViewModel>, Exception> callBack)
 {
   _wsActivityMonitor.GetUserConnectionsCompleted += (s, e) =>
   {
    var userCallBack = e.UserState as 
    Action<IEnumerable<UserConnectionDataViewModel>, Exception>;
    if (null == userCallBack)
    {// Wrong data type.return;}
     // Check if we got an error from request.
     if (null != e.Error)
     {
       userCallBack(null, e.Error);
       return;
     }
     // Process results.
     var connectDataList = new List<UserConnectionDataViewModel>();

     foreach (var connectData in e.Result)
     {
       var ucViewModel = new UserConnectionDataViewModel(connectData);
       connectDataList.Add(ucViewModel);
     }

     userCallBack(connectDataList.AsEnumerable<UserConnectionDataViewModel>(), null);
    };

    _wsActivityMonitor.GetUserConnectionsAsync(sinceLastId, maxResults, callBack);
 }

If you will download code from my earlier post, you will find the code to be same. You can play with sample project to see how this all works and how Windows 7 Phone application is binding to data from WCF service.

Give your advice to big bosses and make money

Views: 920

Tags: ,

WCF | Windows 7 Phone

How to add tool tip to Pushpin in Bing Map Silverlight control

by Naveen 13. July 2010 05:40

Download Sample Projects (188.73 kb)

bing maps silverlight control

Some time back I wrote about using Bing Maps Silverlight control. Recently I was developing an application for a client using Bing Maps silverlight control and realized that there have been some changes since I last wrote about it. So this series of posts is focused on some of the following topics.

  • How to use Bing Maps Silverlight control?
  • How to add push pins or location markers on Bing Maps?
  • How to add tool tip to push pin or location on Bing Map?
  • How to use WCF in silverlight application?
  • How to use Bing Maps web service in Silverlight application?
  • .... and more...

How to use Bing Maps Silverlight control?

As I discussed in my previous post that first you need to make sure that you have all the necessary tools on your development machine. So here is some content from previous post.

Set up development enviroment

Before you can start developing your silverlight application using Bing Map Silverlight control, you will need to do following things.

  • Create a developer account at Bing portal
  • As part of registration process, you will also be required to a credential key that is used with each request that you send to Bing web service to access data.
  • Download Bing Map Control SDK and install on your development machine

Create or Update Project

I will recommend reading on Creating a Basic Application Using the Silverlight Map Control. There have been some namespace changes as well as assembly name changes since last version of the control. Therefore it is important to follow the latest article about assembly and namespace references. Following snapshot shows the references of BingMaps control assemblies that you are going to need in your project.

bing maps assemblies

Add Pushpin to Map Control

As I mentioned in my previous post about BingMaps control, the control is a container that can host other child windows. Pushpin is nothing but another control that you add to the map control itself. So you add a map layer to the map and then add Pushpin controls to this map layer. Following code snippet from the sample shows how push pin were added.


void AddMapPushPin(ByteBlocksActivityService.GeoLocation loc)
{
Pushpin pin = new Pushpin();
Location pinLocation = new Location() 
  { Longitude = loc.Longitude, Latitude = loc.Latitude };
pin.Location = pinLocation;
GetLocationDetails(pin);
_mapLayer.AddChild(pin, pinLocation, PositionOrigin.BottomRight);
}

You may be wondering what is GeoLocation parameter to this method. This is one of the objects that I defined in my data service. I will discuss more about how to use WCF in silverlight application in subseuent posts. You can see it is pretty straight forward to add push pin to Bing Map control. You can provide your own image to be used as push pin as well. For me the standard image provided by the map control itself did the job.

Add title to Pushpin

A blank push pin is not going to provide much of information to the users. So it will be helpful if we could display some text on it as well. Depending on image used for displaying push pin, you will have very limited space. So you have to keep the title short so that it fits. This text could be some abbreviation.

You will use Content property of Pushpin control to set text to be displyed on the pushpin as shown in the code below.


pin.Content = address.CountryRegion;

Add Tool tip to Pushpin

push pin tool tip

As i mentioned above, a blank Pushpin does not provide much of information to your users. And there is not much you can display in Content. As with any visual controls, Tooltip is one of the best ways to convey information to users. This is where you can get really creative about displaying details about location or pushpin to your user. For this post, I will keep this display of tool tip to displaying address corresponding to the pin location.

bing maps push pin tool tip

As I mentioned earlier that Pushpin is nothing but another UIElement or control hosted inside Map control. So you can use TooltipService to add tool tip to Pushpin. Following code snippet shows how I added address as tool tip to Pushpin


var tooltipText = "Unkown";
if (e.Result.Results.Count != 0)
{
 var address = e.Result.Results[0].Address;
 tooltipText = address.FormattedAddress;
 pin.Content = address.CountryRegion;
}
System.Windows.Controls.ToolTipService.SetToolTip(pin, tooltipText);

I got address for the given location using ReverseGeoCode service from Bing Maps SOAP Services. I will discuss this in detail when I discuss about how to use Bing Maps SOAP Services in Silverlight applications.

Sample Project

You can download the sample project to play with maps. Remember that you will need to get your own Bing Maps Developer key from Microsoft to use the control.

Give your advice to big bosses and make money

Views: 795

Tags: ,

Bing Map | Silverlight | WCF

Silverlight WCF Error - Custom tool warning: The type 'System.Collections.ObjectModel.ObservableCollection`1' could not be found

by Naveen 16. April 2010 04:59

While developing a Silverlight applicatio, I ran into the following error when I tried to add service reference to one of my WCF services.

Custom tool warning: The type 'System.Collections.ObjectModel.ObservableCollection`1' could not be found

This was really strange because I had the reference to this WCF earlier and I was not running into any issues. I made some service contract interface changes so I had to update the reference in my silverlight application as well. For a moment I thought that the new DataContract and DataMember that I added into the service contract may have something to do with it. I had added a new property to my DataContract which was an enumeration. So I removed that from the contract. I still kept getting the same error.

After fighting with it for an hour or so, I decided to use the ultimate solution that I happen to use for most Microsoft products. I closed the solution and shut down instance of Visual Studio. And then restarted Visual Studio and loaded my projects. Now I added Service Reference to same WCF service and no errors. It seems that there is some bug or something in Visual Studio's reference generation tool that triggers when there is significant change in your service's contracts.

Bottom line is that if you run into similar errors with WCF Service Reference tool, first try this wonderful solution of restarting Visual Studio and reloading your project.

Give your advice to big bosses and make money

Views: 1273

Tags: ,

Silverlight | WCF

WCF Error - Could not find endpoint element with name and contract in the ServiceModel client configuration section

by Naveen 30. March 2010 14:23

This week I had to work on an old Silverlight and WCF application. So I had to make this Silverlight 3.0 application consume a WCF service that is used to perform search in Amazon.com database. This post is about first WCF error I ran into when my silverlight application tried to call into my WCF web service. And I realized this is a very common issue lot of developers run into when developing a Silverlight application that consumes WCF service.


{System.InvalidOperationException: Could not find endpoint element with name 
'BasicEndPoint' and contract 'ProductSearchService.IAmazonSearchService' 
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 name could be found in the client element....

The error provided me some starting point to start my diagnosis. Here are the steps that i followed and approached the solution.

Check WCF Configuration File On Client

When you choose Add Service Reference option in Visual Studio to add a WCF service reference to your Silverlight application, it will add a WCF client configuration file ServiceReferences.ClientConfig in your project. Open that file to check if it does have correct WCF configuration entries. Well, in my case, for some reason Visual Studio choked and added an empty ServiceReferences.ClientConfig file. So I manually added the configuration entried to create a WCF proxy.


<configuration>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicEndPoint" maxBufferSize="2147483647" 
           maxReceivedMessageSize="2147483647">
          <security mode="None" />
        </binding>
        <binding name="BasicHttpBinding_IAmazonSearchService" 
            maxBufferSize="2147483647"
          maxReceivedMessageSize="2147483647">
          <security mode="None" />
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost/ProductsSearch/AmazonSearchService.svc"
        binding="basicHttpBinding" 
        bindingConfiguration="BasicHttpBinding_IAmazonSearchService"
        contract="ProductSearchService.IAmazonSearchService" 
        name="BasicHttpBinding_IAmazonSearchService" />
    </client>
  </system.serviceModel>
</configuration>

After populating configuration, I still kept getting the same when my Silverlight application tried to connect to WCF service. So I moved to next end point of this equation that was server side WCF service.

Silverlight Supports basicHttpBinding and not wsHttpBinding

I quickly checked the service implementation code and did not find anything wrong. There was nothing to check much because my one method in service was returning statically constructed list. So at this point I did not have to worry about diagnosing any issues with Amazon.com web service itself.

Now I opened web.config file to look for configuration entries for my WCF configuration. Oh well, there was something obviously wrong. Notice binding value in endpoint configuration. It is set to wsHttpBinding


<system.serviceModel>
  <behaviors>
   <serviceBehaviors>
    <behavior name="ProductsSearch.AmazonSearchServiceBehavior">
     <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
     </serviceBehaviors>
    </behaviors>
   <services>
    <service behaviorConfiguration="ProductsSearch.AmazonSearchServiceBehavior" 
     name="ProductsSearch.AmazonSearchService">
      <endpoint address="" binding="wsHttpBinding" 
       contract="ProductsSearch.IAmazonSearchService">
        <identity>
         <dns value="localhost"/>
        </identity>
      </endpoint>
      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
  </services>
</system.serviceModel>

Change the endpoint configuration to use basicHttpBinding. Recompile the service and go back to Silverlight project. Right click on the service reference and choose the option to update it. And now compile Silverlight project.

It worked!

Yes, that did work. So if you are working with a Silverlight 3.0 application that is going to consume a WCF service, make sure that:

  • Your WCF service is configured to use basicHttpBinding
  • Your client side WCF configuration file has correct information about the binding etc.
  • And if you are calling the client proxy constructor by name, then you do have correct name for your endpoint in client configuration file.
Give your advice to big bosses and make money

Views: 2678

Tags: ,

.Net | Silverlight | WCF

HTTP Error 404.17 - Not Found, The requested content appears to be script and will not be served by the static file handler

by Naveen 25. March 2010 05:04

If you are developing on Windows 7 or Vista or for that matter operating system where you have IIS7 installed and have Visual Studio 2008 and Visual Studio 2010 installed, at some point you will run into following error when developing WCF service.


HTTP Error 404.17 - Not Found
The requested content appears to be script and will not be served by 
the static file handler.

You do not receive this error because you have one of the components mentioned above installed or because of the operating system. It is combination of few things that causes this error. I read few posts about this error and could not find a comprehensive explanation and solution. I had to stich together few of those suggestions to come up with final solution and explanation. In this post I will make an attempt to discuss how to diagnose this error, why this occurs and how to fix it.

Diagnosis

One thing that IIS7 does very well is that error descriptions have become little bit more descriptive as compared to previous versions. So if you look at the error, it tells that it something to with file handler for the file type that user is trying to access. In my case I have a WCF service so my file is .svc

Requested URL: http://localhost:80/ProductsSearch/AmazonSearchService.svc 

That was kind of strange to me that I had developed a similar application and WCF service using Visual Studio 2010 and did not get this error. But this time I was developing on Visual Studio 2008. So there was first clue that it has something to do with version of some component. Follow the following steps to see what file handler or mime type handlers are installed for your web site.

  • Bring up IIS manager and you will notice an icon in IIS section that reads Handler Mappings.

  • Double click on this icon and you will see a dialog box that looks like image belong and has listing of all file types and the handlers associated with it. Locate the file type that is throwing error for you. In my case it was .svc file for WCF service. I noticed that there are three file handlers associated with this file type and I am still getting the error.

  • Double click on any of these entries and you will see the details that look like image below. It tells you the assembly or module that is mapped to handle requests for these file types. You will notice that in my case it was pointing to correct ISAPI extension BUT it was pointing to .Net 4.0 framework folder.

The last step made things clear that although I have a file handler for .svc file type, but it is being served by framework version for which my site is not configured. I was developing for ASP.Net 2.0. The solution was just to have correct mapping for correct .Net framework that my web site is mapped to.

Finding Mapped Framework For Your Web Site

Each application in IIS7 is configured to use an application pool. And each of these application pools is assigned to a .Net Framework. When you create an application in IIS7 is gets assigned to Default Application Pool by default untill you change it explicitly. And depending on you have configured application pools, this Default Application Pool may be mapped to ASP.Net2.0 or ASP.Net4.0 depending on what all versions of ASP.Net framework you have installed on your machine. In my case Default Application Pool is mapped to .Net 2.0 framework as you can see from the screenshot below.

Default Application Pool

Fix The Error

There are two steps that you will have to perform the error about mapping to static file handler.

Fix Application Pool

Check the application pool for your application. Make sure that it is configured to correct version of .Net framework. You can always a custom application pool in IIS and then configure your application to use that. You can always configure your application to use Classic .Net AppPool. You can see from following screenshot that it is mapped to .Net 2.0 and configured to use Classic pipe line and not integrated one.

Add or Edit Mapping

There is a good chance that your installation of IIS7 does not have mapping for the file type for .Net framework version that your application is using. Follow the following steps to add a new mapping in IIS for your application.

  • Bring up Mapping Handler dialog box for your web application.

  • In right side pane you will notice a link Add Script Map.

  • Click on that link that will bring up Add Script Map dialog box. Enter the required information to create a new mapping. Pay close attention to the handler module file path. Notice that I have created a new mapping for .svc file that is going to be served by aspnet_isapi.dll from v2.0.50727 folder and not from .Net 4.0 folder.

  • Click OK and you should have new file handler added for your application.

This should fix the error.

Give your advice to big bosses and make money

Views: 3890

Tags: ,

IIS | WCF

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>

Give your advice to big bosses and make money

Views: 2025

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();
}

Give your advice to big bosses and make money

Views: 4299

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.

Give your advice to big bosses and make money

Views: 3505

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.

Give your advice to big bosses and make money

Views: 7057

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.

Give your advice to big bosses and make money

Views: 16909

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);
       }
    }
   }
}

Give your advice to big bosses and make money

Views: 5907

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) {}
    
    
Give your advice to big bosses and make money

Views: 13504

Tags:

WCF

Powered by BlogEngine.NET 1.5.1.7
Theme by Naveen Kohli

By Categories