Using the Amazon Web Service from ASP.NET

xiaoxiao2021-03-06  118

In this article we will be utilizing the Amazon Web Service (AWS) from an ASP.NET web form. Instead of taking a comprehensive look at the entire API we will concentrate on a single method to retrieve product information. In developing the sample we will Take a look at Abstract Techniques To make the Web service Easier to use.

Our goal in this article is to build a user control which we can place on a web form. The user control will retrieve information about a book and display the information, such as price and availability, with a minimum of effort from the form developer. The Ideal Usage Would Look Similar To The Following:

<% @ Register tagprefix = "uc1" tagname = "Amazon_showbook" src = "Amazon_showbook.ascx"%> ...

ASIN is short for "Amazon Standard Item Number". For books, the ASIN is the same as the ISBN. Every product on amazon.com has as ASIN which you can find on the product's page. The end result should look like the following screen Shot:

Setting up References

For starters, you'll need to download the Amazon.com Web Services Developer's Kit. The kit is free, although you must apply for your own, unique developer token to use in the web service calls, as we will see later. It is important for you to read the terms and conditions before beginning development, as amazon.com has specific rules on how you use the API and display the information, including how frequently you can make calls to the API.

Once the kit and developer token are in hand, you are ready to begin a new web project. Right click the project and select "Add Web Reference". In the dialog box that follows, we will go to the URL for the WSDL describing AWS at http://soap.amazon.com/schemas3/AmazonWebServices.wsdl. Before clicking the Add Reference button you might want to give the web reference a different name (in the lower right textbox), in this example we will use AmazonWS. After clicking the Add Reference button you'll have a proxy class in your project for the web service. Calling methods on the proxy class will result in a network hop across the Internet to amazon's servers, where the information you request will be located and sent Back to Your Application. Let's Take a Look At A Simple Example.Search Request, First Attempt

The Following Code Snippet Demonstrateed A Quick and Dirty Call To Amazon. We will discuss Some of the Basics About this call before moving on to improve the code.

Amazonws.asinRequest asinRequest = New Amazonws.asinRequest ();

AsinRequest.asin = "1904811000";

AsinRequest.devtag = "1234567890aaa";

AsinRequest.Type = "Heavy";

AsinRequest.tag = "WebServices-20";

Amazonws.amazonsearch = new amazonws.amazonsearchService ();

Amazonws.Productinfo AWSINFO;

AWSINFO = Amazonsearch.asinsearchRequest (AsinRequest);

PriceLabel.Text = awsinfo.details [0] .ourprice;

Before we call the web service we need to setup an object with the information the server needs to fulfill our request. The AsinRequest class has a number of fields to populate when searching for a specific ASIN. In the above code we are populating the four required FIELDS. The Asin in this Example Is The Ins for a book. The devTag is The developer token given to us by amazon. The Type Field Can Be set to "Lite" or "Heavy", Depending on The Amount of Detail you want server to return. Finally, the tag field holds your Amazon associate's identifier. If you are not an Amazon associate you can pass a generic associate ID of "webservices-20" .With the AsinRequest object populated we can make a call to the service using the AmazonSearchService class. When successful the call will give us back a ProductInfo object, which contains quite a bit of information about the book. In the example above we are pulling out the price for the book.

There are just a couple problems with the code from an architectural viewpoint. The values ​​are hardcoded, and the developer needs to know a good bit of detail to dig out the required information from the ProductInfo object which we can simplify. Now that we understand better How this all Works, Let's try to improve.

Search Request: Second Attempt

Our first step will be to write our own class to hold product information. By doing so anyone who is going to use our code will not need to learn the Amazon classes, but instead can use a simpler class tailored for our application needs.

Public Class ProductInfo

{

Public String Title = "unknown";

Public String Url = string.empty;

Public String price = "0.00";

Public String Availability = "unavailable";

Public String REVIEWS = "0"; public string authors = string.empty;

}

Not a particularly interesting class, but it will be easy to use and mildly abstracts away the Amazon structure from the rest of the application. Next, we will write a service helper class. The service helper class will do all the hard work of calling the Web Service and Organizing The Results Into Our Own Productinfo Object. The First Method We Write Is Shown Below.

Private Static ProductInfo getProductinfofromaws (String Asin)

