コード例 #1
0
        private AmazonWishlistItems ConvertAmazonWishlist(string content)
        {
            AmazonWishlistItems result = new AmazonWishlistItems();

            using (StringReader sr = new StringReader(content))
            {
                XmlSerializer ser = new XmlSerializer(typeof(ItemLookupResponse));

                ItemLookupResponse data = (ItemLookupResponse)ser.Deserialize(sr);

                if (data == null || data.Items == null || data.Items.Length == 0)
                {
                    return(result);
                }

                if (asinIds.Length > 0)
                {
                    result.Ids = asinIds;
                }

                foreach (Item item in data.Items)
                {
                    result.Items.Add(service.ConvertAmazonProduct(item));
                }
            }

            return(result);
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: rafysanchez/TesteViaVarejo
        public string getCurrentPrice(string itemID)
        {
            const string accessKeyId = "AKIAINHOZEYXDKHXMYUQ";
            const string secretKey   = "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";

            // create a WCF Amazon ECS client
            AWSECommerceServicePortTypeClient client = new AWSECommerceServicePortTypeClient(
                new BasicHttpBinding(BasicHttpSecurityMode.Transport),
                new EndpointAddress("https://webservices.amazon.com/onca/soap?Service=AWSECommerceService"));

            // add authentication to the ECS client
            client.ChannelFactory.Endpoint.Behaviors.Add(new AmazonSigningEndpointBehavior(accessKeyId, secretKey));

            // prepare an ItemSearch request
            ItemLookupRequest request = new ItemLookupRequest();

            request.ItemId        = new string[] { itemID };
            request.ResponseGroup = new string[] { "OfferSummary" };
            request.MerchantId    = "Amazon";

            ItemLookup itemSearch = new ItemLookup();

            itemSearch.Request        = new ItemLookupRequest[] { request };
            itemSearch.AWSAccessKeyId = accessKeyId;
            itemSearch.AssociateTag   = "rgreuel-20";

            // issue the ItemSearch request
            ItemLookupResponse response = client.ItemLookup(itemSearch);

            // write out the results
            Item returnedItem = response.Items[0].Item.First();

            return((returnedItem.OfferSummary.LowestNewPrice.FormattedPrice).Substring(1, returnedItem.OfferSummary.LowestNewPrice.FormattedPrice.Length - 1));
        }
コード例 #3
0
        private static Item[] DoAmazonItemLookup(string[] ASINs)
        {
            ItemLookupResponse response = null;

            AWSECommerceServicePortTypeClient ecs = GetClient();
            ItemLookupRequest request             = GetLookupRequest();

            request.ItemId = ASINs;

            ItemLookup lookup = new ItemLookup();

            lookup.AssociateTag   = _ASSOCIATE_TAG;
            lookup.AWSAccessKeyId = _ACCESS_KEY_ID;

            // Set the request on the search wrapper
            lookup.Request = new ItemLookupRequest[] { request };

            try
            {
                //Send the request and store the response
                response = ecs.ItemLookup(lookup);
            }
            catch (NullReferenceException e)
            {
                Debug.WriteLine(e.ToString());
            }

            if (response == null)
            {
                throw new Exception("Request did not return a response. Error using Amazon API");
            }

            return(response.Items[0].Item);
        }
コード例 #4
0
    private string getImageURL(string asin)
    {
        const string accessKeyId = "AKIAINHOZEYXDKHXMYUQ";
        const string secretKey   = "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";

        // create a WCF Amazon ECS client
        AWSECommerceServicePortTypeClient client = new AWSECommerceServicePortTypeClient(
            new BasicHttpBinding(BasicHttpSecurityMode.Transport),
            new EndpointAddress("https://webservices.amazon.com/onca/soap?Service=AWSECommerceService"));

        // add authentication to the ECS client
        client.ChannelFactory.Endpoint.Behaviors.Add(new AmazonSigningEndpointBehavior(accessKeyId, secretKey));

        // prepare an ItemSearch request
        ItemLookupRequest request = new ItemLookupRequest();

        request.ItemId        = new string[] { asin };
        request.ResponseGroup = new string[] { "Images" };
        request.MerchantId    = "Amazon";

        ItemLookup itemSearch = new ItemLookup();

        itemSearch.Request        = new ItemLookupRequest[] { request };
        itemSearch.AWSAccessKeyId = accessKeyId;
        itemSearch.AssociateTag   = "rgreuel-20";

        // issue the ItemSearch request
        ItemLookupResponse response = client.ItemLookup(itemSearch);

        Item returnedItem = response.Items[0].Item.First();

        return("<img src=\"" + returnedItem.MediumImage.URL + "\"/>");
    }
コード例 #5
0
ファイル: Program.cs プロジェクト: rafysanchez/TesteViaVarejo
        public string ReviewsFrame()
        {
            BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);

            binding.MaxReceivedMessageSize = int.MaxValue;
            binding.MaxBufferSize          = 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(ConfigurationManager.AppSettings["accessKeyId"], ConfigurationManager.AppSettings["secretKey"]));

            ItemLookupRequest request = new ItemLookupRequest();

            request.ItemId        = this.ItemIds;
            request.IdType        = ItemLookupRequestIdType.ASIN;
            request.ResponseGroup = new string[] { "Reviews" };

            ItemLookup itemLookup = new ItemLookup();

            itemLookup.Request        = new ItemLookupRequest[] { request };
            itemLookup.AWSAccessKeyId = ConfigurationManager.AppSettings["accessKeyId"];
            itemLookup.AssociateTag   = ConfigurationManager.AppSettings["associateTag"];

            ItemLookupResponse response = amazonClient.ItemLookup(itemLookup);
            string             frameUrl = response.Items[0].Item[0].CustomerReviews.IFrameURL;

            return(frameUrl);
        }
コード例 #6
0
        public ItemLookupResponse Lookup(ItemLookupRequest lookupRequest)
        {
            ItemLookup          lookup   = CreateItemLookup(lookupRequest);
            AWSECommerceService api      = GetService();
            ItemLookupResponse  response = api.ItemLookup(lookup);

            return(response);
        }
        private string SerializeSearchObject(ItemLookupResponse toSerialize)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());

            using (StringWriter textWriter = new StringWriter())
            {
                xmlSerializer.Serialize(textWriter, toSerialize);
                return(textWriter.ToString());
            }
        }
コード例 #8
0
        public ItemLookupResponse Lookup(params string[] asins)
        {
            ItemLookupRequest lookupRequest = CreateItemLookupRequest();

            lookupRequest.ItemId = asins;

            ItemLookupResponse response = Lookup(lookupRequest);

            return(response);
        }
コード例 #9
0
        public static ItemLookupResponse GetItemDetails(string itemId, string region)
        {
            ItemLookupResponse itemResponse = null;

            string response = AmazonProductAPIContext.Instance.GetDetailsForItemId(itemId, region.ToString());

            itemResponse = GetObjectFromResponse <ItemLookupResponse>(response);

            return(itemResponse);
        }
