Managed Extensions Example That Calls the Amazon Web Service

Managed Extensions Example That Calls the Amazon Web Service

Welcome to this week's installment of .NET Tips & Techniques! Each week, award-winning Architect and Lead Programmer Tom Archer from the Archer Consulting Group demonstrates how to perform a practical .NET programming task using either C# or Managed C++ Extensions.

I recently attended a major conference where I was surprised to hear many extremely intelligent and talented programmers state that they had not spent a lot of time working with or investigating Web services and what they could do for their companies. When I asked a few of them why, I was shocked to hear that many of them had gotten the idea that Web services were just too much of a pain to work with from C++. I do agree that writing a Web services client from an MFC application requires several steps. However, the magic of Visual C++ is that you can mix native (non-.NET) and managed (.NET) code. Therefore, in this week's installment of the .NET Tips & Techniques series, I'll illustrate just how easily you can access a Web service using the .NET Managed Extensions to C++.

Notes on the Amazon Web Service and This Article

The example I chose calls the Amazon Web Service to perform a search based on the passed ISBN value.

Obviously, my intention is not to document the Amazon Web Service (it's very large and extremely well documented on their Web site), but to illustrate that calling a Web service is as easy as writing a couple of lines of code. I simply chose Amazon because it's a Web service that everyone can access.

Also note that to run the code shown in this article (or in the attached demo), you need to acquire your own "developer token" from Amazon. It is completely free and comes with no strings attached. You can acquire your developer token here.

When you have your developer token, simply plug it into this article's attached demo. You do not need to download the Amazon Web Service Toolkit in order to use this example. However, if you wish to do so (it's also free and comes with no obligation), the toolkit can be downloaded here and comes with tons of great examples written in many languages..

Managed Extensions Example That Calls the Amazon Web Service

Using the XmlTextReader to Invoke a Web Service

The easiest way to call a Web service is to let the .NET XmlTextReader do the heavy lifting. When you pass the URL of a Web service to the XmlTextReader constructor, it actually makes the call for you and then puts the data into an XmlTextReader object—just as if you had read an XML file from disk!

From there, you can either read through the data sequentially (the XmlTextReader is a fast, non-cached, forward-only reader for XML data) or you can load the data into an XmlDocument object where you can dynamically position it within the XML document per your application's needs—such as in searching and modifying specific node values.

  1. The first thing you'll need to do is add the following using namespace entries:
  2. using namespace System::Xml;
    using namespace System::Text;
    
  3. The following class (AmazonClient) contains a static function (FindISBN) that is all you need:
  4. class AmazonClient
    {
    public:
      static void FindISBN(String* isbn)
      {
        try
        {
          StringBuilder* url =  new
          StringBuilder();url->Append(S"http://xml.amazon.com/onca/xml3?t=
          webservices-20");url->Append(S"&dev-t=TOKEN");  
          // <=== Insert your Amazon developer token here
          url->Append(S"&type=heavy");
          url->AppendFormat(S"&AsinSearch={0}", isbn);
          url->Append(S"&f=xml");
    
          Console::WriteLine(S"Searching Amazon for {0}\n", isbn);
          XmlTextReader* reader = new XmlTextReader(url->ToString());
    
          // display some sample data
          while (reader->Read())
          {
            if (XmlNodeType::Element == reader->NodeType)
            {
              if (0 == String::Compare(reader->Name, S"Authors"))
                 Console::WriteLine(S"Authors:");
              else if (0 == String::Compare(reader->Name, S"Author"))
              {
                 Console::Write(S"\t");
                 Console::WriteLine(reader->ReadString());
              }
              else if (0 == String::Compare(reader->Name, S"Manufacturer"))
                 Console::WriteLine(reader->ReadString());
              else if (0 == String::Compare(reader->Name, S"ProductName"))
                Console::WriteLine(reader->ReadString());
            }
          }
        }
        catch(Exception* e)
        {
          Console::WriteLine(e->Message);
        }
      }
    };
    
  5. Finally, to call this class' lone static function, you simply pass it the desired ISBN as follows:
  6. AmazonClient::FindISBN(S"032117352X");

    Note that the code first builds a string containing the Amazon Web Service URL. It then passes that string to the XmlTextReader object, which calls the Web service, parses the returned data, and fills the XmlTextReader object. From there, it uses a simple while loop where each node read from the XmlTextReader object is checked.

    Even if you're new to XML programming, you can see that 1) a node is identified as an element by virtue of its node type being set to XmlNodeType::Element. The name of that element can then be retrieved via the Name property. If the element is one in which you wish to retrieve its value, you then call the XmlTextReader::ReadString method.

    (For those of you looking for more information on using the .NET XML class from MFC, I have an entire chapter devoted to that in my book, Extending MFC Applications with the .NET Framework.

It's Not So Hard After All

Although the example of calling a Web service that this article provided is simple and non-typed, I hope it did accomplish its main objective: illustrating how easy the .NET XmlTextReader class can make calling a Web service. Also note that while I used the Amazon Web Service as an example, what you read here will apply to virtually any Web service.



About the Author

Tom Archer - MSFT

I am a Program Manager and Content Strategist for the Microsoft MSDN Online team managing the Windows Vista and Visual C++ developer centers. Before being employed at Microsoft, I was awarded MVP status for the Visual C++ product. A 20+ year veteran of programming with various languages - C++, C, Assembler, RPG III/400, PL/I, etc. - I've also written many technical books (Inside C#, Extending MFC Applications with the .NET Framework, Visual C++.NET Bible, etc.) and 100+ online articles.

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds