Question How to Pass Proxy info in App.Config file

kbsudhir

New member
Joined
Apr 16, 2013
Messages
1
Programming Experience
Beginner

Hi All,

I have built a Bings Map program using the below link:
Developing a .NET Application Using Bing Maps SOAP Services

Now, this works perfectly at house but same throws the below error when I test it at my office:

[There was no endpoint listening at Service that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details./QUOTE]


In office proxy is used to connect to the internet whereas there is no proxy at my house.

Below is the my code:

Windows form code:
Code:
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;

using BingMapsSampleTest.GeocodeService;
using BingMapsSampleTest.SearchService;
using BingMapsSampleTest.ImageryService;
using BingMapsSampleTest.RouteService;

namespace BingMapsSampleTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private String GeocodeAddress(string address)
        {
            string results = "";
            string key = "AvAQo6JWlBdXloVK2dZVjrBKEebcm7gcug-yzqT7WZXQAWQCNf9WhgKLTCusPyvp";
            GeocodeRequest geocodeRequest = new GeocodeRequest();
            // Set the credentials using a valid Bing Maps key
            geocodeRequest.Credentials = new GeocodeService.Credentials();
            geocodeRequest.Credentials.ApplicationId = key;
            // Set the full address query
            geocodeRequest.Query = address;
            // Set the options to only return high confidence results 
            ConfidenceFilter[] filters = new ConfidenceFilter[1];
            filters[0] = new ConfidenceFilter();
            filters[0].MinimumConfidence = GeocodeService.Confidence.High;
            // Add the filters to the options
            GeocodeOptions geocodeOptions = new GeocodeOptions();
            geocodeOptions.Filters = filters;
            geocodeRequest.Options = geocodeOptions;
            // Make the geocode request
            GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
            
            //GeocodeResponse geocodeResponse = geocodeService.Geocode(geocodeRequest);
            //try
            //{
                GeocodeResponse geocodeResponse = geocodeService.Geocode(geocodeRequest);
            //    if (geocodeResponse.Results.Length > 0)
            //        results = String.Format("Latitude: {0}\nLongitude: {1}",
            //          geocodeResponse.Results[0].Locations[0].Latitude,
            //          geocodeResponse.Results[0].Locations[0].Longitude);
            //    else
            //        results = "No Results Found";
            //    return results;
            //}
            //catch(Exception Ex)
            //{
            //    Console.WriteLine(Ex.InnerException);
            //}
            if (geocodeResponse.Results.Length > 0)
                results = String.Format("Latitude: {0}\nLongitude: {1}",
                geocodeResponse.Results[0].Locations[0].Latitude,
              geocodeResponse.Results[0].Locations[0].Longitude);
            else
                results = "No Results Found";
            return results;
            
        }
        private void btnGeoCode_Click(object sender, RoutedEventArgs e)
        {
            labelResults.Content = GeocodeAddress(textInput.Text);
        }
        private string ReverseGeocodePoint(string locationString)
        {
            string results = "";
            string key = "AvAQo6JWlBdXloVK2dZVjrBKEebcm7gcug-yzqT7WZXQAWQCNf9WhgKLTCusPyvp";
            ReverseGeocodeRequest reverseGeocodeRequest = new ReverseGeocodeRequest();
            // Set the credentials using a valid Bing Maps key
            reverseGeocodeRequest.Credentials = new GeocodeService.Credentials();
            reverseGeocodeRequest.Credentials.ApplicationId = key;
            // Set the point to use to find a matching address
            GeocodeService.Location point = new GeocodeService.Location();
            string[] digits = locationString.Split(',');
            point.Latitude = double.Parse(digits[0].Trim());
            point.Longitude = double.Parse(digits[1].Trim());
            reverseGeocodeRequest.Location = point;
            // Make the reverse geocode request
            GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
            GeocodeResponse geocodeResponse = geocodeService.ReverseGeocode(reverseGeocodeRequest);
            if (geocodeResponse.Results.Length > 0)
                results = geocodeResponse.Results[0].DisplayName;
            else
                results = "No Results found";
            return results;
        }
        private void btnReverseGeocode_Click(object sender, RoutedEventArgs e)
        {
            labelResults.Content = ReverseGeocodePoint(textInput.Text);
        }
        private string SearchKeywordLocation(string keywordLocation)
        {
            String results = "";
            String key = "AvAQo6JWlBdXloVK2dZVjrBKEebcm7gcug-yzqT7WZXQAWQCNf9WhgKLTCusPyvp";
            SearchRequest searchRequest = new SearchRequest();
            // Set the credentials using a valid Bing Maps key
            searchRequest.Credentials = new SearchService.Credentials();
            searchRequest.Credentials.ApplicationId = key;
            //Create the search query
            StructuredSearchQuery ssQuery = new StructuredSearchQuery();
            string[] parts = keywordLocation.Split(';');
            ssQuery.Keyword = parts[0];
            ssQuery.Location = parts[1];
            searchRequest.StructuredQuery = ssQuery;
            //Define options on the search
            searchRequest.SearchOptions = new SearchOptions();
            searchRequest.SearchOptions.Filters =
                new FilterExpression()
                {
                    PropertyId = 3,
                    CompareOperator = CompareOperator.GreaterThanOrEquals,
                    FilterValue = 8.16
                };
            //Make the search request 
            SearchServiceClient searchService = new SearchServiceClient("BasicHttpBinding_ISearchService");
            SearchResponse searchResponse = searchService.Search(searchRequest);
            //Parse and format results
            if (searchResponse.ResultSets[0].Results.Length > 0)
            {
                StringBuilder resultList = new StringBuilder("");
                for (int i = 0; i < searchResponse.ResultSets[0].Results.Length; i++)
                {
                    resultList.Append(String.Format("{0}. {1}\n", i + 1,
                        searchResponse.ResultSets[0].Results[i].Name));
                }
                results = resultList.ToString();
            }
            else
                results = "No results found";
            return results;
        }
        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            labelResults.Content = SearchKeywordLocation(textInput.Text);
        }
        private string GetImagery(string locationString)
        {
            string key = "AvAQo6JWlBdXloVK2dZVjrBKEebcm7gcug-yzqT7WZXQAWQCNf9WhgKLTCusPyvp";
            MapUriRequest mapUriRequest = new MapUriRequest();
            // Set credentials using a valid Bing Maps key
            mapUriRequest.Credentials = new ImageryService.Credentials();
            mapUriRequest.Credentials.ApplicationId = key;
            // Set the location of the requested image
            mapUriRequest.Center = new ImageryService.Location();
            string[] digits = locationString.Split(',');
            mapUriRequest.Center.Latitude = double.Parse(digits[0].Trim());
            mapUriRequest.Center.Longitude = double.Parse(digits[1].Trim());
            // Set the map style and zoom level
            MapUriOptions mapUriOptions = new MapUriOptions();
            mapUriOptions.Style = MapStyle.AerialWithLabels;
            mapUriOptions.ZoomLevel = 17;
            // Set the size of the requested image in pixels
            mapUriOptions.ImageSize = new ImageryService.SizeOfint();
            mapUriOptions.ImageSize.Height = 200;
            mapUriOptions.ImageSize.Width = 300;
            mapUriRequest.Options = mapUriOptions;
            //Make the request and return the URI
            ImageryServiceClient imageryService = new ImageryServiceClient("BasicHttpBinding_IImageryService");
            MapUriResponse mapUriResponse = imageryService.GetMapUri(mapUriRequest);
            return mapUriResponse.Uri;
        }
        private void btnRequestImage_Click(object sender, RoutedEventArgs e)
        {
            // Make label hidden and image visible
            labelResults.Visibility = Visibility.Hidden;
            imageResults.Visibility = Visibility.Visible;
            //Get URI and set image
            String imageURI = GetImagery(textInput.Text);
            imageResults.Source = new BitmapImage(new Uri(imageURI));
        }
        private string RequestImageMetadata(string locationString)
        {
            string results = "";
            string key = "AvAQo6JWlBdXloVK2dZVjrBKEebcm7gcug-yzqT7WZXQAWQCNf9WhgKLTCusPyvp";
            ImageryMetadataRequest metadataRequest = new ImageryMetadataRequest();
            // Set credentials using a valid Bing Maps key
            metadataRequest.Credentials = new ImageryService.Credentials();
            metadataRequest.Credentials.ApplicationId = key;
            // Set the imagery metadata request options
            ImageryService.Location centerLocation = new ImageryService.Location();
            string[] digits = locationString.Split(',');
            centerLocation.Latitude = double.Parse(digits[0].Trim());
            centerLocation.Longitude = double.Parse(digits[1].Trim());
            metadataRequest.Options = new ImageryMetadataOptions();
            metadataRequest.Options.Location = centerLocation;
            metadataRequest.Options.ZoomLevel = 10;
            metadataRequest.Style = MapStyle.AerialWithLabels;
            // Make the imagery metadata request 
            ImageryServiceClient imageryService = new ImageryServiceClient("BasicHttpBinding_IImageryService");
            ImageryMetadataResponse metadataResponse =
              imageryService.GetImageryMetadata(metadataRequest);
            ImageryMetadataResult result = metadataResponse.Results[0];
            if (metadataResponse.Results.Length > 0)
                results = String.Format("Uri: {0}\nVintage: {1} to {2}\nZoom Levels: {3} to {4}",
                    result.ImageUri,
                    result.Vintage.From.ToString(),
                    result.Vintage.To.ToString(),
                    result.ZoomRange.From.ToString(),
                    result.ZoomRange.To.ToString());
            else
                results = "Metadata is not available";
            return results;
        }
        private void btnRequestMetadata_Click(object sender, RoutedEventArgs e)
        {
            labelResults.Content = RequestImageMetadata(textInput.Text); 
        }
        private string CreateRoute(string waypointString)
        {
            string results = "";
            string key = "AvAQo6JWlBdXloVK2dZVjrBKEebcm7gcug-yzqT7WZXQAWQCNf9WhgKLTCusPyvp";
            RouteRequest routeRequest = new RouteRequest();
            // Set the credentials using a valid Bing Maps key
            routeRequest.Credentials = new RouteService.Credentials();
            routeRequest.Credentials.ApplicationId = key;
            //Parse user data to create array of waypoints
            string[] points = waypointString.Split(';');
            Waypoint[] waypoints = new Waypoint[points.Length];
            int pointIndex = -1;
            foreach (string point in points)
            {
                pointIndex++;
                waypoints[pointIndex] = new Waypoint();
                string[] digits = point.Split(','); waypoints[pointIndex].Location = new RouteService.Location();
                waypoints[pointIndex].Location.Latitude = double.Parse(digits[0].Trim());
                waypoints[pointIndex].Location.Longitude = double.Parse(digits[1].Trim());
                if (pointIndex == 0)
                    waypoints[pointIndex].Description = "Start";
                else if (pointIndex == points.Length)
                    waypoints[pointIndex].Description = "End";
                else
                    waypoints[pointIndex].Description = string.Format("Stop #{0}", pointIndex);
            }
            routeRequest.Waypoints = waypoints;
            // Make the calculate route request
            RouteServiceClient routeService = new RouteServiceClient("BasicHttpBinding_IRouteService");
            RouteResponse routeResponse = routeService.CalculateRoute(routeRequest);
            // Iterate through each itinerary item to get the route directions
            StringBuilder directions = new StringBuilder("");
            if (routeResponse.Result.Legs.Length > 0)
            {
                int instructionCount = 0;
                int legCount = 0;
                foreach (RouteLeg leg in routeResponse.Result.Legs)
                {
                    legCount++;
                    directions.Append(string.Format("Leg #{0}\n", legCount));
                    foreach (ItineraryItem item in leg.Itinerary)
                    {
                        instructionCount++;
                        directions.Append(string.Format("{0}. {1}\n",
                            instructionCount, item.Text));
                    }
                }
                //Remove all Bing Maps tags around keywords.  
                //If you wanted to format the results, you could use the tags
                Regex regex = new Regex("<[/a-zA-Z:]*>",
                  RegexOptions.IgnoreCase | RegexOptions.Multiline);
                results = regex.Replace(directions.ToString(), string.Empty);
            }
            else
                results = "No Route found";
            return results;
        }
        private void btnRoute_Click(object sender, RoutedEventArgs e)
        {
            labelResults.Content = CreateRoute(textInput.Text); 
        }

        private string CreateMajorRoutes(string locationString)
        {
            string results = "";
            string key = "AvAQo6JWlBdXloVK2dZVjrBKEebcm7gcug-yzqT7WZXQAWQCNf9WhgKLTCusPyvp";
            MajorRoutesRequest majorRoutesRequest = new MajorRoutesRequest();
            // Set the credentials using a valid Bing Maps key
            majorRoutesRequest.Credentials = new RouteService.Credentials();
            majorRoutesRequest.Credentials.ApplicationId = key;
            // Set the destination of the routes from major roads
            Waypoint endPoint = new Waypoint();
            endPoint.Location = new RouteService.Location();
            string[] digits = locationString.Split(',');
            endPoint.Location.Latitude = double.Parse(digits[0].Trim());
            endPoint.Location.Longitude = double.Parse(digits[1].Trim());
            endPoint.Description = "Location";
            // Set the option to return full routes with directions
            MajorRoutesOptions options = new MajorRoutesOptions();
            options.ReturnRoutes = true;
            majorRoutesRequest.Destination = endPoint;
            majorRoutesRequest.Options = options;
            // Make the route-from-major-roads request
            RouteServiceClient routeService = new RouteServiceClient("BasicHttpBinding_IRouteService");
            // The result is an MajorRoutesResponse Object
            MajorRoutesResponse majorRoutesResponse = routeService.CalculateRoutesFromMajorRoads(majorRoutesRequest);
            Regex regex = new Regex("<[/a-zA-Z:]*>",
              RegexOptions.IgnoreCase | RegexOptions.Multiline);
            if (majorRoutesResponse.StartingPoints.Length > 0)
            {
                StringBuilder directions = new StringBuilder();
                for (int i = 0; i < majorRoutesResponse.StartingPoints.Length; i++)
                {
                    directions.Append(String.Format("Coming from {1}\n", i + 1,
                        majorRoutesResponse.StartingPoints[i].Description));
                    for (int j = 0;
                      j < majorRoutesResponse.Routes[i].Legs[0].Itinerary.Length; j++)
                    {
                        //Strip tags
                        string step = regex.Replace(
                          majorRoutesResponse.Routes[i].Legs[0].Itinerary[j].Text, string.Empty);
                        directions.Append(String.Format("     {0}. {1}\n", j + 1, step));
                    }
                }
                results = directions.ToString();
            }
            else
                results = "No Routes found";
            return results;
        }
        private void btnMajorRoutes_Click(object sender, RoutedEventArgs e)
        {
            labelResults.Content = CreateMajorRoutes(textInput.Text); 
        }
 

    }
}
app.config