コード例 #10
0
        static void Main(string[] args)
        {
            // If you are using a debugging proxy like Fiddler to capture SOAP
            // envelopes, and you get SSL Certificate warnings, uncomment the
            // following line:
            // ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

            // Create an ItemLookup request, with ResponseGroup "Small"
            // and using the item ID provided above.
            ItemLookup itemLookup = new ItemLookup();

            itemLookup.AWSAccessKeyId = MY_AWS_ID;

            ItemLookupRequest itemLookupRequest = new ItemLookupRequest();

            itemLookupRequest.ItemId        = new String[] { ITEM_ID };
            itemLookupRequest.ResponseGroup = new String[] { "Small", "AlternateVersions" };
            itemLookup.Request = new ItemLookupRequest[] { itemLookupRequest };

            // create an instance of the serivce
            AWSECommerceService api = new AWSECommerceService();

            // set the destination
            api.Destination = new Uri(DESTINATION);

            // apply the security policy, which will add the require security elements to the
            // outgoing SOAP header
            AmazonHmacAssertion amazonHmacAssertion = new AmazonHmacAssertion(MY_AWS_ID, MY_AWS_SECRET);

            api.SetPolicy(amazonHmacAssertion.Policy());

            // make the call and print the title if it succeeds
            try
            {
                ItemLookupResponse itemLookupResponse = api.ItemLookup(itemLookup);
                Item item = itemLookupResponse.Items[0].Item[0];
                System.Console.WriteLine(item.ItemAttributes.Title);
            }
            catch (Exception e)
            {
                System.Console.Error.WriteLine(e);
            }

            // we're done
            System.Console.WriteLine("HMAC sample finished. Hit Enter to terminate.");
            System.Console.ReadLine();
        }
コード例 #11
0
        public GetProductAPIContract GetProductDetails(GetProductAPIArgs args, HttpRequestMessage request)
        {
            DynamoDBTracer.Tracer.Write(string.Format("GetProductDetails called. Args: {0}", args), "Verbose");
            this.CheckAndUpdateDoSLimits(request, "GetProductCall");
            ItemLookupResponse itemResponse = AmazonProductHelper.GetItemDetails(args.ProductASIN, args.ProductRegion.ToString());

            var item = itemResponse.Items.FirstOrDefault().Item.FirstOrDefault();

            GetProductAPIContract apiContract = new GetProductAPIContract
            {
                ProductASIN   = item.ASIN,
                ProductName   = item.ItemAttributes.Title,
                ProductRegion = args.ProductRegion
            };

            DynamoDBTracer.Tracer.Write(string.Format("GetProductDetails succeeded. Args: {0}", args), "Verbose");
            return(apiContract);
        }
        static void Main(string[] args)
        {
            // If you are using a debugging proxy like Fiddler to capture SOAP
            // envelopes, and you get SSL Certificate warnings, uncomment the
            // following line:
            // ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

            // create an ItemLookup request:
            ItemLookup itemLookup = new ItemLookup();

            itemLookup.AWSAccessKeyId = MY_AWS_ACCESS_KEY_ID;

            ItemLookupRequest itemLookupRequest = new ItemLookupRequest();

            itemLookupRequest.ItemId        = new String[] { "0545010225" };
            itemLookupRequest.ResponseGroup = new String[] { "Small", "AlternateVersions" };
            itemLookup.Request = new ItemLookupRequest[] { itemLookupRequest };

            // create service instance and set destination
            AWSECommerceService api = new AWSECommerceService();

            api.Destination = new Uri(DESTINATION);

            // set the policy so that all outgoing requests are signed with the certificate
            AmazonX509Assertion amazonX509Assertion = new AmazonX509Assertion(MY_AWS_CERT_NAME);

            api.SetPolicy(amazonX509Assertion.Policy());

            // fetch the response.
            ItemLookupResponse itemLookupResponse = api.ItemLookup(itemLookup);

            Item item = null;

            try {
                item = itemLookupResponse.Items[0].Item[0];
                System.Console.WriteLine(item.ItemAttributes.Title);
            } catch (Exception e) {
                System.Console.Error.WriteLine(e);
            }

            System.Console.WriteLine("X.509 sample finished. Hit Enter to terminate.");
            System.Console.ReadLine();
        }
コード例 #13
0
        /// <inheritdoc />
        public async Task <WalmartResult <ItemLookupResponse> > ItemLookupAsync(string itemIDs, string[] upcs)
        {
            //conditions
            Condition.Requires(itemIDs).IsNotNull();
            Condition.Requires(itemIDs.Count()).IsGreaterThan(0);

            //create the payload to pass
            var payload = new ItemLookupRequest(this.apiKey, this.lsPublisherId, itemIDs);

            //serialize object
            var keyValueContent = payload.ToKeyValue();

            //encode as url content
            var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);

            //create the URI
            string uri = WalmartInformation.ItemsEndpoint + "?" + await formUrlEncodedContent.ReadAsStringAsync();

            //post it and get the response
            HttpResponseMessage response = await this.httpClient.GetAsync(uri);//.PostAsync(WalmartInformation.ItemsEndpoint, content);

            //read the string
            string responseJson = await response.Content.ReadAsStringAsync();

            //create the result
            WalmartResult <ItemLookupResponse> result = new WalmartResult <ItemLookupResponse>(responseJson);

            //is it ok
            if (response.StatusCode == HttpStatusCode.OK)
            {
                ItemLookupResponse itemLookupResponse = JsonConvert.DeserializeObject <ItemLookupResponse>(responseJson);
                result.Value = itemLookupResponse;
            }

            //parse the exception
            result.Exception = await this.ParseException(response, responseJson);

            //return
            return(result);
        }
コード例 #14
0
ファイル: HttpBoatsClient.cs プロジェクト: usaf-cloud/StrayG
        /// <inheritdoc />
        public async Task <BoatsResult <ItemLookupResponse> > ItemLookupAsync(string itemID)
        {
            //conditions
            Condition.Ensures(itemID).IsNotNullOrWhiteSpace();

            //create the payload to pass
            var payload = new ItemLookupRequest(this.consumerKey, itemID);

            //serialize object
            var keyValueContent = payload.ToKeyValue();

            //encode as url content
            var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);

            //create the URI
            string uri = BoatsInformation.InventoryEndpoint + "?" + await formUrlEncodedContent.ReadAsStringAsync();

            //post it and get the response
            HttpResponseMessage response = await this.httpClient.GetAsync(uri);

            //read the string
            string responseJson = await response.Content.ReadAsStringAsync();

            //create the result
            BoatsResult <ItemLookupResponse> result = new BoatsResult <ItemLookupResponse>(responseJson);

            //is it ok
            if (response.StatusCode == HttpStatusCode.OK)
            {
                ItemLookupResponse itemLookupResponse = JsonConvert.DeserializeObject <ItemLookupResponse>(responseJson);
                result.Value = itemLookupResponse;
            }

            //parse the exception
            result.Exception = await this.ParseException(response, responseJson);

            //return
            return(result);
        }
