【记录】尝试使用AWS SDK for .NET去实现C#版本的ItemLookup

【背景】

折腾:

【基本解决】用C#实现AWS的API中的ItemLookup

期间,已经下载并安装了AWS SDK for .NET。

接下来,尝试使用此Amazon的库,去实现对应的ItemLookup。

【折腾过程】

1.参考:

Starting a New Project

去在VS1020中新建一个AWS Console Project:

aws console project

2.然后输入Access Key ID等信息:

aws access credentials key id

3.生成的代码如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

using Amazon;
using Amazon.EC2;
using Amazon.EC2.Model;
using Amazon.SimpleDB;
using Amazon.SimpleDB.Model;
using Amazon.S3;
using Amazon.S3.Model;

namespace AwsConsoleApp1
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.Write(GetServiceOutput());
            Console.Read();
        }

        public static string GetServiceOutput()
        {
            StringBuilder sb = new StringBuilder(1024);
            using (StringWriter sr = new StringWriter(sb))
            {
                sr.WriteLine("===========================================");
                sr.WriteLine("Welcome to the AWS .NET SDK!");
                sr.WriteLine("===========================================");

                // Print the number of Amazon EC2 instances.
                AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client(RegionEndpoint.USWest2);
                DescribeInstancesRequest ec2Request = new DescribeInstancesRequest();

                try
                {
                    DescribeInstancesResponse ec2Response = ec2.DescribeInstances(ec2Request);
                    int numInstances = 0;
                    numInstances = ec2Response.DescribeInstancesResult.Reservation.Count;
                    sr.WriteLine("You have " + numInstances + " Amazon EC2 instance(s) running in the US-East (Northern Virginia) region.");

                }
                catch (AmazonEC2Exception ex)
                {
                    if (ex.ErrorCode != null && ex.ErrorCode.Equals("AuthFailure"))
                    {
                        sr.WriteLine("The account you are using is not signed up for Amazon EC2.");
                        sr.WriteLine("You can sign up for Amazon EC2 at http://aws.amazon.com/ec2");
                    }
                    else
                    {
                        sr.WriteLine("Caught Exception: " + ex.Message);
                        sr.WriteLine("Response Status Code: " + ex.StatusCode);
                        sr.WriteLine("Error Code: " + ex.ErrorCode);
                        sr.WriteLine("Error Type: " + ex.ErrorType);
                        sr.WriteLine("Request ID: " + ex.RequestId);
                        sr.WriteLine("XML: " + ex.XML);
                    }
                }
                sr.WriteLine();

                // Print the number of Amazon SimpleDB domains.
                AmazonSimpleDB sdb = AWSClientFactory.CreateAmazonSimpleDBClient(RegionEndpoint.USWest2);
                ListDomainsRequest sdbRequest = new ListDomainsRequest();

                try
                {
                    ListDomainsResponse sdbResponse = sdb.ListDomains(sdbRequest);

                    if (sdbResponse.IsSetListDomainsResult())
                    {
                        int numDomains = 0;
                        numDomains = sdbResponse.ListDomainsResult.DomainName.Count;
                        sr.WriteLine("You have " + numDomains + " Amazon SimpleDB domain(s) in the US-East (Northern Virginia) region.");
                    }
                }
                catch (AmazonSimpleDBException ex)
                {
                    if (ex.ErrorCode != null && ex.ErrorCode.Equals("AuthFailure"))
                    {
                        sr.WriteLine("The account you are using is not signed up for Amazon SimpleDB.");
                        sr.WriteLine("You can sign up for Amazon SimpleDB at http://aws.amazon.com/simpledb");
                    }
                    else
                    {
                        sr.WriteLine("Caught Exception: " + ex.Message);
                        sr.WriteLine("Response Status Code: " + ex.StatusCode);
                        sr.WriteLine("Error Code: " + ex.ErrorCode);
                        sr.WriteLine("Error Type: " + ex.ErrorType);
                        sr.WriteLine("Request ID: " + ex.RequestId);
                        sr.WriteLine("XML: " + ex.XML);
                    }
                }
                sr.WriteLine();

                // Print the number of Amazon S3 Buckets.
                AmazonS3 s3Client = AWSClientFactory.CreateAmazonS3Client(RegionEndpoint.USWest2);

                try
                {
                    ListBucketsResponse response = s3Client.ListBuckets();
                    int numBuckets = 0;
                    if (response.Buckets != null &&
                        response.Buckets.Count > 0)
                    {
                        numBuckets = response.Buckets.Count;
                    }
                    sr.WriteLine("You have " + numBuckets + " Amazon S3 bucket(s) in the US Standard region.");
                }
                catch (AmazonS3Exception ex)
                {
                    if (ex.ErrorCode != null && (ex.ErrorCode.Equals("InvalidAccessKeyId") ||
                        ex.ErrorCode.Equals("InvalidSecurity")))
                    {
                        sr.WriteLine("Please check the provided AWS Credentials.");
                        sr.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
                    }
                    else
                    {
                        sr.WriteLine("Caught Exception: " + ex.Message);
                        sr.WriteLine("Response Status Code: " + ex.StatusCode);
                        sr.WriteLine("Error Code: " + ex.ErrorCode);
                        sr.WriteLine("Request ID: " + ex.RequestId);
                        sr.WriteLine("XML: " + ex.XML);
                    }
                }
                sr.WriteLine("Press any key to continue...");
            }
            return sb.ToString();
        }
    }
}