Code:

C#:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IGeocodeService" />
                <binding name="BasicHttpBinding_ISearchService" />
                <binding name="BasicHttpBinding_IImageryService" />
                <binding name="BasicHttpBinding_IRouteService" />
            </basicHttpBinding>
            <customBinding>
                <binding name="CustomBinding_IGeocodeService">
                    <binaryMessageEncoding />
                    <httpTransport />
                </binding>
                <binding name="CustomBinding_ISearchService">
                    <textMessageEncoding messageVersion="Soap12" />
                    <httpTransport />
                </binding>
                <binding name="CustomBinding_IImageryService">
                    <binaryMessageEncoding />
                    <httpTransport />
                </binding>
                <binding name="CustomBinding_IRouteService">
                    <binaryMessageEncoding />
                    <httpTransport />
                </binding>
            </customBinding>
        </bindings>
        <client>
            <endpoint address="[URL="http://dev.virtualearth.net/webservices/v1/geocodeservice/GeocodeService.svc"]Service[/URL]"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IGeocodeService"
                contract="GeocodeService.IGeocodeService" name="BasicHttpBinding_IGeocodeService" />
            <endpoint address="[URL="http://dev.virtualearth.net/webservices/v1/searchservice/searchservice.svc"]Service[/URL]"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ISearchService"
                contract="SearchService.ISearchService" name="BasicHttpBinding_ISearchService" />
            <endpoint address="[URL="http://dev.virtualearth.net/webservices/v1/imageryservice/imageryservice.svc"]Service[/URL]"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IImageryService"
                contract="ImageryService.IImageryService" name="BasicHttpBinding_IImageryService" />
            <endpoint address="[URL="http://dev.virtualearth.net/webservices/v1/routeservice/routeservice.svc"]Service[/URL]"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IRouteService"
                contract="RouteService.IRouteService" name="BasicHttpBinding_IRouteService" />
        </client>
    </system.serviceModel>
 
 <!--<httpTransport manualAddressing="false" maxBufferPoolSize="524288"
  maxMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous"
  bypassProxyOnLocal="true" hostNameComparisonMode="StrongWildcard"
  mapAddressingHeadersToHttpHeaders="true" proxyAuthenticationScheme="Anonymous"
  realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false"
  useDefaultWebProxy="true" />-->
  
  <!--<system.net>
    <defaultProxy useDefaultCredentials="true"/>
  </system.net>-->
</configuration>

I get the above error on the below line of code & similar line across.

Code:
C#:
[FONT=Courier New]GeocodeResponse geocodeResponse = geocodeService.Geocode(geocodeRequest)[/FONT]

Now, solution is to provide proper proxy info.
I tried two code in app.config.

First one.

Code:
C#:
[FONT=Courier New]<system.net>    
<defaultProxy useDefaultCredentials="true"/>
</system.net>[/FONT]

With this code error remains same.

Second code in app.config is:

Code:

C#:
<httpTransport manualAddressing="false" maxBufferPoolSize="524288"
  maxMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous"
  bypassProxyOnLocal="true" hostNameComparisonMode="StrongWildcard"
  mapAddressingHeadersToHttpHeaders="true" proxyAuthenticationScheme="Anonymous"
  realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false"
  useDefaultWebProxy="true" />

Here I get a different error, this is -
The type initializer for 'System.ServiceModel.Diagnostics.TraceUtility' threw an exception


Please guide on how to pass proper proxy info in app.config file.

Regards
Sudhir
 

Latest posts

Back
Top Bottom