コード例 #15
0
ファイル: Program.cs プロジェクト: EvilOrange/AmazonSearch
 private static void ItemLookupFunc(IEnumerable<Item> items)
 {
     foreach (var item in items)
     {
         var itemlookuprequest = new ItemLookupRequest
         {
             ResponseGroup = new string[] { "Offers" },
             IdType = ItemLookupRequestIdType.ASIN,
             ItemId = new string[] { item.ASIN }
         };
         var itemlookup = new ItemLookup
         {
             Request = new ItemLookupRequest[] {itemlookuprequest},
             AWSAccessKeyId = AwsAccessKeyId,
             AssociateTag = AssociateTag
         };
         if (_itemlookupresponse == null)
         {
             try
             {
                 _itemlookupresponse = AmazonClient.ItemLookup(itemlookup);
             }
             catch (ServerTooBusyException)
             {
                 Items.Clear();
                 ItemSearchFunc();
                 break;
             }
         }
         Items.Add(item.ItemAttributes.Title + " " + _itemlookupresponse.Items[0].Item[0].OfferSummary.LowestUsedPrice.FormattedPrice);
         if (Items.Count != PerPage) continue;
         Display(Items);
         break;
     }
     if (Items.Count >= PerPage) return;
     _itemPage++;
     ItemSearchFunc();
 }
コード例 #16
0
ファイル: AmazonTest.cs プロジェクト: usaf-cloud/StrayG
        public async Task ItemLookup()
        {
            //create a WCF Amazon ECS client
            AWSECommerceServiceClient client = new AWSECommerceServiceClient();

            //prepare an ItemLookupRequest
            ItemLookupRequest request = new ItemLookupRequest()
            {
                IdType = ItemLookupRequestIdType.ASIN,
                ItemId = new string[] { "B002NF0KI2" },
            };

            //prepare an ItemLookup
            ItemLookup itemLookup = new ItemLookup()
            {
                Request        = new ItemLookupRequest[] { request },
                AssociateTag   = AmazonInformation.GetAssociateTag(),
                AWSAccessKeyId = AmazonInformation.GetAccessKeyID(),
            };

            // issue the ItemLookup request
            ItemLookupResponse response = client.ItemLookup(itemLookup);

            if (response.Items[0].Request.Errors.Length > 0)
            {
                foreach (ErrorsError error in response.Items[0].Request.Errors)
                {
                    Debug.WriteLine(error.Message);
                }
            }
            else
            {
                foreach (var item in response.Items[0].Item)
                {
                    Debug.WriteLine(item.ItemAttributes.Title);
                }
            }
        }