调试运行结果是,3个示例,都出错:

===========================================

Welcome to the AWS .NET SDK!

===========================================

Caught Exception: You are not subscribed to this service. Please go to http://aws.amazon.com to subscribe.

Response Status Code: Unauthorized

Error Code: OptInRequired

Error Type: Unknown

Request ID: bae99725-79b4-4850-946f-b43a96ff1d67

XML: <?xml version="1.0" encoding="UTF-8"?>

<Response><Errors><Error><Code>OptInRequired</Code><Message>You are not subscribed to this service. Please go to http://aws.amazon.com to subscribe.</Message></Error></Errors><RequestID>bae99725-79b4-

4850-946f-b43a96ff1d67</RequestID></Response>

Caught Exception: Subscription check failed. Please sign up for Amazon SimpleDB service.

Response Status Code: Unauthorized

Error Code: SubscriptionCheckFailed

Error Type: Unknown

Request ID: 7596a4d6-3305-cc36-2652-76c824b3a5fe

XML: <?xml version="1.0"?>

<Response><Errors><Error><Code>SubscriptionCheckFailed</Code><Message>Subscription check failed. Please sign up for Amazon SimpleDB service.</Message></Error></Errors><RequestID>7596a4d6-3305-cc36-265

2-76c824b3a5fe</RequestID></Response>

Caught Exception: Your account is not signed up for the S3 service. You must sign up before you can use S3.

Response Status Code: Forbidden

Error Code: NotSignedUp

Request ID: B3C78A53611A5924

XML: <?xml version="1.0" encoding="UTF-8"?>

<Error><Code>NotSignedUp</Code><Message>Your account is not signed up for the S3 service. You must sign up before you can use S3.</Message><RequestId>B3C78A53611A5924</RequestId><HostId>t1vuXxSv2r180q

bV/OnaDmv3XzVV/4DK2NyJD/4wCPg1MOLzuWT3xR99Lb16EcHB</HostId></Error>

Press any key to continue…

因为我自己没注册相关服务。

 

4.想办法,参考别人代码,去试试ItemLookup,但是结果找不到AWSECommerceService和ItemLookup:

【已解决】已装AWS SDK for .NET,但是C#中找不到AWSECommerceService和ItemLookup

 

5.另外,先参考了:

C# search amazon example with new amazon service

某人回复说到,2011年11月后,好像对于所有的request,都要加上一个Associate Tag的,否则貌似返回都是null和错误。

 

6.然后就可以继续去写代码了。

7.又参考:

http://flyingpies.wordpress.com/2009/08/13/signing-amazon-product-advertising-api-cwcf-part-2/

下载了:

AmazonProductAdvtApiWcfSample.zip, 324KB, 8/1/2009

然后参考其项目,把Amazon.ECS.Addons中的三个cs文件:

AmazonHeader.cs

AmazonSigningEndpointBehavior.cs

AmazonSigningMessageInspector.cs

都添加进来了,然后才可以找到AmazonSigningEndpointBehavior

8.期间代码调试无法正常获得response,后来参考:

ItemLookup returns null

找到:

Product Advertising API Change Details

得知:

Associate Tag Parameter: Every request made to the API should include a valid Associate Tag. Any request that does not contain a valid Associate Tag will be rejected with an appropriate error message. For details on the Associate Tag parameter, please refer to our Developer guide.

即,必须包括Associate Tag才可以的。

所以,去:

https://affiliate-program.amazon.com/

注册一个。

9.后来,用代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using AwsWinformApiDemo.AWSECommerceService;
using System.ServiceModel;
using Async;