{

Amazonws.asinRequest asinRequest = New Amazonws.asinRequest ();

AsinRequest.asin = asin;

AsinRequest.devtag = awsconfig.devtag;

AsinRequest.Type = awsconfig.type_heavy;

AsinRequest.tag = awsconfig.tag;

Amazonws.amazonsearch = new amazonws.amazonsearchService ();

Amazonws.Productinfo AWSINFO;

AWSINFO = Amazonsearch.asinsearchRequest (AsinRequest);

ProductInfo Info = New Productinfo ();

IF (AWSINFO! = NULL)

{

IF (awsinfo.details.length> 0 && awsinfo.details [0]! = null)

{

IF (awsinfo.details [0] .productname! = null)

Info.title = awsinfo.details [0] .productname;

IF (awsinfo.details [0] .authors.length> 0)

Info.join (",", awsinfo.details [0] .authors;

IF (awsinfo.details [0] .availability! = NULL)

Info.availability = awsinfo.details [0] .availability;

IF (awsinfo.details [0] .ourprice! = null)

INFO.PRICE = awsinfo.details [0] .ourprice;

IF (awsinfo.details [0] .reviews! = null&&

AWSINFO.DETAILS [0] .reviews.totalcustomerreviews! = NULL)

INFO.REVIEWS = awsinfo.details [0] .reviews.totalcustomerreview;

IF (awsinfo.details [0] .url! = null)

INFO.URL = awsinfo.details [0] .url;

}

Return INFO;

}

Notice we have pushed all of the values ​​we hard-coded in the first step (devtag, type) into another class with the name of AWSConfig. AWSConfig can pull these items from the web.config file using the ConfigurationSettings class of .NET, or From A Database or Another XML File. We Now Have Slightly More Flexible and Robust Code.

After the web service call, the method carefully extracts the information we need from the Amazon ProductInfo object and populates our own ProductInfo object. The Amazon web service will return null values ​​for data items which do not exist, so we need to carefully check for null Before overwriting the default value in out.

NOTICE WE DECLARED The Method As Private. The Application Code Will NOT CALL THIS Method Directly. INSTEAD, WE Are Going to Add Some Additional Methods To Enable Caching of The Information.

Public Static ProductInfo getProductInfo (String Asin)

{

ProductInfo info = null;

INFO = GetProductinfofromCache (asin);

IF (info == null)

{

INFO = GetProductinfofromaws (asin);

CacheProductinfo (Asin, Info);

}

Return INFO;

}

Static ProductInfo getProductInfofromcache (String Asin)

{

String Key = formatcachekey (asin);

ProductInfo info = null;

INFO = httpruntime.cache [key] as productinfo;

Return INFO;

}

Static Void CacheProductinfo (String Asin, ProductInfo Info)

{

String Key = formatcachekey (asin);

HTTPRUNTIME.CACHE.INSERT

Key,

INFO,

NULL,

Datetime.now.addhours (12),

Timespan.zero

);

}

Static string formatcachekey (String Asin)

{

Return "AWS_PRODUCT" ASIN

}

Now we will cache the results for 12 hours and avoid the overhead of the web service call. (Reminder: make sure to read the terms and conditions documents for AWS closely as Amazon has stipulations on how long you can cache specific pieces of information). The public method GetProductInfo will first check to see if there is a result in the cache before calling GetProductInfoFromAWS. Once it has a result it will cache the result using a key that includes the ASIN value to ensure the key is unique.Assuming we designed our user control with simple Label and Hyperlink Webform controls, the Page_Load event handler for the control should look relatively simple. We just need to give the service helper class an ASIN and wait for the results to return.

Private Void Page_Load (Object Sender, System.EventArgs E)

{

IF (! ispostback)

{

Amazon.Productinfo Info;

INFO = Amazon.serviceHelper.getProductInfo (Asin);

TitleLink.navigateURL = Info.UR1;

TitleLink.Text = info.title;

Authorlabel.text = info.authors;

PriceLabel.Text = Info.price;

AvailabilityLabel.Text = Info.availabILABILTY;

REVIEWLABEL.TEXT = INFO.REVIEWS;

}

}

Public String Asin

{

Get {return;

Set {asin = value;}

}

String asin = NULL;

Notice we have also given the user control a public property ASIN. This allows us to specify the ASIN to lookup inside of the control tag in the ASPX, as we demonstrated at the beginning of the article. We could also programmatically assign the ASIN as the RESULT OF A User Request.

Now what is missing? We have made the Amazon product search easy to use for our web form developer. We have also made it clear through the naming convention (Amazon.ServiceHelper.GetProductInfo) that the code is making a web service call. The developer should realize this code could fail for any number of reason even though the parameters are all correctly initialized. Network connectivity could be lost, or the service could be temporarily unavailable.Dealing with the increased risk of exceptions is an important aspect of using web services. We Could try A Simplistict Error Handler IN Our User Control Like The One Shown Below:

Try

{

INFO = Amazon.serviceHelper.getProductInfo (Asin);

}

Catch (Exception)

{

THIS.Visible = FALSE;

}

This technique is the "head in the sand approach". We simply do not display the user control at all if an exception occurs. If this is acceptable behavior for your application than the world is good, but think of what else is happening behind the scenes. for every user who hits the page with this user control the application will attempt a web service call and must wait to timeout if the network is down. All this waiting for a large number of users can spell disaster for performance. Let's try To make a few more changes to improve the situation.

Search Request: third Attempt

Our third attempt adds some additional code to the getProductinfo method. The last ity is shown below.

Public Static ProductInfo getProductInfo (String Asin)

{

ProductInfo info = null;

INFO = GetProductinfofromCache (asin);

IF (info == null)

{

Try

{

INFO = GetProductinfofromaws (asin);

}

Catch (Exception)

{

// log the error ...

}

IF (info == null)

{

Info = new productinfo (); cacheproductinfo

Asin, info, datetime.now awsconfig.cachetime_on_error

);

}

Else

{

CacheProductinfo (

Asin, info, datetime.now awsconfig.cachetime_on_success

);

}

}

Return INFO;

}

Static Void CacheProductinfo (String Asin, ProductInfo Info, DateTime Expiration)

{

String Key = formatcachekey (asin);

HTTPRUNTIME.CACHE.INSERT

Key,

INFO,

NULL,

EXPIRATION,

Timespan.zero

);

}

Notice we have added a try catch block now. What you do when an exception occurs will depend on the needs of your application. Perhaps you'll need to log the failure to a database, or to the event log, or send an email to An administrator.

We've also added two new configuration items to configure the cache. When an error occurs we will create a new ProductInfo object and cache the object for a short amount of time (say, 5 minutes). Hopefully, in 5 minutes the service will .

Summary

In this article we've designed and built an interface to the Amazon Web Service. Hopefully you'll find this article helpful as an introduction to AWS as well as pick up some design guidelines to use in your own web service client application. In future .

转载请注明原文地址:https://www.9cbs.com/read-127009.html

New Post(0)