コード例 #17
0
        public static Hashtable Parse(string asin, AmazonCountry country, bool isBarcode, AmazonIndex index, string barcodeType)
        {
            Hashtable objResults = new Hashtable();

            try
            {
                ItemLookupRequest request = new ItemLookupRequest();

                if (isBarcode)
                {
                    switch (barcodeType)
                    {
                    case "EAN_8":
                    case "EAN_13":
                        request.IdType = ItemLookupRequestIdType.EAN;
                        break;

                    case "UPC_A":
                    case "UPC_E":
                    case "UPC_EAN_EXTENSION":
                        request.IdType = ItemLookupRequestIdType.UPC;
                        break;

                    default:
                        request.IdType = ItemLookupRequestIdType.EAN;
                        break;
                    }
                    request.SearchIndex = index.ToString();
                }
                else
                {
                    request.IdType = ItemLookupRequestIdType.ASIN;
                }

                request.IdTypeSpecified = true;
                request.ItemId          = new [] { asin };


                request.ResponseGroup = new [] { "EditorialReview",
                                                 "Images", "ItemAttributes", "Large", "Tracks" };

                ItemLookup itemLookup = new ItemLookup();
                itemLookup.AWSAccessKeyId = Aws1;
                itemLookup.AssociateTag   = AssociateTag;
                itemLookup.Request        = new [] { request };

                AWSECommerceServicePortTypeClient client =
                    new AWSECommerceServicePortTypeClient(
                        new BasicHttpBinding("AWSECommerceServiceBinding"),
                        new EndpointAddress(string.Format("https://webservices.amazon.{0}/onca/soap?Service=AWSECommerceService", country.ToString())));

                // add authentication to the ECS client
                client.ChannelFactory.Endpoint.Behaviors.Add(new AmazonSigningEndpointBehavior(Aws1, Aws2));

                ItemLookupResponse response = client.ItemLookup(itemLookup);

                if (response.Items.GetLength(0) > 0)
                {
                    if (response.Items[0].Item != null)
                    {
                        if (response.Items[0].Item.GetLength(0) > 0)
                        {
                            Item item = response.Items[0].Item[0];
                            #region Actor

                            bool isNew;
                            if (item.ItemAttributes.Actor != null)
                            {
                                List <Artist> actors = item.ItemAttributes.Actor.Select(actor => ArtistServices.Get(actor, out isNew)).ToList();
                                objResults.Add("Actors", actors);
                            }
                            #endregion
                            #region Album
                            if (string.IsNullOrWhiteSpace(item.ItemAttributes.Title) == false)
                            {
                                objResults.Add("Album", item.ItemAttributes.Title);
                            }
                            #endregion
                            #region AlternateVersions
                            if (item.AlternateVersions != null)
                            {
                                if (item.AlternateVersions.GetLength(0) > 0)
                                {
                                    objResults.Add("OriginalTitle", item.AlternateVersions[0].Title);
                                }
                            }
                            #endregion
                            #region Artist
                            if (item.ItemAttributes.Artist != null)
                            {
                                if (item.ItemAttributes.Artist.GetLength(0) > 0)
                                {
                                    if (MySettings.FastSearch == false && index == AmazonIndex.Music)
                                    {
                                        Artist artist = ArtistServices.Get(item.ItemAttributes.Artist[0], out isNew);

                                        GetArtistCredits(artist, index, country, 1);
                                        objResults.Add("Artist", artist);
                                    }
                                    else
                                    {
                                        objResults.Add("Artist", ArtistServices.Get(item.ItemAttributes.Artist[0], out isNew));
                                    }
                                }
                            }
                            #endregion
                            #region AspectRatio
                            if (string.IsNullOrWhiteSpace(item.ItemAttributes.AspectRatio) == false)
                            {
                                objResults.Add("DisplayAspectRatio", MovieServices.GetAspectRatio(item.ItemAttributes.AspectRatio));
                            }
                            #endregion
                            #region Author

                            if (item.ItemAttributes.Author != null)
                            {
                                if (item.ItemAttributes.Author.GetLength(0) > 0)
                                {
                                    if (MySettings.FastSearch == false && index == AmazonIndex.Books)
                                    {
                                        //Fix since 2.6.7.0
                                        Artist artist = ArtistServices.Get(item.ItemAttributes.Author[0], out isNew);
                                        GetArtistCredits(artist, index, country, 1);
                                        objResults.Add("Author", artist);
                                    }
                                    else
                                    {
                                        objResults.Add("Author", ArtistServices.Get(item.ItemAttributes.Author[0], out isNew));
                                    }
                                }
                            }
                            #endregion
                            #region Background
                            if (item.ImageSets != null && item.LargeImage != null)
                            {
                                if (item.ImageSets.GetLength(0) > 0 && item.ImageSets[0].LargeImage.URL != item.LargeImage.URL)
                                {
                                    objResults.Add("Background", item.ImageSets[0].LargeImage.URL);
                                }
                                else if (item.ImageSets.GetLength(0) > 1 && item.ImageSets[1].LargeImage.URL != item.LargeImage.URL)
                                {
                                    objResults.Add("Background", item.ImageSets[1].LargeImage.URL);
                                }
                            }
                            #endregion
                            #region BarCode
                            if (string.IsNullOrWhiteSpace(item.ItemAttributes.EAN) == false)
                            {
                                objResults.Add("BarCode", item.ItemAttributes.EAN);
                            }
                            else if (string.IsNullOrWhiteSpace(item.ItemAttributes.UPC) == false)
                            {
                                objResults.Add("BarCode", item.ItemAttributes.UPC);
                            }
                            else if (string.IsNullOrWhiteSpace(item.ASIN) == false)
                            {
                                objResults.Add("BarCode", item.ASIN);
                            }
                            #endregion
                            #region Comments
                            if (item.CustomerReviews != null)
                            {
                                if (item.CustomerReviews.HasReviews == true)
                                {
                                    objResults.Add("Comments", Util.PurgeHtml(GetReview(item.CustomerReviews.IFrameURL, country)));
                                }
                            }
                            #endregion
                            #region Description
                            if (item.EditorialReviews != null)
                            {
                                string description = string.Empty;
                                foreach (EditorialReview edito in item.EditorialReviews)
                                {
                                    if (edito.Content.Length > description.Length && edito.IsLinkSuppressed == false)
                                    {
                                        description = edito.Content;
                                        break;
                                    }
                                }
                                objResults.Add("Description", Util.PurgeHtml(description));
                            }
                            #endregion
                            #region Director
                            if (item.ItemAttributes.Director != null)
                            {
                                List <Artist> directors = item.ItemAttributes.Director.Select(director => ArtistServices.Get(director, out isNew)).ToList();
                                objResults.Add("Director", directors);
                            }
                            #endregion
                            #region Editor
                            if (string.IsNullOrEmpty(item.ItemAttributes.Publisher) == false)
                            {
                                objResults.Add("Editor", item.ItemAttributes.Publisher);
                            }

                            if (objResults.ContainsKey("Editor") == false)
                            {
                                if (string.IsNullOrEmpty(item.ItemAttributes.Label) == false)
                                {
                                    objResults.Add("Editor", item.ItemAttributes.Label);
                                }
                            }

                            if (objResults.ContainsKey("Editor") == false)
                            {
                                if (string.IsNullOrEmpty(item.ItemAttributes.Manufacturer) == false)
                                {
                                    objResults.Add("Editor", item.ItemAttributes.Manufacturer);
                                }
                            }

                            if (objResults.ContainsKey("Editor") == false)
                            {
                                if (string.IsNullOrEmpty(item.ItemAttributes.Studio) == false)
                                {
                                    objResults.Add("Editor", item.ItemAttributes.Studio);
                                }
                            }

                            #endregion
                            #region Format
                            if (item.ItemAttributes.Format != null)
                            {
                                if (item.ItemAttributes.Format.GetLength(0) > 0)
                                {
                                    objResults.Add("Format", item.ItemAttributes.Format[0]);
                                }
                            }
                            #endregion
                            #region Feature
                            if (item.ItemAttributes.Feature != null)
                            {
                                if (item.ItemAttributes.Feature.GetLength(0) > 0)
                                {
                                    if (objResults.ContainsKey("Description") == false)
                                    {
                                        objResults.Add("Description", item.ItemAttributes.Feature[0]);
                                    }
                                    else if (objResults.ContainsKey("Comments") == false)
                                    {
                                        objResults.Add("Comments", item.ItemAttributes.Feature[0]);
                                    }
                                }
                            }
                            #endregion
                            #region Image
                            if (item.LargeImage != null)
                            {
                                objResults.Add("Image", item.LargeImage.URL);
                            }
                            #endregion
                            #region ISBN
                            if (string.IsNullOrWhiteSpace(item.ItemAttributes.ISBN) == false)
                            {
                                objResults.Add("ISBN", item.ItemAttributes.ISBN);
                            }
                            #endregion
                            #region Language
                            if (item.ItemAttributes.Languages != null)
                            {
                                if (item.ItemAttributes.Languages.GetLength(0) > 0)
                                {
                                    objResults.Add("Language", item.ItemAttributes.Languages[0].Name);
                                }
                            }
                            #endregion
                            #region Links
                            if (string.IsNullOrEmpty(item.DetailPageURL) == false)
                            {
                                objResults.Add("Links", item.DetailPageURL);
                            }
                            #endregion
                            #region Pages
                            if (string.IsNullOrEmpty(item.ItemAttributes.NumberOfPages) == false)
                            {
                                objResults.Add("Pages", item.ItemAttributes.NumberOfPages);
                            }
                            #endregion
                            #region Platform
                            if (item.ItemAttributes.Platform != null)
                            {
                                if (item.ItemAttributes.Platform.GetLength(0) > 0)
                                {
                                    objResults.Add("Platform", item.ItemAttributes.Platform[0]);
                                }
                            }
                            #endregion
                            #region ProductGroup
                            if (string.IsNullOrEmpty(item.ItemAttributes.ProductGroup) == false)
                            {
                                objResults.Add("ProductGroup", item.ItemAttributes.ProductGroup);
                            }
                            #endregion
                            #region ProductTypeName
                            if (string.IsNullOrEmpty(item.ItemAttributes.ProductTypeName) == false)
                            {
                                objResults.Add("ProductTypeName", item.ItemAttributes.ProductTypeName);
                            }
                            #endregion
                            #region Price
                            if (item.ItemAttributes.ListPrice != null)
                            {
                                objResults.Add("Price", item.ItemAttributes.ListPrice.Amount);
                            }
                            #endregion
                            #region Rated
                            if (string.IsNullOrEmpty(item.ItemAttributes.AudienceRating) == false)
                            {
                                if (item.ItemAttributes.AudienceRating.Contains("PG-13"))
                                {
                                    objResults.Add("Rated", "PG-13");
                                }
                                else if (item.ItemAttributes.AudienceRating.Contains("NC-17"))
                                {
                                    objResults.Add("Rated", "NC-17");
                                }
                                else if (item.ItemAttributes.AudienceRating.Contains("PG"))
                                {
                                    objResults.Add("Rated", "PG");
                                }
                                else if (item.ItemAttributes.AudienceRating.Contains("R"))
                                {
                                    objResults.Add("Rated", "R");
                                }
                                else if (item.ItemAttributes.AudienceRating.Contains("G") || item.ItemAttributes.AudienceRating.Contains("Tous publics"))
                                {
                                    objResults.Add("Rated", "G");
                                }
                            }
                            #endregion
                            #region Rating
                            if (objResults.ContainsKey("Rating") == false)
                            {
                                if (item.CustomerReviews != null)
                                {
                                    if (item.CustomerReviews.HasReviews == true)
                                    {
                                        objResults.Add("Rating", GetRating(item.CustomerReviews.IFrameURL));
                                    }
                                }
                            }
                            #endregion
                            #region Released
                            if (string.IsNullOrWhiteSpace(item.ItemAttributes.ReleaseDate) == false)
                            {
                                DateTime date;
                                if (DateTime.TryParse(item.ItemAttributes.ReleaseDate, out date) == true)
                                {
                                    objResults.Add("Released", date);
                                }
                            }
                            else if (string.IsNullOrWhiteSpace(item.ItemAttributes.PublicationDate) == false)
                            {
                                DateTime date;
                                if (DateTime.TryParse(item.ItemAttributes.PublicationDate, out date) == true)
                                {
                                    objResults.Add("Released", date);
                                }
                            }
                            #endregion
                            #region RunTime
                            if (item.ItemAttributes.RunningTime != null)
                            {
                                objResults.Add("Runtime", (int?)item.ItemAttributes.RunningTime.Value);
                            }
                            #endregion
                            #region Studio
                            if (string.IsNullOrWhiteSpace(item.ItemAttributes.Studio) == false)
                            {
                                objResults.Add("Studio", item.ItemAttributes.Studio);
                            }
                            #endregion
                            #region Title
                            if (string.IsNullOrWhiteSpace(item.ItemAttributes.Title) == false)
                            {
                                objResults.Add("Title", item.ItemAttributes.Title);
                            }
                            #endregion
                            #region Tracks
                            if (item.Tracks != null)
                            {
                                if (item.Tracks[0].Track.GetLength(0) > 0)
                                {
                                    List <string> tracks = item.Tracks[0].Track.Select(node => node.Value).ToList();
                                    objResults.Add("Tracks", tracks);
                                }
                            }
                            #endregion
                            #region Types
                            if (item.BrowseNodes != null)
                            {
                                if (item.BrowseNodes.BrowseNode.GetLength(0) > 0)
                                {
                                    List <string> types = new List <string>();
                                    foreach (BrowseNode node in item.BrowseNodes.BrowseNode)
                                    {
                                        if (node.Ancestors.GetLength(0) > 0)
                                        {
                                            if (node.Ancestors[0].Name == "Genres" ||
                                                node.Ancestors[0].Name == "Styles" ||
                                                node.Ancestors[0].Name == "Nintendo DS" ||
                                                node.Ancestors[0].Name == "Categories" ||
                                                node.Ancestors[0].Name == "Categorías" ||
                                                node.Ancestors[0].Name == "Thèmes" ||
                                                node.Ancestors[0].Name == "Juegos" ||
                                                node.Ancestors[0].Name == "Genre (theme_browse-bin)" ||
                                                node.Ancestors[0].Name == "Les collections" ||
                                                node.Ancestors[0].Name == "Literature & Fiction" ||
                                                node.Ancestors[0].BrowseNodeId == "301138" ||
                                                node.Ancestors[0].BrowseNodeId == "301134" ||
                                                (node.Ancestors[0].BrowseNodeId == "425527031" && node.BrowseNodeId != "2486268031") ||
                                                node.Ancestors[0].BrowseNodeId == "466276" ||
                                                node.Ancestors[0].BrowseNodeId == "302068" ||
                                                node.Ancestors[0].BrowseNodeId == "924340031" ||
                                                node.Ancestors[0].BrowseNodeId == "301132" ||
                                                node.Ancestors[0].BrowseNodeId == "2" ||
                                                node.Ancestors[0].BrowseNodeId == "2396" ||
                                                node.Ancestors[0].Name == "Literatura y ficción")
                                            {
                                                types.Add(node.Name);
                                            }
                                            else if (node.Ancestors[0].IsCategoryRoot == false && node.Ancestors[0].Ancestors != null)
                                            {
                                                if (node.Ancestors[0].Ancestors.GetLength(0) > 0)
                                                {
                                                    if (node.Ancestors[0].Ancestors[0].Name == "Genres" ||
                                                        node.Ancestors[0].Name == "Nintendo DS" ||
                                                        node.Ancestors[0].Name == "Styles" ||
                                                        node.Ancestors[0].Name == "Categories" ||
                                                        node.Ancestors[0].Name == "Categorías" ||
                                                        node.Ancestors[0].Name == "Les collections" ||
                                                        node.Ancestors[0].Name == "Juegos" ||
                                                        node.Ancestors[0].Name == "Genre (theme_browse-bin)" ||
                                                        node.Ancestors[0].Name == "Literature & Fiction" ||
                                                        node.Ancestors[0].Name == "Literatura y ficción")
                                                    {
                                                        types.Add(node.Name);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    objResults.Add("Types", types);
                                }
                            }
                            #endregion
                        }
                    }
                }
                return(objResults);
            }
            catch (Exception ex)
            {
                Util.LogException(ex, asin);
                return(null);
            }
        }
コード例 #18
0
ファイル: MainForm.cs プロジェクト: ron-t/breview-a-crawler
        private void updateBooksDetail(string[] ISBNs)
        {
            ItemLookupRequest request = new ItemLookupRequest();

            if (ISBNs.Count() < 1)
            {
                //appendLineToLog("**No books selected");
                return;
            }

            string[] toProcess;
            /***** batch in 10s *****/
            for (int i = 0; i < ISBNs.Length; i = i + 10)
            {
                toProcess = ISBNs.Skip(i).Take(10).ToArray();

                //mark unprocessed books as'processed' by setting dummy values (but retain existing non null values)
                AmazonCrawlerEntities c = DbUtil.getNewContext();
                foreach (var isbn in toProcess)
                {
                    Book b = DbUtil.getBook(c, isbn);

                    if (chkTitle.Checked && b.title == null)
                    {
                        b.title = "-";
                    }

                    if (chkDetailUrl.Checked && b.detailPageURL == null)
                    {
                        b.detailPageURL = "-";
                    }
                }

                try
                {
                    c.SaveChanges();
                }
                catch (Exception ex)
                {
                    appendLineToLog("[error] preparing books from Db: " + ex.Message);
                    appendLineToLog("\t" + ex.StackTrace);
                    return;
                }

                request.ItemId = toProcess;
                request.IdType = ItemLookupRequestIdType.ISBN;
                //request.SearchIndex = "Books";

                request.ResponseGroup = new string[] { "ItemAttributes" };
                //request.ResponseGroup = new string[] { "Reviews", "Large", "SalesRank" };

                ItemLookup itemLookup = new ItemLookup();
                itemLookup.Request      = new ItemLookupRequest[] { request };
                itemLookup.AssociateTag = "notag"; //this is a required param, so I just use a dummy value which seems to work

                // send the ItemSearch request
                ItemLookupResponse response = amazonClient.ItemLookup(itemLookup);

                if (response.Items != null && response.Items.Count() > 0 && response.Items[0].Item != null)
                {
                    AmazonCrawlerEntities context = DbUtil.getNewContext();

                    // write out the results from the ItemSearch request
                    foreach (var item in response.Items[0].Item)
                    {
                        Book toUpdate = DbUtil.getBook(context, item.ASIN);

                        if (toUpdate != null)
                        {
                            int      parseOutput;
                            DateTime parseOutputDate = DateTime.MinValue;

                            if (item.ItemAttributes != null && item.ItemAttributes.Title != null)
                            {
                                toUpdate.title = item.ItemAttributes.Title;
                            }

                            //2012-10-31 21:51
                            //Not going to get sales rank from here. There are multiple ranks listed on the details page
                            //so will crawl that separately instead.
                            //The plan is to crawl it same time as getting rating stats AND author ranks so the stats are
                            //collected at roughly the same time.

                            //int.TryParse(item.SalesRank, out parseOutput);
                            //toUpdate.salesRank = parseOutput;

                            int.TryParse(item.ItemAttributes.NumberOfPages, out parseOutput);
                            if (parseOutput > 0)
                            {
                                toUpdate.pages = parseOutput;
                            }
                            else
                            {
                                toUpdate.pages = null;
                            }

                            toUpdate.publisher = item.ItemAttributes.Publisher;

                            DateTime.TryParse(item.ItemAttributes.PublicationDate, out parseOutputDate);
                            if (parseOutputDate.Equals(DateTime.MinValue))
                            {
                                //date format is just a year number.
                                DateTime.TryParse(item.ItemAttributes.PublicationDate + "/01/01", out parseOutputDate);
                            }
                            if (parseOutputDate > DateTime.MinValue)
                            {
                                toUpdate.publicationDate = parseOutputDate;
                            }
                            else
                            {
                                toUpdate.publicationDate = null;
                            }

                            toUpdate.detailPageURL = item.DetailPageURL.Substring(0, item.DetailPageURL.IndexOf("%3F"));

                            context.SaveChanges();
                            appendLineToLog(item.ItemAttributes.Title + " (" + item.ASIN + ") updated.");
                        }
                        else
                        {
                            appendLineToLog("[error] ISBN " + item.ASIN + " not found in database");
                        }
                    }
                    if (response.Items[0].Item.Count() != toProcess.Count())
                    {
                        appendLineToLog((toProcess.Count() - response.Items[0].Item.Count()) + " books skipped");
                    }
                }
                else
                {
                    appendLineToLog(toProcess.Count() + " books skipped.");

                    /********************
                    * Check if it's due to ItemID invalid error, if so then continue as normal
                    * ItemID invalid error just means the ISBN doesn't exist in Amazon's API.
                    * ******************/
                    if (response.Items != null && response.Items[0].Request != null && response.Items[0].Request.Errors != null)
                    {
                        var errorCode = response.Items[0].Request.Errors[0].Code;
                        if (errorCode == "AWS.InvalidParameterValue")
                        {
                            sleep();
                            continue;
                        }
                    }
                    //Otherwise there may be an API error
                    //undo the 'process' marker.
                    else
                    {
                        foreach (var isbn in toProcess)
                        {
                            Book b = DbUtil.getBook(c, isbn);

                            if (b.title == "-")
                            {
                                b.title = null;
                            }

                            if (b.detailPageURL == "-")
                            {
                                b.detailPageURL = null;
                            }
                        }

                        try
                        {
                            c.SaveChanges();
                        }
                        catch (Exception ex)
                        {
                            appendLineToLog("[error] preparing books from Db: " + ex.Message);
                            appendLineToLog("\t" + ex.StackTrace);
                            return;
                        }

                        //sleep between 3 and 10 minutes before continuing
                        TimeSpan duration = new TimeSpan(0, 0, ((3 * 60) + (RANDOM.Next(10 * 60))));
                        appendLineToLog(string.Format("Sleeping for {0}:{1} mins and secs", duration.Minutes, duration.Seconds));
                        System.Threading.Thread.Sleep(duration);
                    }
                }

                sleep(); //delay each API call
            }
        }
コード例 #19
0
ファイル: Productos.cs プロジェクト: Marcosibushak/BuyBox
        private void ValidacionProductosAsin(ItemLookupResponse reponseAsin)
        {
            try
            {
                OBitacora.GuardarLinea($"{ DateTime.Now:yyyy-MM-dd hh:mm:ss}|Productos|Revisando que la lista ASIN no tenga errores");
                if (reponseAsin.Items.First().Request.Errors != null)
                {
                    foreach (var error in reponseAsin.Items.First().Request.Errors)
                    {
                        if (error.Message !=
                            "Este artículo no es accesible mediante la API para publicidad de productos.")
                        {
                            OBitacora.GuardarLinea(
                                $"{DateTime.Now:yyyy-MM-dd hh:mm:ss}|Error respuesta amazon producto|{error.Message}|");
                            if (!ProductosAdapter.Existe(error.Message.Split(' ').First()))
                            {
                                try
                                {
                                    if (ProductosAdapter.Existe(error.Message.Replace("\n", "").Split(' ').First()))
                                    {
                                        ProductosAdapter.Actualizar(new Producto
                                        {
                                            ASIN               = error.Message.Replace("\n", "").Split(' ').First(),
                                            Offers             = $"{error.Code}|{error.Message}",
                                            UPC                = "",
                                            Label              = "",
                                            Actualizacion      = false,
                                            Amount             = "",
                                            Binding            = "",
                                            Brand              = "",
                                            BuyBox             = null,
                                            Caracteristicas    = null,
                                            ClothingSize       = "",
                                            Color              = "",
                                            Comentarios        = null,
                                            CurrencyCode       = "",
                                            Department         = "",
                                            Dimensiones        = null,
                                            DimensionesPaquete = null,
                                            EAN                = "",
                                            FormattedPrice     = "",
                                            LargeImage         = "",
                                            LegalDisclaimer    = "",
                                            MPN                = "",
                                            Manufacture        = "",
                                            MediumImage        = "",
                                            Model              = "",
                                            NumberItems        = 0,
                                            PackageQuantity    = 0,
                                            PartNumber         = "",
                                            ProdcutTypeName    = "",
                                            ProductGroup       = "",
                                            Publisher          = "",
                                            ReleaseDate        = "",
                                            Resumen            = null,
                                            SalesRank          = 0,
                                            Similares          = null,
                                            Size               = "",
                                            SmallImage         = "",
                                            Studio             = "",
                                            Title              = "",
                                            UPCs               = null,
                                            isAdultProduct     = false,
                                            isAutographed      = false,
                                            isMemorabilia      = false
                                        });
                                    }
                                    else
                                    {
                                        ProductosAdapter.Insertar(new Producto
                                        {
                                            ASIN               = error.Message.Replace("\n", "").Split(' ').First(),
                                            Offers             = $"{error.Code}|{error.Message}",
                                            UPC                = "",
                                            Label              = "",
                                            Actualizacion      = false,
                                            Amount             = "",
                                            Binding            = "",
                                            Brand              = "",
                                            BuyBox             = null,
                                            Caracteristicas    = null,
                                            ClothingSize       = "",
                                            Color              = "",
                                            Comentarios        = null,
                                            CurrencyCode       = "",
                                            Department         = "",
                                            Dimensiones        = null,
                                            DimensionesPaquete = null,
                                            EAN                = "",
                                            FormattedPrice     = "",
                                            LargeImage         = "",
                                            LegalDisclaimer    = "",
                                            MPN                = "",
                                            Manufacture        = "",
                                            MediumImage        = "",
                                            Model              = "",
                                            NumberItems        = 0,
                                            PackageQuantity    = 0,
                                            PartNumber         = "",
                                            ProdcutTypeName    = "",
                                            ProductGroup       = "",
                                            Publisher          = "",
                                            ReleaseDate        = "",
                                            Resumen            = null,
                                            SalesRank          = 0,
                                            Similares          = null,
                                            Size               = "",
                                            SmallImage         = "",
                                            Studio             = "",
                                            Title              = "",
                                            UPCs               = null,
                                            isAdultProduct     = false,
                                            isAutographed      = false,
                                            isMemorabilia      = false
                                        });
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("Error guardar errores amazon: " + GetMessageError(ex));
                                    OBitacora.GuardarLinea(
                                        $"{DateTime.Now:yyyy-MM-dd hh:mm:ss}|Productos|Guardar amazon error|{GetMessageError(ex)}");
                                }
                            }
                        }
                    }
                }
                OBitacora.GuardarLinea($"{ DateTime.Now:yyyy-MM-dd hh:mm:ss}|Productos|Obteniendo elemento ASIN");
                var productosAsin = reponseAsin.Items.First();

                OBitacora.GuardarLinea($"{ DateTime.Now:yyyy-MM-dd hh:mm:ss}|Productos|Procesando elementos ASIN");
                ProcesarItems(productosAsin);
                OBitacora.GuardarLinea($"{ DateTime.Now:yyyy-MM-dd hh:mm:ss}|Productos|Fin de proceso de elementos ASIN");
            }
            catch (DbEntityValidationException ex)
            {
                var resultErrors = ex.EntityValidationErrors.Aggregate("",
                                                                       (current1, validationErrors) => validationErrors.ValidationErrors.Aggregate(current1,
                                                                                                                                                   (current, validationError) =>
                                                                                                                                                   current + $"NValid.{validationErrors.Entry.Entity}:{validationError.ErrorMessage}"));
                OBitacora.GuardarLinea($"{DateTime.Now:yyyy-MM-dd hh:mm:ss}|Error|{resultErrors} /{GetMessageError(ex)}|");
            }
            catch (Exception ex)
            {
                OBitacora.GuardarLinea($"{DateTime.Now:yyyy-MM-dd hh:mm:ss}|Error|{GetMessageError(ex)}/{ex.StackTrace}|");
            }
        }
コード例 #20
0
ファイル: Productos.cs プロジェクト: Marcosibushak/BuyBox
        private void ValidacionProductosUpc(ItemLookupResponse responseUpc)
        {
            try
            {
                OBitacora.GuardarLinea($"{ DateTime.Now:yyyy-MM-dd hh:mm:ss}|Productos|Revisando que la lista UPC no tenga errores");
                if (responseUpc.Items.First().Request.Errors != null)
                {
                    foreach (var error in responseUpc.Items.First().Request.Errors)
                    {
                        OBitacora.GuardarLinea($"{DateTime.Now:yyyy-MM-dd hh:mm:ss}|Productos|{error.Message}|");
                        if (!ProductosAdapter.Existe(error.Message.Split(' ').First()))
                        {
                            try
                            {
                                ProductosAdapter.Insertar(new Producto
                                {
                                    ASIN               = error.Message.Split(' ').First(),
                                    Offers             = $"{error.Code}|{error.Message}",
                                    UPC                = "",
                                    Label              = "",
                                    Actualizacion      = false,
                                    Amount             = "",
                                    Binding            = "",
                                    Brand              = "",
                                    BuyBox             = null,
                                    Caracteristicas    = null,
                                    ClothingSize       = "",
                                    Color              = "",
                                    Comentarios        = null,
                                    CurrencyCode       = "",
                                    Department         = "",
                                    Dimensiones        = null,
                                    DimensionesPaquete = null,
                                    EAN                = "",
                                    FormattedPrice     = "",
                                    LargeImage         = "",
                                    LegalDisclaimer    = "",
                                    MPN                = "",
                                    Manufacture        = "",
                                    MediumImage        = "",
                                    Model              = "",
                                    NumberItems        = 0,
                                    PackageQuantity    = 0,
                                    PartNumber         = "",
                                    ProdcutTypeName    = "",
                                    ProductGroup       = "",
                                    Publisher          = "",
                                    ReleaseDate        = "",
                                    Resumen            = null,
                                    SalesRank          = 0,
                                    Similares          = null,
                                    Size               = "",
                                    SmallImage         = "",
                                    Studio             = "",
                                    Title              = "",
                                    UPCs               = null,
                                    isAdultProduct     = false,
                                    isAutographed      = false,
                                    isMemorabilia      = false
                                });
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Error guardar errores amazon: " + GetMessageError(ex));
                                OBitacora.GuardarLinea($"{ DateTime.Now:yyyy-MM-dd hh:mm:ss}|Productos|Guardar amazon error|{ GetMessageError(ex) }");
                            }
                        }
                    }
                }
                OBitacora.GuardarLinea($"{ DateTime.Now:yyyy-MM-dd hh:mm:ss}|Productos|Obteniendo elementos UPC");
                var productosUpc = responseUpc.Items.First();

                OBitacora.GuardarLinea($"{ DateTime.Now:yyyy-MM-dd hh:mm:ss}|Productos|Procesando elementos UPC");
                ProcesarItems(productosUpc);
                OBitacora.GuardarLinea($"{ DateTime.Now:yyyy-MM-dd hh:mm:ss}|Productos|Fin proceso de elementos UPC");
            }
            catch (Exception ex)
            {
                OBitacora.GuardarLinea($"{ DateTime.Now:yyyy-MM-dd hh:mm:ss}|Error Productos|{GetMessageError(ex)}/{ex.StackTrace}");
            }
        }
コード例 #21
0
ファイル: LookupResults.cs プロジェクト: dekkerb115/Bam.Net
 public LookupResults(ItemLookupResponse response)
 {
     this.Info = new LookupResponseInfo(response.Items[0]);
     SetItems();
 }
コード例 #22
0
        //private string GetAttribute(string xpath)
        //{

        //}

        private AmazonItemLookup MapProperties(ItemLookupResponse response)
        {
            AmazonItemLookup item = new AmazonItemLookup();

            if (response.Items != null && response.Items.Item != null)
            {
                item.ASIN          = response.Items.Item.ASIN;
                item.ParentASIN    = response.Items.Item.ParentASIN != null ? response.Items.Item.ParentASIN : "";
                item.DetailPageURL = response.Items.Item.DetailPageURL != null ? response.Items.Item.DetailPageURL : "";

                if (response.Items.Item.SmallImage != null)
                {
                    item.SmallImageUrl = response.Items.Item.SmallImage.URL != null ? response.Items.Item.SmallImage.URL : "";
                }

                if (response.Items.Item.MediumImage != null)
                {
                    item.MediumImageUrl = response.Items.Item.MediumImage.URL != null ? response.Items.Item.MediumImage.URL : "";
                }

                if (response.Items.Item.MediumImage != null)
                {
                    item.LargeImageUrl = response.Items.Item.LargeImage.URL != null ? response.Items.Item.LargeImage.URL : "";
                }

                if (response.Items.Item.ItemAttributes != null)
                {
                    item.Manufacturer = response.Items.Item.ItemAttributes.Manufacturer != null ? response.Items.Item.ItemAttributes.Manufacturer : "";
                    item.ProductGroup = response.Items.Item.ItemAttributes.ProductGroup != null ? response.Items.Item.ItemAttributes.ProductGroup : "";
                    item.Title        = response.Items.Item.ItemAttributes.Title != null ? response.Items.Item.ItemAttributes.Title : "";

                    if (response.Items.Item.ItemAttributes.Feature != null && response.Items.Item.ItemAttributes.Feature.Count() > 0)
                    {
                        item.FeatureDescription = string.Join(" ", response.Items.Item.ItemAttributes.Feature);
                    }

                    item.ProductType = response.Items.Item.ItemAttributes.ProductTypeName;
                    item.UPC         = Convert.ToInt64(response.Items.Item.ItemAttributes.UPC);
                    item.Model       = response.Items.Item.ItemAttributes.Model != null ? response.Items.Item.ItemAttributes.Model : "";

                    if (response.Items.Item.ItemAttributes.ListPrice != null)
                    {
                        item.ListPrice         = response.Items.Item.ItemAttributes.ListPrice.FormattedPrice != null ? response.Items.Item.ItemAttributes.ListPrice.FormattedPrice : "";
                        item.ListPriceCurrency = response.Items.Item.ItemAttributes.ListPrice.CurrencyCode != null ? response.Items.Item.ItemAttributes.ListPrice.CurrencyCode : "";
                        item.ListPriceValue    = response.Items.Item.ItemAttributes.ListPrice.Amount != null ? response.Items.Item.ItemAttributes.ListPrice.Amount : ulong.MinValue;
                    }
                }

                //if (response.Items.Item.OfferSummary != null)
                //{
                //    if (response.Items.Item.OfferSummary.LowestNewPrice != null)
                //    {
                //        item.ListPriceCurrency = response.Items.Item.OfferSummary.LowestNewPrice.CurrencyCode;
                //        item.ListPrice = response.Items.Item.OfferSummary.LowestNewPrice.FormattedPrice;
                //        item.ListPriceValue = response.Items.Item.OfferSummary.LowestNewPrice.Amount;
                //    }
                //}
            }

            if (response.Items != null && response.Items.Request != null && response.Items.Request.Errors != null)
            {
                item.ErrorCode    = response.Items.Request.Errors.Error.Code != null ? response.Items.Request.Errors.Error.Code : "";
                item.ErrorMessage = response.Items.Request.Errors.Error.Message != null ? response.Items.Request.Errors.Error.Message : "";
            }

            // inefficient - change FetchItem
            item.ResultXML = SerializeObject(response);

            return(item);
        }
コード例 #23
0
        public static List <PriceSourceItemOld> ToPriceSourceItemsOld(this ItemLookupResponse amazonItemResponse)
        {
            List <PriceSourceItemOld> result = new List <PriceSourceItemOld>();

            if (amazonItemResponse == null || amazonItemResponse.Items.Item == null)
            {
                return(result);
            }
            foreach (var item in amazonItemResponse.Items.Item)
            {
                string asin     = item.ASIN;
                string url      = item.DetailPageURL;
                string imageUrl = item.LargeImage?.URL;
                if (string.IsNullOrWhiteSpace(imageUrl) && item.ImageSets?.Length > 0)
                {
                    imageUrl = item.ImageSets.FirstOrDefault()?.LargeImage?.URL;
                }
                string itemName = item.ItemAttributes.Title;

                string model        = item.ItemAttributes.Model;
                string modelYear    = item.ItemAttributes.ModelYear;
                string brand        = item.ItemAttributes.Brand;
                string manufacturer = item.ItemAttributes.Manufacturer;
                string ean          = item.ItemAttributes.EAN;
                if (string.IsNullOrWhiteSpace(itemName))
                {
                    itemName = item.ToString();
                }

                if (item.Offers.TotalOffers != "0")
                {
                    foreach (var offer in item.Offers.Offer)
                    {
                        string merchant = offer.Merchant?.Name;
                        foreach (var offerListing in offer.OfferListing)
                        {
                            PriceSourceItemOld priceSourceItem = new PriceSourceItemOld();
                            priceSourceItem.Merchant     = merchant;
                            priceSourceItem.ASIN         = asin;
                            priceSourceItem.URL          = url;
                            priceSourceItem.ImageUrl     = imageUrl;
                            priceSourceItem.Name         = itemName;
                            priceSourceItem.Model        = model;
                            priceSourceItem.ModelYear    = modelYear;
                            priceSourceItem.Brand        = brand;
                            priceSourceItem.Manufacturer = manufacturer;
                            priceSourceItem.Ean          = ean;
                            string priceStr = offerListing.Price.Amount;
                            priceSourceItem.Name          = itemName;
                            priceSourceItem.PriceCurrency = offerListing.Price.CurrencyCode;
                            if (!string.IsNullOrWhiteSpace(offerListing.SalePrice?.Amount))
                            {
                                priceStr = offerListing.SalePrice.Amount;
                                priceSourceItem.PriceCurrency = offerListing.SalePrice.CurrencyCode;
                            }
                            if (priceStr.Length >= 2)
                            {
                                priceStr = priceStr.Insert(priceStr.Length - 2, ".");
                            }
                            priceSourceItem.Price = double.Parse(priceStr);
                            result.Add(priceSourceItem);
                        }
                    }
                }
                else if (item.ItemLinks.FirstOrDefault(l => l.Description == "All Offers") != null)
                {
                    //Usually if that is not here then there are no offers
                    if (item.OfferSummary?.LowestNewPrice?.Amount != null)
                    {
                        url = item.ItemLinks.FirstOrDefault(l => l.Description == "All Offers").URL;
                        PriceSourceItemOld priceSourceItem = new PriceSourceItemOld();
                        priceSourceItem.ASIN         = asin;
                        priceSourceItem.Name         = itemName;
                        priceSourceItem.URL          = url;
                        priceSourceItem.ImageUrl     = imageUrl;
                        priceSourceItem.Model        = model;
                        priceSourceItem.ModelYear    = modelYear;
                        priceSourceItem.Brand        = brand;
                        priceSourceItem.Manufacturer = manufacturer;
                        priceSourceItem.Ean          = ean;

                        string priceStr = item.OfferSummary.LowestNewPrice.Amount;
                        priceSourceItem.PriceCurrency = item.OfferSummary.LowestNewPrice.CurrencyCode;
                        if (priceStr.Length >= 2)
                        {
                            priceStr = priceStr.Insert(priceStr.Length - 2, ".");
                        }
                        priceSourceItem.Price = double.Parse(priceStr);
                        result.Add(priceSourceItem);
                    }
                }
            }
            return(result);
        }
コード例 #24
0
        public AwsItem GetResultsFromXml(string xml)
        {
            var itemLookupResponse = new ItemLookupResponse(xml);

            return(itemLookupResponse.ToAwsItem());
        }
コード例 #25
0
 internal void SetInfo(ItemLookupResponse response)
 {
     SetInfo(response.Items[0]);
 }
コード例 #26
0
 internal LookupResponseInfo(ItemLookupResponse response)
     : this(response.Items[0])
 {
 }