namespace AwsWinformApiDemo
{
    public partial class AmazonAws : Form
    {
        private const string accessKeyId = "xxx";
        private const string secretKey = "yyy";
        private const string associateTag = "zzz";

        public AmazonAws()
        {
            InitializeComponent();
        }

        private void AmazonAws_Load(object sender, EventArgs e)
        {
        //    //AWSECommerceServicePortTypeClient amazonClient = new AWSECommerceServicePortTypeClient();

            //http://stackoverflow.com/questions/8142909/c-sharp-search-amazon-example-with-new-amazon-service
            BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
            binding.MaxReceivedMessageSize = int.MaxValue;
            AWSECommerceServicePortTypeClient amazonClient = new AWSECommerceServicePortTypeClient(
                        binding,
                        new EndpointAddress("https://webservices.amazon.com/onca/soap?Service=AWSECommerceService"));
            // add authentication to the ECS client
            amazonClient.ChannelFactory.Endpoint.Behaviors.Add(new AmazonSigningEndpointBehavior(accessKeyId, secretKey));

            ItemLookup lookup = new ItemLookup();
            ItemLookupRequest lookupReq = new ItemLookupRequest();
            ItemLookupResponse lookupResp = new ItemLookupResponse();

            lookup.AWSAccessKeyId = secretKey;
            lookup.AssociateTag = associateTag;

            //http://docs.aws.amazon.com/AWSECommerceService/2011-08-01/DG/ItemLookup.html
            lookupReq.IdType = ItemLookupRequestIdType.ASIN; //Amazon Standard Identification Number

            //http://www.amazon.com/gp/product/B0083PWAPW
            lookupReq.ItemId = new string[] { "B0083PWAPW" };

            //http://docs.aws.amazon.com/AWSECommerceService/latest/DG/OfferSummaries.html
            lookupReq.ResponseGroup = new string[] { "OfferSummary" };

            //http://stackoverflow.com/questions/6460936/amazon-product-advertising-api-item-lookup-request-working-example
            lookupReq.SearchIndex = "All";

            lookup.Request = new ItemLookupRequest[] { lookupReq };

            lookupResp = amazonClient.ItemLookup(lookup);
            MessageBox.Show(lookupResp.ToString());

            ////https://forums.aws.amazon.com/message.jspa?messageID=318807
            //BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
            //binding.MaxReceivedMessageSize = int.MaxValue;
            //binding.ReaderQuotas.MaxStringContentLength = int.MaxValue;

            //AWSECommerceServicePortTypeClient client = new AWSECommerceServicePortTypeClient(
            //                binding,
            //                new EndpointAddress("https://webservices.amazon.com/onca/soap?Service=AWSECommerceService"));
            //                //new EndpointAddress("https://aws.amazonaws.com/onca/soap"));

            //client.ChannelFactory.Endpoint.Behaviors.Add(new AmazonSigningEndpointBehavior(accessKeyId, secretKey));

            //ItemLookupRequest[] request = new ItemLookupRequest[1];
            //request[0] = new ItemLookupRequest();
            //request[0].ItemId = new string[] { "0762744499" };

            //ItemLookup itemLookup = new ItemLookup();
            //itemLookup.Request = request;
            //itemLookup.AWSAccessKeyId = accessKeyId;
            //itemLookup.AssociateTag = associateTag;

            //ItemLookupResponse response = new ItemLookupResponse();
            //response = client.ItemLookup(itemLookup);
            //MessageBox.Show(response.ToString());
        }
    }
}

还是不行。

不仅仅是无法获得lookupResp,而且是,对于这一行的调试,都无法执行到。好像是由于异步执行的原因。

10.参考:

Amazon API, Product Advertising API , ItemSearch, C#

->

search items with .NET : ItemSearchResponse always null

下载到:

Simple.Amazon.ECS.zip

结果发现只有两个文件:AWSECommerceService.wsdl和Reference.cs

不是完整的项目,没啥参考价值。

因为这两个内容,之前都已经通过

http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl

添加进来了,且都已经是最新的了。

11.随便试试,去配置一下已加的那个服务:

右击AWSECommerceService->Configure Service Reference:

generate asynchronous operations

然后再去运行代码试试,看看能否debug到。

结果问题依旧。

 

【总结】

暂时是:

通过AWS的SDK,搞不定;

通过那个AWSECommerceServicePortTypeClient,也搞不定;

所以,放弃此方向的折腾。


后续折腾参见:

【基本解决】用C#实现AWS的API中的ItemLookup



发表评论

电子邮件地址不会被公开。 必填项已用*标注

无觅相关文章插件,快速提升流量