Export (0) Print
Expand All

How to: Consume a Web Service from X++

Dynamics AX 2009

This topic describes how to consume an external Web service from X++ in Microsoft Dynamics AX. The first step to consuming an external Web service is to add a reference to the Web service. For more information, see How to: Add a Service Reference. This code works with Live Search 1.1b.

NoteNote

Code that consumes a Web service must run on the server, otherwise you will receive an error.


After you add the service reference, the methods of the Web service are available in X++ through Intellisense. The following example shows you how to consume the Microsoft Windows Live Search service. This example issues a search and returns the results in an Infolog window.

ImportantImportant

In order to use the Live Search Web service, you must have the necessary resources and provision your application by getting an application ID. For more information about the Live Search API, see Getting Started with the Live Search API.


For more information about security, see "Security considerations for AIF Web services" in the Server and Database Administration Help.

  1. In the AOT, navigate to the Classes node, right-click and select New Class.

  2. Right-click the new class and select Properties.

  3. Set the Name property to LiveSearchTestClass.

  4. Set the RunOn property to Server.

  5. Right-click the class and select New Method. Replace the method with the following code in the code editor. This adds a main method that calls the search service with a search string and displays the results in an Infolog window.

    public static void main(Args _args)
    {
        Container searchResults;
        int i;
        ;
    
        // Call the method to issue the search with the search criteria.
        // Replace this string with the string you want to search for.
        searchResults = LiveSearchTestClass::
            searchLive("Dynamics AX");
    
        // Display the search results.
        info(strfmt("Total # of hits...%1", conpeek(searchResults, 1)));
        info(conpeek(searchResults, 2));
    }
    

    If you call this code from a form button clicked event, you could display the results in text boxes by setting the control text property to the container values as shown in the following code.

    NumberHits.text(strfmt("Total # of hits...%1", 
        conpeek(results, 1)));
    SearchResults.text(conpeek(results, 2));
    
  6. Right-click the class and select New Method. Replace the method with the following code in the code editor. This method creates the source request and puts it in an array.

    public static WindowsLiveSearch.SourceRequest[] getSourceRequestArray()
    {
        WindowsLiveSearch.SourceRequest[] array;
        WindowsLiveSearch.SourceRequest sourceRequest;
        WindowsLiveSearch.SourceType sourceType;
        
        try
        {
            new InteropPermission(InteropKind::ClrInterop).assert();
            // Create the source request and designate the type
            // of search.
            sourceRequest = new WindowsLiveSearch.SourceRequest();
            sourceType = WindowsLiveSearch.SourceType::Web;
    
            sourceRequest.set_Source(sourceType);
    
            // Add the source request to an array.
            array = new WindowsLiveSearch.SourceRequest[1]();
            array.SetValue(sourceRequest, 0);
            return array;
        }
        catch(Exception::CLRError)
        {
            throw error(AifUtil::getClrErrorMessage());
        }
    }
    
  7. Right-click the class and select New Method. Replace the method with the following code in the code editor. This is the method that calls the Live Search Web service and returns the search results in a container.

    public static container searchLive(str searchQuery)
    {
    #File
        WindowsLiveSearch.MSNSearchPortTypeClient searchService;
        ClrObject sourceRequestArray, searchRequestObj;
        WindowsLiveSearch.SearchRequest searchRequest;
        WindowsLiveSearch.SearchResponse searchResponse;
        WindowsLiveSearch.SourceResponse[] sourceResponseArray, resultsArray;
        ArrayIdx idx1, idx2;
        int srcResponseLength, resultsLength, totalHits;
        WindowsLiveSearch.Result searchResult;
        WindowsLiveSearch.SourceResponse sourceResponse;
        TextBuffer searchResultBuff;
        str title, description, url;
        ;
        try
        {
            searchResultBuff = new TextBuffer();
            new InteropPermission(InteropKind::ClrInterop).assert();
    
            // Create the search request.
            searchRequestObj = new WindowsLiveSearch.SearchRequest();
            // Replace this string with your Application ID.
            searchRequestObj.set_AppID("YOUR_LIVESEARCH_APP_ID");
            searchRequestObj.set_CultureInfo("en-us");
            searchRequestObj.set_Query(searchQuery);
    
            sourceRequestArray =
                LiveSearchTestClass::getSourceRequestArray();
            searchRequestObj.set_Requests(sourceRequestArray);
    
            //Create the service and call it.
            searchRequest = searchRequestObj;
            searchService = new WindowsLiveSearch.MSNSearchPortTypeClient();
            searchResponse = searchService.Search(searchRequest);
            sourceResponseArray = searchResponse.get_Responses();
    
            // Iterate through the search results.
            srcResponseLength = sourceResponseArray.get_Length();
            // Iterating through a .NET array so start at zero.
            for(idx1=0; idx1 < srcResponseLength ; idx1++)
            {
                sourceResponse = sourceResponseArray.GetValue(idx1);
    
                totalHits = ClrInterop::getAnyTypeForObject(
                    sourceResponse.get_Total());
                resultsArray = sourceResponse.get_Results();
                resultsLength = resultsArray.get_Length();
    
                // Iterating through .NET array so start at zero.
                for(idx2=0; idx2 < resultsLength ; idx2++)
                {
                    searchResult = resultsArray.GetValue(idx2);
                    // Gets the title, description, and URL and appends
                    // it to the search results.
                    title = searchResult.get_Title();
                    searchResultBuff.appendText(title);
                    searchResultBuff.appendText(#delimiterCRLF);
                    description =  searchResult.get_Description();
                    searchResultBuff.appendText(description);
                    searchResultBuff.appendText(#delimiterCRLF);
                    url =  searchResult.get_Url();
                    searchResultBuff.appendText(url);
                    searchResultBuff.appendText(#delimiterCRLF);
                    searchResultBuff.appendText("---------------------
                        --------------------------------------------");
                    searchResultBuff.appendText(#delimiterCRLF);
                }
            }
    
            CodeAccessPermission::revertAssert();
    
            // Convert the buffer to a string and add it to a container.
            return [totalHits, searchResultBuff.getText()];
    
        }
        catch(Exception::CLRError)
        {
            throw error(AifUtil::getClrErrorMessage());
        }
    }
    

    You should now have a class named LiveSearchTest with three methods:

    • getSourceRequestArray

    • main

    • SearchLive

  8. Press F7 to compile the class and press F5 to run the main method. The search results should appear in an Infolog window as shown in the following figure.

AIF Consume Web Service Search Results

The results from a call to the Microsoft Live Search service

For more information about consuming external Web services from X++, see Consuming Web Services in Microsoft Dynamics AX 2009 white paper.

  • If the WSDL of the external Web service contains an enum, you will need to restart the AOS service. If you add a service reference and you receive an error, this may be the cause.

  • You may receive the following error message when adding a service reference to the LiveSearch service:

    The remote name could not be resolved: ‘soap.search.msn.com’
    

    This could indicate that the server is not using the proxy settings of the machine. If you receive this error message, add the following settings to the Ax32Serv.config file. This file is located in the Server\Bin directory. If your installation does not have this file, you must create it.

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <system.net>
        <defaultProxy>
          <proxy usesystemdefault="False" proxyaddress="http://serverproxyaddress.com" bypassonlocal="True" autoDetect="False" />
        </defaultProxy>
      </system.net>
    </configuration>
    

Community Additions

ADD
Show:
© 2015 Microsoft