public Album AmazonAlbumLookup(string albumId) { Album album = new Album(); var helper = new SignedRequestHelper(Options.MainSettings.AmazonSite); string requestString = helper.Sign(string.Format(itemLookup, albumId)); string responseXml = Util.GetWebPage(requestString); if (responseXml == null) return album; XmlDocument xml = new XmlDocument(); xml.LoadXml(responseXml); // Retrieve default Namespace of the document and add it to the NameSpacemanager string defaultNameSpace = xml.DocumentElement.GetNamespaceOfPrefix(""); XmlNamespaceManager nsMgr = new XmlNamespaceManager(xml.NameTable); nsMgr.AddNamespace("ns", defaultNameSpace); XmlNodeList nodes = xml.SelectNodes("/ns:ItemLookupResponse/ns:Items/ns:Item", nsMgr); if (nodes.Count > 0) { album = FillAlbum(nodes[0]); } return album; }
private T Fetch <T>(OrderAmazonSettings amazonSettings, IDictionary <string, string> request) where T : class { request["Service"] = amazonSettings.Service; request["AssociateTag"] = amazonSettings.AssociateTag; request["Version"] = amazonSettings.Version; SignedRequestHelper helper = new SignedRequestHelper(amazonSettings.AWSAccessKeyID, amazonSettings.AWSSecretKey, amazonSettings.Endpoint); string requestUrl = helper.Sign(request); string _awsNamespace = string.Format("http://webservices.amazon.com/{0}/{1}", "AWSECommerceService", "2013-08-01"); try { HttpWebRequest webRequest = (System.Net.HttpWebRequest)HttpWebRequest.Create(requestUrl); webRequest.UserAgent = "Chrome/56.0.2924.87"; webRequest.AllowWriteStreamBuffering = true; webRequest.Timeout = 20000; using (WebResponse response = webRequest.GetResponseAsync().Result) { using (StreamReader xmlReader = new StreamReader(response.GetResponseStream())) { XmlSerializer serializer = new XmlSerializer(typeof(T), _awsNamespace); T result = (T)serializer.Deserialize(xmlReader); if (result != null) { return(result); } } } } catch (Exception ex) { var logger = EngineContext.Current.Resolve <ILogger>(); logger.Error(ex.Message, ex); } return(null); }
// from https://msdn.microsoft.com/en-us/library/hh534080.aspx private XmlDocument MakeRequest(string searchTerm, int itemPage) { SignedRequestHelper helper = new SignedRequestHelper(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY, DESTINATION); IDictionary <string, string> r1 = new Dictionary <string, String>(); r1["Service"] = "AWSECommerceService"; r1["Operation"] = "ItemSearch"; r1["ResponseGroup"] = "ItemAttributes,OfferSummary"; r1["AssociateTag"] = "test123"; r1["Keywords"] = (searchTerm != null) ? searchTerm : "nike"; r1["SearchIndex"] = "All"; r1["ItemPage"] = itemPage.ToString(); string requestUrl = helper.Sign(r1); try { HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest; HttpWebResponse response = request.GetResponse() as HttpWebResponse; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(response.GetResponseStream()); return(xmlDoc); } catch (Exception e) { Console.WriteLine(e.Message); return(null); } }
/// <summary> /// Lookup an Amazon Album, for which the ASIN is known. /// Should find one exact match. /// </summary> /// <param name = "albumID"></param> /// <returns></returns> public AmazonAlbum AmazonAlbumLookup(string albumID) { AmazonAlbum album = new AmazonAlbum(); SignedRequestHelper helper = new SignedRequestHelper(Options.MainSettings.AmazonSite); string requestString = helper.Sign(string.Format(itemLookup, albumID)); string responseXml = Util.GetWebPage(requestString); if (responseXml == null) { return(album); } XmlDocument xml = new XmlDocument(); xml.LoadXml(responseXml); // Retrieve default Namespace of the document and add it to the NameSpacemanager string defaultNameSpace = xml.DocumentElement.GetNamespaceOfPrefix(""); XmlNamespaceManager nsMgr = new XmlNamespaceManager(xml.NameTable); nsMgr.AddNamespace("ns", defaultNameSpace); XmlNodeList nodes = xml.SelectNodes("/ns:ItemLookupResponse/ns:Items/ns:Item", nsMgr); if (nodes.Count > 0) { album = FillAlbum(nodes[0]); } return(album); }
public static IEnumerable <AmazonBookSearchResult> AmazonItemLookup(string category, string browseNode, string keyWords) { SignedRequestHelper helper = new SignedRequestHelper(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY, DESTINATION); String requestUrl; IDictionary <string, string> r1 = new Dictionary <string, String>(); r1["Service"] = "AWSECommerceService"; r1["Version"] = "2009-03-31"; r1["Operation"] = "ItemSearch"; r1["ResponseGroup"] = "ItemAttributes"; r1["SearchIndex"] = category; r1["Keywords"] = keyWords; requestUrl = helper.Sign(r1); XmlDocument xmlDoc = sendRequest(requestUrl); XDocument doc = XDocument.Load(new XmlNodeReader(xmlDoc)); XNamespace ns = "http://webservices.amazon.com/AWSECommerceService/2009-03-31"; IEnumerable <AmazonBookSearchResult> result = from items in doc.Element(ns + "ItemSearchResponse").Elements(ns + "Items").Elements(ns + "Item") select new AmazonBookSearchResult { ASIN = (string)items.Element(ns + "ASIN") }; int count = doc.Element(ns + "ItemSearchResponse").Elements(ns + "Items").Elements(ns + "Item").Count(); return(result); } // end Lookup()
/// <summary> /// Lookup an Amazon Album, for which the ASIN is known. /// Should find one exact match. /// </summary> /// <param name = "albumID"></param> /// <returns></returns> public AmazonAlbum AmazonAlbumLookup(string albumID) { AmazonAlbum album = new AmazonAlbum(); SignedRequestHelper helper = new SignedRequestHelper(Options.MainSettings.AmazonSite); string requestString = helper.Sign(string.Format(itemLookup, albumID)); string responseXml = Util.GetWebPage(requestString); if (responseXml == null) { return(album); } XmlDocument xml = new XmlDocument(); xml.LoadXml(responseXml); XmlNamespaceManager nsMgr = new XmlNamespaceManager(xml.NameTable); nsMgr.AddNamespace("ns", "http://webservices.amazon.com/AWSECommerceService/2009-03-31"); XmlNodeList nodes = xml.SelectNodes("/ns:ItemLookupResponse/ns:Items/ns:Item", nsMgr); if (nodes.Count > 0) { album = FillAlbum(nodes[0]); } return(album); }
/// <summary> /// リクエストURL作成 /// </summary> /// <param name="isbn"></param> /// <returns></returns> public string CreateRequestUrl(string isbn) { var isbnWithoutSign = isbn.Replace("-", ""); if (isbnWithoutSign.Length != ISBN_LENGTH10 && isbnWithoutSign.Length != ISBN_LENGTH13 ) { throw new ArgumentException("ISBNの長さ不正"); } SignedRequestHelper helper = new SignedRequestHelper(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY, DESTINATION, ASSOCIATE_TAG); IDictionary <string, string> request = new Dictionary <string, String>(); request["Service"] = "AWSECommerceService"; request["Operation"] = "ItemLookup"; request["IdType"] = "ISBN"; request["ItemId"] = isbnWithoutSign; request["SearchIndex"] = "Books"; request["ResponseGroup"] = "Images,ItemAttributes,Offers"; string requestUrl = helper.Sign(request); System.IO.File.AppendAllText(@"V:\localweb\log\bookshelf.log", "RequestUrl:" + requestUrl); return(requestUrl); }
/// <summary> /// Search on Amazon for an albums of a specific artist /// </summary> /// <param name = "artist"></param> /// <param name = "albumTitle"></param> /// <returns></returns> public List <AmazonAlbum> AmazonAlbumSearch(string artist, string albumTitle) { log.Debug("Amazon: Searching Amazon Webservices"); List <AmazonAlbum> albums = new List <AmazonAlbum>(); SignedRequestHelper helper = new SignedRequestHelper(Options.MainSettings.AmazonSite); string requestString = helper.Sign(string.Format(itemSearch, HttpUtility.UrlEncode(artist), HttpUtility.UrlEncode(albumTitle))); string responseXml = Util.GetWebPage(requestString); if (responseXml == null) { log.Debug("Amazon: Amazon Webservices did not return any data"); return(albums); } XmlDocument xml = new XmlDocument(); xml.LoadXml(responseXml); // Retrieve default Namespace of the document and add it to the NameSpacemanager string defaultNameSpace = xml.DocumentElement.GetNamespaceOfPrefix(""); XmlNamespaceManager nsMgr = new XmlNamespaceManager(xml.NameTable); nsMgr.AddNamespace("ns", defaultNameSpace); XmlNodeList nodes = xml.SelectNodes("/ns:ItemSearchResponse/ns:Items/ns:Item", nsMgr); if (nodes.Count > 0) { foreach (XmlNode node in nodes) { AmazonAlbum newAlbum = FillAlbum(node); // Check if we already got an album with the same title. // This happens, if the same album has been released by different distributors, labels // we will skip the album in this case bool found = false; foreach (AmazonAlbum album in albums) { if (album.Title == newAlbum.Title) { found = true; break; } } if (!found) { if (newAlbum.LargeImageUrl != null || newAlbum.MediumImageUrl != null || newAlbum.SmallImageUrl != null) { albums.Add(newAlbum); } } } } return(albums); }
private string ExecuteRequest(Dictionary <string, string> request, Regions region) { SignedRequestHelper helper = new SignedRequestHelper(this.AWS_ACCESS_KEY, this.AWS_SECRET_KEY, RegionUrlMapping[region]); string requestUri = helper.Sign(request); string response = RestApiUtils.ExecuteRestApi(requestUri); return(response); }
public static Product getAmazonDataById(string id) { Product p = new Product(); SignedRequestHelper s = new SignedRequestHelper("//Your Associate Key Id //", "//Your Associate Secret Key //", "webservices.amazon.in"); IDictionary <string, string> r1 = new Dictionary <string, string>(); r1["Service"] = "AWSECommerceService"; r1["Operation"] = "ItemLookup"; r1["AssociateTag"] = "//Your Associate Tag "; r1["ItemId"] = id; r1["IdType"] = "ASIN"; r1["ResponseGroup"] = "Images,ItemAttributes"; r1["Condition"] = "All"; r1["Version"] = "2011-08-01"; string signedUrl = s.Sign(r1); WebRequest request = HttpWebRequest.Create(signedUrl); WebResponse response = request.GetResponse(); XmlDocument doc = new XmlDocument(); doc.Load(response.GetResponseStream()); string NAMESPACE = "http://webservices.amazon.com/AWSECommerceService/2011-08-01"; XmlNode productTypeNode = doc.GetElementsByTagName("ProductGroup", NAMESPACE)[0]; XmlNode titleNode = doc.GetElementsByTagName("Title", NAMESPACE)[0]; XmlNode ImageUrlNode = doc.GetElementsByTagName("ImageSets", NAMESPACE)[0]; XmlNode urlNode = doc.GetElementsByTagName("DetailPageURL", NAMESPACE)[0]; XmlNode ImageNode = ImageUrlNode.FirstChild.LastChild.FirstChild; p.url = urlNode.InnerText; p.imgsrc = ImageNode.InnerText; p.title = titleNode.InnerText; p.productType = productTypeNode.InnerText; p.price = "N/A"; p.website = "Amazon"; response.Close(); return(p); }
private ItemSearchResponse ExecuteItemSearch(IDictionary <string, string> query, string AWSAccessKeyId, string AWSSecretKey, string AWSMarketPlace) { String requestUrl; SignedRequestHelper helper = new SignedRequestHelper(AWSAccessKeyId, AWSSecretKey, AWSMarketPlace); requestUrl = helper.Sign(query); var item = FetchSearchItem(requestUrl); return(item); }
public IList <ICatalogueExtendedInfo> SearchAmazon(string searchTerms) { var searchArray = searchTerms.Split(','); IDictionary <string, string> searchParams = AmazonHelper.GetBaseSearchParams(SearchType.ArtistSearch); IList <ICatalogueExtendedInfo> returnArray = new List <ICatalogueExtendedInfo>(); foreach (var searchItem in searchArray) { SignedRequestHelper urlHelper = new SignedRequestHelper(this._accessID, this._secretKey, this._requestEndpoint, this._associateTag); searchParams["Artist"] = searchItem.Trim(); var restUrl = urlHelper.Sign(searchParams); XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.Load(restUrl); } catch (WebException ex) { //Log here throw; } var items = xmlDoc["ItemSearchResponse"]["Items"]; foreach (XmlNode item in items) { if (item.Name == "Item") { var newItem = AmazonHelper.GetNewCatalogueObjectFromXmlNode(item); if (newItem.Artist.ToLower() == searchItem.Trim()) { returnArray.Add(newItem); } } } if (returnArray.Count == 0) { ICatalogueExtendedInfo newItem = new CatalogueExtendedInfo { Artist = "None", Title = "None", PicUrl = "None available", ASIN = "", ReleaseDate = "", Price = 0, Url = "http://my-cue.co.uk" }; } } return(returnArray); }
/* * Function to return XmlDocument using GET method */ public XElement getOutputXml(Page page, string keywords, string cat, string key1, string key2, string pgnum, string min, string max, string sort) { AWS_ACCESS_KEY_ID_IDENTIFIER = key1; AWS_SECRET_KEY_IDENTIFIER = key2; SignedRequestHelper helper = new SignedRequestHelper(AWS_ACCESS_KEY_ID_IDENTIFIER, AWS_SECRET_KEY_IDENTIFIER, DESTINATION); String reqUrl; XElement xmldoc = null; String[] Keywords = new String[] { keywords, }; // Creating request string foreach (String keyword in Keywords) { String reqString = "Service=AWSECommerceService" + "&Version=2013-04-04" + "&Operation=ItemSearch" + "&AssociateTag=net4ccsneue02-20" + "&SearchIndex=" + cat + "&ItemPage=" + pgnum + "&MinimumPrice=" + min + "&MaximumPrice=" + max + "&Sort=" + sort + "&ResponseGroup=ItemAttributes,Images,Variations,Offers" + "&MerchantId=All" + "&Keywords=" + keyword; // Calling sign method to sign the request url with signature reqUrl = helper.Sign(reqString); // Sending HTTP request to web service and returning response as Xml document try { WebRequest req = HttpWebRequest.Create(reqUrl); WebResponse resp = req.GetResponse(); XmlDocument doc = new XmlDocument(); Stream responseStream = resp.GetResponseStream(); doc.Load(responseStream); XmlElement root = doc.DocumentElement; string xml = root.InnerXml; string fxml = "<root>" + xml + "</root>"; TextReader tr = new StringReader(fxml); XElement lroot = XElement.Load(tr); return(lroot); } catch (Exception e) { System.Console.WriteLine("Caught Exception: " + e.Message); System.Console.WriteLine("Stack Trace: " + e.StackTrace); } return(xmldoc); } return(xmldoc); }
public void Purchase(string item,string quantity) { SignedRequestHelper helper = new SignedRequestHelper("AKIAIDNYFWXXLHWVIZTA", "FqhoXL791UFp5/+fADdWjYHRj13mzA3ShJxuUSoP", "webservices.amazon.com", "FqhoXL791UFp5/+fADdWjYHRj13mzA3ShJxuUSoP"); IDictionary<string, string> r1 = new Dictionary<string, String>(); r1["Service"] = "AWSECommerceService"; r1["Operation"] = "CartCreate"; r1["Item.1.ASIN"] = item; r1["Item.1.Quantity"] = quantity; string strRequestUrl = helper.Sign(r1); new AmazonResponseParser().Purchase(strRequestUrl); }
public ICatalogueExtendedInfo LookupSearchString(string searchString, SearchIndex searchIndex) { string searchIndexString; var searchStringEncoded = HttpUtility.UrlEncode(searchString); IDictionary <string, string> searchParams = AmazonHelper.GetBaseSearchParams(SearchType.SearchTerm); ICatalogueExtendedInfo returnItem = new CatalogueExtendedInfo(); switch (searchIndex) { case SearchIndex.MP3: searchIndexString = "MP3Downloads"; break; case SearchIndex.CD: searchIndexString = "Music"; break; default: searchIndexString = "All"; break; } SignedRequestHelper urlHelper = new SignedRequestHelper(this._accessID, this._secretKey, this._requestEndpoint, this._associateTag); searchParams["Keywords"] = searchStringEncoded; searchParams["SearchIndex"] = searchIndexString; var restUrl = urlHelper.Sign(searchParams); XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.Load(restUrl); } catch (WebException ex) { //Log here throw; } var items = xmlDoc["ItemSearchResponse"]["Items"]; foreach (XmlNode item in items) { if (item.Name == "Item") { returnItem = AmazonHelper.GetNewCatalogueObjectFromXmlNode(item); break; } } return(returnItem); }
public AmazonItem ItemLookup(string id) { SignedRequestHelper helper = new SignedRequestHelper("AKIAIDNYFWXXLHWVIZTA", "FqhoXL791UFp5/+fADdWjYHRj13mzA3ShJxuUSoP", "webservices.amazon.com", "FqhoXL791UFp5/+fADdWjYHRj13mzA3ShJxuUSoP"); IDictionary<string, string> r1 = new Dictionary<string, String>(); r1["Service"] = "AWSECommerceService"; r1["Operation"] = "ItemLookup"; r1["ItemId"] = id; r1["ItemType"] = "ASIN"; r1["ResponseGroup"] = "Images,ItemAttributes,Offers"; r1["Version"] = "2011-08-01"; string strRequestUrl = helper.Sign(r1); return new AmazonResponseParser().GetProducts(strRequestUrl).FirstOrDefault(); }
//overload with page set public static string GenerateSignedRequestUrl(string search, string page, string ind) { SignedRequestHelper helper = new SignedRequestHelper("AKIAICBPC6GRXG5RSJVQ", "sVEJc5ntFfiBU8k4DriOLWk2mBT2Nqt1BbOLbTn5", "webservices.amazon.com"); IDictionary<string, string> req = new Dictionary<string, String>(); req["Service"] = "AWSECommerceService"; req["Keywords"] = search; req["Operation"] = "ItemSearch"; req["SearchIndex"] = ind; req["AssociateTag"] = "givmemyidcom-20"; req["ItemPage"] = page; req["ResponseGroup"] = "Offers,Images,ItemAttributes"; req["Timestamp"] = DateTime.Now.ToString("yyyy-mm-ddThh:mm:ssZ"); return helper.Sign(req); }
public UPCItemLookup(string p_sUPC) { string requestUrl; SignedRequestHelper oHelper = new SignedRequestHelper(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY, DESTINATION); IDictionary<string, string> r1 = new Dictionary<string, String>(); r1["Service"] = "AWSECommerceService"; r1["Version"] = "2009-03-31"; r1["Operation"] = "ItemLookup"; r1["ItemId"] = p_sUPC; r1["ResponseGroup"] = "Small"; requestUrl = oHelper.Sign(r1); string title = FetchTitle(requestUrl); }
public string buildRequest(BasicAmazonOperation opertionData) { IDictionary <string, string> requestParams = new Dictionary <string, String>(); requestParams["AssociateTag"] = associateTag; //requestParams["Operation"] = "ItemLookup"; //requestParams["ItemId"] = "B00IZ1Y2XM"; requestParams["Service"] = "AWSECommerceService"; requestParams["Version"] = "2011-08-01"; requestParams["Operation"] = opertionData.OperationName; var requestUrl = requestParams.Concat(opertionData.requestParameters).ToDictionary(i => i.Key, i => i.Value); return(helper.Sign(requestUrl)); }
private string GetRequestUrl(string pageNr, string searchString) { SignedRequestHelper signingHelper = new SignedRequestHelper(keyID, tag, secKey, destination); // Assembling request IDictionary<string, string> request = new Dictionary<string, String>(); request["Service"] = "AWSECommerceService"; request["Operation"] = "ItemSearch"; request["SearchIndex"] = "All"; request["Keywords"] = searchString; request["ResponseGroup"] = "Medium"; request["ItemPage"] = pageNr; return signingHelper.Sign(request); }
private string GetRequestUrl(string pageNr, string searchString) { SignedRequestHelper signingHelper = new SignedRequestHelper(keyID, tag, secKey, destination); // Assembling request IDictionary <string, string> request = new Dictionary <string, String>(); request["Service"] = "AWSECommerceService"; request["Operation"] = "ItemSearch"; request["SearchIndex"] = "All"; request["Keywords"] = searchString; request["ResponseGroup"] = "Medium"; request["ItemPage"] = pageNr; return(signingHelper.Sign(request)); }
private string CreateSignedUrl() { SignedRequestHelper helper = new SignedRequestHelper(Configuration.AWSAccessKeyId, Configuration.AWSSecretAccessKey, Constants.AWSUrl); QueryString query = new QueryString(); query.Add("Service", "AWSECommerceService"); query.Add("AssociateTag", Configuration.AWSAID); query.Add("Version", "2011-08-01"); query.Add("ResponseGroup", "Images,Small"); query.Add("Operation", "ItemSearch"); query.Add("SearchIndex", ItemType.ToString()); query.Add(SearchType.ToString(), Uri.EscapeDataString(Keywords)); var signedUrl = helper.Sign(query); return signedUrl; }
private String GetProductUrlRequestByEan(String ean) { IDictionary <string, string> requestParams = new Dictionary <string, String>(); requestParams.Add("Service", "AWSECommerceService"); requestParams.Add("Operation", "ItemSearch"); requestParams.Add("AWSAccessKeyId", ACCESS_KEY_ID); requestParams.Add("AssociateTag", ASSOCIATE_TAG); requestParams.Add("Keywords", ean); requestParams.Add("IdType", "EAN"); requestParams.Add("ResponseGroup", "Accessories,AlternateVersions,BrowseNodes,EditorialReview,Images,ItemAttributes,ItemIds,OfferFull,OfferListings,Offers,OfferSummary,PromotionSummary,RelatedItems,Reviews,SalesRank,Similarities"); requestParams.Add("SearchIndex", "All"); requestParams.Add("RelationshipType", "AuthorityTitle"); return(helper.Sign(requestParams)); }
public void SelectProducts(string keyword, Action<string, IEnumerable<Product>> productsCallback) { SignedRequestHelper signer = new SignedRequestHelper(ApplicationContext.Current.StartupArguments["AccessKey"], ApplicationContext.Current.StartupArguments["SecretKey"], ServiceDomain); string url = signer.Sign(String.Format(SearchQueryFormat, keyword.Replace(' ', '+'))); Uri searchUri = new Uri(url, UriKind.Absolute); WebClient webClient = new WebClient(); webClient.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e) { if ((e.Cancelled == false) && (e.Error == null)) { string xml = e.Result; if (String.IsNullOrEmpty(xml) == false) { // Remove the default xmlns, simply because it simplifies the node names // we use in the XLINQ statement next. xml = xml.Replace(@"xmlns=""http://webservices.amazon.com/AWSECommerceService/2009-03-31""", String.Empty); XDocument xdoc = XDocument.Parse(xml); IEnumerable<Product> productsQuery = from item in xdoc.Descendants("Item") where item.HasElements && item.Element("ItemAttributes").HasElements && item.Element("ItemAttributes").Element("Author") != null select new Product { ASIN = item.Element("ASIN").Value, ItemUri = new Uri(item.Element("DetailPageURL").Value, UriKind.Absolute), ImageUri = new Uri(item.Element("MediumImage").Element("URL").Value, UriKind.Absolute), Title = item.Element("ItemAttributes").Element("Title").Value, By = item.Element("ItemAttributes").Element("Author").Value }; Product[] products = productsQuery.ToArray(); productsCallback(keyword, products); return; } productsCallback(keyword, null); } }; webClient.DownloadStringAsync(searchUri); }
private string BuildQueryUrl() { SignedRequestHelper rh = new SignedRequestHelper( ConfigurationManager.AppSettings.Get("AWSAccessKey"), ConfigurationManager.AppSettings.Get("AWSSecretKey"), "/", SERVICE_HOST ); IDictionary<string, string> qs = new Dictionary<string, string>(StringComparer.Ordinal); qs.Add("Action", ACTION_NAME ); qs.Add("ResponseGroup", RESPONSE_GROUP_NAME); qs.Add("AWSAccessKeyId", ConfigurationManager.AppSettings.Get("AWSAccessKey")); qs.Add("Url", m_websiteUrl ); qs.Add("SignatureVersion", "2"); qs.Add("SignatureMethod", HASH_ALGORITHM); return rh.Sign( qs ); }
private static XmlDocument FetchItem(string id, SignedRequestHelper otsi) { string requestString = "Service=AWSECommerceService" + "&Version=2011-08-01" + "&Operation=ItemLookup" + "&AssociateTag=PutYourAssociateTagHere" + "&ItemId=" + id ; string requestUrl; requestUrl = otsi.Sign(requestString); WebRequest request = HttpWebRequest.Create(requestUrl); WebResponse response = request.GetResponse(); XmlDocument doc = new XmlDocument(); doc.Load(response.GetResponseStream()); return(doc); }
public async Task<TodoItem> Lookup(string isbn) { if (isbn.Length == 13) this.ITEM_ID = isbn; else if (isbn.Length == 10) this.ITEM_ID = IsbnConverter.ConvertToISBN13(isbn); else //return ""; return null; SignedRequestHelper helper = new SignedRequestHelper( Helpers.ApiKeys.MY_AWS_ASSOCIATE_TAG, Helpers.ApiKeys.MY_AWS_ACCESS_KEY_ID, Helpers.ApiKeys.MY_AWS_SECRET_KEY, DESTINATION, ID_TYPE); /* * The helper supports two forms of requests - dictionary form and query string form. */ String requestUrl; //String itemInfo; TodoItem itemInfo; /* * Here is an ItemLookup example where the request is stored as a dictionary. */ IDictionary<string, string> r1 = new Dictionary<string, String>(); r1["Service"] = "AWSECommerceService"; r1["Version"] = "2009-03-31"; r1["Operation"] = "ItemLookup"; r1["ItemId"] = ITEM_ID; r1["ResponseGroup"] = "Images,Small"; requestUrl = helper.Sign(r1); itemInfo = await FetchTitle(requestUrl); System.Diagnostics.Debug.WriteLine("ItemLookup Dictionary form."); //System.Diagnostics.Debug.WriteLine($"ItemInfo is title: {itemInfo.Name}, image: {itemInfo.Image}"); return itemInfo; }
public static string ItemSearchRequest(string keywords, int page) { SignedRequestHelper helper = new SignedRequestHelper(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY, DESTINATION); String requestUrl; String requestString = "Service=AWSECommerceService" + "&Version=2009-03-31" + "&Operation=ItemSearch" + "&AssociateTag=SomeAsosiateTag" + "&SearchIndex=All" + "&Keywords=" + keywords + "&ItemPage=" + page + "&ResponseGroup=Request,ItemAttributes,OfferSummary,Images,Reviews,EditorialReview" ; requestUrl = helper.Sign(requestString); return(requestUrl); }
public ActionResult AddToCart([FromBody] Checkout checkout)//([FromBody]List<AmzCartItem> items, string id) { var result = string.Empty; var id = (checkout.Id == "undefined" || checkout.Id == string.Empty) ? ASSOCIATE_ID : checkout.Id; CartOperation cartOp = new CartOperation(); Cart cart = new Cart(); try { var d = cartOp.AddCartItems(checkout.items, id, false); //var url = signHelper.Sign(d); string url = ""; string endPoint = HtmlHelper.EndPointUrl(); using (SignedRequestHelper signer = new SignedRequestHelper( Environment.GetEnvironmentVariable("ACCESS_KEY"), Environment.GetEnvironmentVariable("SECRET_KEY"), endPoint)) { url = signer.Sign(d); //signHelper.Sign(StoreInDictionary(search, page)); } WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponseAsync().Result; XmlDocument doc = new XmlDocument(); doc.Load(response.GetResponseStream()); var reqNodes = doc.GetElementsByTagName("Request"); var cidNodes = doc.GetElementsByTagName("CartId"); var purchaseUrlNodes = doc.GetElementsByTagName("PurchaseURL"); Request req = new Request(); req.IsValid = bool.Parse(reqNodes[0].FirstChild.InnerText); cart.CartId = cidNodes[0].InnerText; cart.Request = req; cart.PurchaseURL = purchaseUrlNodes[0].InnerText; } catch (Exception ex) { // TODO: create a logger result = "Server Error: " + ex.Message; } return(new JsonResult(cart)); }
public List<AmazonItem> ItemSearch(string page, string keyword = null, string category = null) { SignedRequestHelper helper = new SignedRequestHelper("AKIAIDNYFWXXLHWVIZTA", "FqhoXL791UFp5/+fADdWjYHRj13mzA3ShJxuUSoP", "webservices.amazon.com", "FqhoXL791UFp5/+fADdWjYHRj13mzA3ShJxuUSoP"); IDictionary<string, string> r1 = new Dictionary<string, String>(); r1["Service"] = "AWSECommerceService"; r1["Operation"] = "ItemSearch"; r1["SearchIndex"] = category ?? "All"; if(category != null) r1["Sort"] = "salesrank"; r1["Availability"] = "Available"; r1["ResponseGroup"] = "Medium"; r1["ItemPage"] = page; r1["Condition"] = "New"; r1["Keywords"] = keyword ?? "All"; r1["ResponseGroup"] = "Images,ItemAttributes,Offers"; r1["Version"] = "2011-08-01"; string strRequestUrl = helper.Sign(r1); return new AmazonResponseParser().GetProducts(strRequestUrl); }
/// <summary> /// Lookup an Amazon Album, for which the ASIN is known. /// Should find one exact match. /// </summary> /// <param name = "albumID"></param> /// <returns></returns> public AmazonAlbum AmazonAlbumLookup(string albumID) { AmazonAlbum album = new AmazonAlbum(); SignedRequestHelper helper = new SignedRequestHelper(Options.MainSettings.AmazonSite); string requestString = helper.Sign(string.Format(itemLookup, albumID)); string responseXml = Util.GetWebPage(requestString); if (responseXml == null) return album; XmlDocument xml = new XmlDocument(); xml.LoadXml(responseXml); XmlNamespaceManager nsMgr = new XmlNamespaceManager(xml.NameTable); nsMgr.AddNamespace("ns", "http://webservices.amazon.com/AWSECommerceService/2009-03-31"); XmlNodeList nodes = xml.SelectNodes("/ns:ItemLookupResponse/ns:Items/ns:Item", nsMgr); if (nodes.Count > 0) { album = FillAlbum(nodes[0]); } return album; }
private static XmlDocument FetchPage(string searchIndex, string keywords, int page, SignedRequestHelper otsi) { string requestString = "Service=AWSECommerceService" + "&Version=2011-08-01" + "&Operation=ItemSearch" + "&ItemPage=" + page + "&AssociateTag=PutYourAssociateTagHere" + "&SearchIndex=" + searchIndex + "&ResponseGroup=Medium" + "&MerchantId=All" + "&Keywords=" + keywords ; string requestUrl; requestUrl = otsi.Sign(requestString); WebRequest request = HttpWebRequest.Create(requestUrl); WebResponse response = request.GetResponse(); XmlDocument doc = new XmlDocument(); doc.Load(response.GetResponseStream()); return(doc); }
//非同期メソッド。呼び出すときは呼び出し側でイベントハンドラーGetItemInfoFromAmazonCompletedEventHandlerを実装すること。 //書籍のXMLデータ取得を試み、その結果をメンバ変数のXMLItemInfo入れたあと、イベントを発行する。 public void GetItemInfo() { //ItemDataBase itemDB = new ItemDataBase(); XElement xmlItemInfo; if (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) { //ネットワークが有効な場合、リクエストを送る。 var helper = new SignedRequestHelper(MyAWSAccessKeyID, MyAWSSecretKey, Destination); // パラメータの設定(取得する製品や取得したい情報によって変わる) var r1 = new Dictionary <string, String>(); r1["Service"] = "AWSECommerceService"; r1["Version"] = "2011-08-01"; r1["Operation"] = "ItemLookup"; r1["ItemId"] = this.TargetItemID; r1["ResponseGroup"] = "Large,Reviews"; r1["IdType"] = "ISBN"; r1["SearchIndex"] = "Books"; //r1["Keywords"] = "村上 春樹"; r1["AssociateTag"] = MyAssociateTag; // Required from API Version 2011-08-01 var requestUrl = helper.Sign(r1); //URLエンコード Debug.WriteLine(requestUrl); // リクエスト送信 var client = new WebClient(); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); //イベントハンドラをセット client.DownloadStringAsync(new Uri(requestUrl)); //リクエスト送信 } else { //ネットワークが無効な場合 xmlItemInfo = new XElement("Error", "No Network Connection"); xmlItemInfo.SetAttributeValue("Code", 1); xmlItemInfo.Add(new XElement("EAN", this.TargetItemID)); SendCompletedEvent("NoNetwork", xmlItemInfo); } }
public ICatalogueExtendedInfo LookupASIN(string ASINNumber) { var itemNumber = HttpUtility.UrlEncode(ASINNumber); IDictionary <string, string> searchParams = AmazonHelper.GetBaseSearchParams(SearchType.ASIN); ICatalogueExtendedInfo returnItem = new CatalogueExtendedInfo(); SignedRequestHelper urlHelper = new SignedRequestHelper(this._accessID, this._secretKey, this._requestEndpoint, this._associateTag); searchParams["ItemId"] = ASINNumber; var restUrl = urlHelper.Sign(searchParams); XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.Load(restUrl); } catch (WebException ex) { //Log here throw; } var items = xmlDoc["ItemLookupResponse"]["Items"]; foreach (XmlNode item in items) { if (item.Name == "Item") { returnItem = AmazonHelper.GetNewCatalogueObjectFromXmlNode(item); break; } } return(returnItem); }
protected override void GetAlbumInfoWithTimer() { log.Debug("Amazon: Searching Amazon Webservices"); var helper = new SignedRequestHelper(Options.MainSettings.AmazonSite); var requestString = helper.Sign(string.Format(itemSearch, HttpUtility.UrlEncode(ArtistName), HttpUtility.UrlEncode(AlbumName))); var uri = new Uri(requestString); var client = new AlbumInfoWebClient(); client.OpenReadCompleted += CallbackMethod; client.OpenReadAsync(uri); while (Complete == false) { if (MEventStopSiteSearches.WaitOne(500, true)) { Complete = true; } } }
/// <summary> /// Insert Product Details in DB /// </summary> /// <returns></returns> public string InsertData() { responseText = string.Empty; foreach (ConnectionStringSettings ConnectionStrings in ConfigurationManager.ConnectionStrings) { walmartCount = 0; int bestbuyCount = 0; int amazonCount = 0; using (var db = new ECoupounEntities(ConnectionStrings.ConnectionString)) { List<APIDetail> apiDetailsList = db.APIDetails.Where(x => x.IsActive == true && x.Provider.Name == "Walmart").ToList(); ProductsJSON jsonObject = null; List<Products> productsList = null; try { db.DeleteProducts(); foreach (var apiDetail in apiDetailsList) { switch (apiDetail.Provider.Name) { case "BestBuy": jsonObject = MakeAPICall(apiDetail.ServiceUrl); if (jsonObject != null) { for (int i = 1; i <= jsonObject.totalPages; i++) { jsonObject = MakeAPICall(apiDetail.ServiceUrl + "&page=" + i); productsList = new List<Products>(); if (jsonObject != null) { foreach (var product in jsonObject.Products) { productsList.Add(product); } bestbuyCount += dbProducts.InsertProduct(apiDetail.CategoryId, apiDetail.ProviderId, productsList, db); } } } break; case "Walmart": MakeWalmartCallAndProcess(apiDetail.ServiceUrl, apiDetail.CategoryId, apiDetail.ProviderId, db); break; case "Amazon": SignedRequestHelper helper = new SignedRequestHelper(ECoupounConstants.AccessKeyId, ECoupounConstants.SecretKey, ECoupounConstants.DESTINATION); for (int p = 1; p <= 10; p++) { string requestUrl = helper.Sign(string.Format(apiDetail.ServiceUrl, p)); List<Products> amazonProductList = new List<Products>(); HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest; // Get response using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader reader = new StreamReader(response.GetResponseStream()); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(response.GetResponseStream()); XmlNodeList xmlnodelstTrack = xmlDoc.GetElementsByTagName("Item"); XmlNodeList xmlnodelstTrack1 = xmlDoc.GetElementsByTagName("TotalPages"); Products product = new Products(); productsList = new List<Products>(); foreach (XmlNode NodeObj in xmlnodelstTrack) { product = new Products(); for (int i = 0; i < NodeObj.ChildNodes.Count; i++) { if (NodeObj.ChildNodes[i].HasChildNodes) { for (int j = 0; j < NodeObj.ChildNodes[i].ChildNodes.Count; j++) { string key = NodeObj.ChildNodes[i].ChildNodes[j].Name == "#text" ? NodeObj.ChildNodes[i].ChildNodes[j].ParentNode.Name : NodeObj.ChildNodes[i].ChildNodes[j].Name; switch (key) { case "ASIN": product.Sku = NodeObj.ChildNodes[i].ChildNodes[j].InnerText; break; case "DetailPageURL": product.Url = NodeObj.ChildNodes[i].ChildNodes[j].InnerText; break; case "Manufacturer": product.Manufacturer = NodeObj.ChildNodes[i].ChildNodes[j].InnerText; break; case "Model": product.ModelNumber = NodeObj.ChildNodes[i].ChildNodes[j].InnerText; break; case "Color": product.Color = NodeObj.ChildNodes[i].ChildNodes[j].InnerText; break; case "Title": product.Name = NodeObj.ChildNodes[i].ChildNodes[j].InnerText; break; case "Size": product.ScreenSizeIn = NodeObj.ChildNodes[i].ChildNodes[j].InnerText.Split('-')[0]; break; case "ListPrice": product.SalePrice = Convert.ToDecimal(NodeObj.ChildNodes[i].ChildNodes[j].InnerText.Split('$')[1]); product.RegularPrice = Convert.ToDecimal(NodeObj.ChildNodes[i].ChildNodes[j].InnerText.Split('$')[1]); break; case "URL": product.Image = NodeObj.ChildNodes[i].ChildNodes[j].InnerText; break; } } } } productsList.Add(product); } amazonCount += dbProducts.InsertProduct(apiDetail.CategoryId, apiDetail.ProviderId, productsList, db); } } break; } } responseText += string.Format("\nBesyBuy {0} Records.\n", bestbuyCount); responseText += string.Format("Walmart {0} Records.\n", walmartCount); responseText += string.Format("Amazon {0} Records.\n", amazonCount); responseText += string.Format("Total {0} Records.\n", bestbuyCount + walmartCount + amazonCount); } catch (Exception ex) { responseText += string.Format("\nBesyBuy {0} Records.\n", bestbuyCount); responseText += string.Format("Walmart {0} Records.\n", walmartCount); responseText += string.Format("Amazon {0} Records.\n", amazonCount); responseText += string.Format("Total {0} Records.\n", bestbuyCount + walmartCount + amazonCount); responseText += "Some exception is occurred while Inserting Data, exception is : " + ex.Message; } } } return responseText; }
public ActionResult Tulemused(int id) { ViewBag.Id = id; SignedRequestHelper helper = new SignedRequestHelper(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY, DESTINATION); string requestUrl; String requestString = "Service=AWSECommerceService" + "&ItemPage=" + id + "&Version=2009-03-31" + "&Operation=ItemSearch" + "&SearchIndex=All" + "&ResponseGroup=Medium" + "&Keywords=" + GlobalOtsiSona + "&AssociateTag=mytag-20" ; requestUrl = helper.Sign(requestString); try { WebRequest request = HttpWebRequest.Create(requestUrl); // System.Diagnostics.Process.Start(requestUrl); WebResponse response = request.GetResponse(); XmlDocument doc = new XmlDocument(); doc.Load(response.GetResponseStream()); XmlNode xmlPages = doc.GetElementsByTagName("TotalPages").Item(0); double pages = Convert.ToDouble(xmlPages.InnerText); for (int i = 0; i <= 10; i++) { XmlNode xmlUrl = doc.GetElementsByTagName("DetailPageURL").Item(i); XmlNode xmlTitle = doc.GetElementsByTagName("Title").Item(i); XmlNode xmlGenre = doc.GetElementsByTagName("ProductGroup").Item(i); XmlNode xmlPrice = doc.GetElementsByTagName("FormattedPrice").Item(i); string url = xmlUrl.InnerText; string title = xmlTitle.InnerText; string genre = xmlGenre.InnerText; string price = xmlPrice.LastChild.OuterXml; price = price.Replace("$",""); if (pages == id) { ViewBag.NoMoreInfo = 1; } AmazonList.Add(new AmazonDB { ID = i, ItemUrl = url, Title = title, Genre = genre, Price = price }); } return View(AmazonList); } catch (Exception e) { System.Console.WriteLine("Caught Exception: " + e.Message); System.Console.WriteLine("Stack Trace: " + e.StackTrace); } return View(AmazonList); }
private static string BuildRequestUrl(string item_id) { if (string.IsNullOrWhiteSpace(AccessKeyId) && string.IsNullOrWhiteSpace(SecretKey)) throw new Exception("AccessKeyId or SecretKey is null or empty."); var helper = new SignedRequestHelper( AccessKeyId, SecretKey, Destination); var param = new Dictionary<string, String>(); param["Service"] = AWS_SERVICE; param["Version"] = AWS_VERSION; param["Operation"] = "ItemLookup"; param["ItemId"] = item_id; param["ResponseGroup"] = "Medium"; param["AssociateTag"] = AssosiateTag; return helper.Sign(param); }
public static void Main() { SignedRequestHelper helper = new SignedRequestHelper(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY, DESTINATION, ASSOCIATE_TAG); /* * The helper supports two forms of requests - dictionary form and query string form. */ String requestUrl; String title; /* * Here is an ItemLookup example where the request is stored as a dictionary. */ IDictionary<string, string> r1 = new Dictionary<string, String>(); r1["Service"] = "AWSECommerceService"; r1["Version"] = "2009-03-31"; r1["Operation"] = "ItemLookup"; r1["ItemId"] = ITEM_ID; r1["ResponseGroup"] = "Small"; /* Random params for testing */ r1["AnUrl"] = "http://www.amazon.com/books"; r1["AnEmailAddress"] = "*****@*****.**"; r1["AUnicodeString"] = "αβγδεٵٶٷٸٹٺチャーハン叉焼"; r1["Latin1Chars"] = "ĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıIJij"; requestUrl = helper.Sign(r1); title = FetchTitle(requestUrl); System.Console.WriteLine("Method 1: ItemLookup Dictionary form."); System.Console.WriteLine("Title is \"" + title + "\""); System.Console.WriteLine(); /* * Here is a CartCreate example where the request is stored as a dictionary. */ IDictionary<string, string> r2 = new Dictionary<string, String>(); r2["Service"] = "AWSECommerceService"; r2["Version"] = "2009-03-31"; r2["Operation"] = "CartCreate"; r2["Item.1.OfferListingId"] = "Ho46Hryi78b4j6Qa4HdSDD0Jhan4MILFeRSa9mK+6ZTpeCBiw0mqMjOG7ZsrzvjqUdVqvwVp237ZWaoLqzY11w=="; r2["Item.1.Quantity"] = "1"; requestUrl = helper.Sign(r2); title = FetchTitle(requestUrl); System.Console.WriteLine("Method 1: CartCreate Dictionary form."); System.Console.WriteLine("Cart Item Title is \"" + title + "\""); System.Console.WriteLine(); /* * Here is an example where the request is stored as a query-string: */ /* * string requestString = "Service=AWSECommerceService&Version=2009-03-31&Operation=ItemLookup&ResponseGroup=Small&ItemId=" + ITEM_ID; */ System.Console.WriteLine("Method 2: Query String form."); String[] Keywords = new String[] { "surprise!", "café", "black~berry", "James (Jim) Collins", "münchen", "harry potter (paperback)", "black*berry", "finger lickin' good", "!\"#$%'()*+,-./:;<=>?@[\\]^_`{|}~", "αβγδε", "ٵٶٷٸٹٺ", "チャーハン", "叉焼", }; foreach (String keyword in Keywords) { String requestString = "Service=AWSECommerceService" + "&Version=2009-03-31" + "&Operation=ItemSearch" + "&SearchIndex=Books" + "&ResponseGroup=Small" + "&Keywords=" + keyword ; requestUrl = helper.Sign(requestString); title = FetchTitle(requestUrl); System.Console.WriteLine("Keyword=\"" + keyword + "\"; Title=\"" + title + "\""); System.Console.WriteLine(); } String cartCreateRequestString = "Service=AWSECommerceService" + "&Version=2009-03-31" + "&Operation=CartCreate" + "&Item.1.OfferListingId=Ho46Hryi78b4j6Qa4HdSDD0Jhan4MILFeRSa9mK%2B6ZTpeCBiw0mqMjOG7ZsrzvjqUdVqvwVp237ZWaoLqzY11w%3D%3D" + "&Item.1.Quantity=1" ; requestUrl = helper.Sign(cartCreateRequestString); title = FetchTitle(requestUrl); System.Console.WriteLine("Cart Item Title=\"" + title + "\""); System.Console.WriteLine(); System.Console.WriteLine("Hit Enter to end"); System.Console.ReadLine(); }
public static List <Product> getAmazonDatabykeyword(string key) { SignedRequestHelper s = new SignedRequestHelper("//Your Associate Key Id //", "//Your Associate Secret Key //", "webservices.amazon.in"); IDictionary <string, string> r1 = new Dictionary <string, string>(); r1["Service"] = "AWSECommerceService"; r1["Operation"] = "ItemSearch"; r1["AssociateTag"] = "//Your Associate Tag "; r1["SearchIndex"] = "All"; r1["Keywords"] = key; r1["ResponseGroup"] = "Images,ItemAttributes,Offers"; r1["Version"] = "2011-08-01"; r1["ItemPage"] = "1"; string signedUrl = s.Sign(r1); string NAMESPACE = "http://webservices.amazon.com/AWSECommerceService/2011-08-01"; WebRequest request = HttpWebRequest.Create(signedUrl); WebResponse response = request.GetResponse(); XmlDocument doc = new XmlDocument(); doc.Load(response.GetResponseStream()); List <Product> lisAmazon = new List <Product>(); for (int i = 0; i < 10; i++) { Product p = new Product(); try { XmlNode idNode = doc.GetElementsByTagName("ASIN", NAMESPACE).Item(i); XmlNode productTypeNode = doc.GetElementsByTagName("ProductGroup", NAMESPACE).Item(i); XmlNode titleNode = doc.GetElementsByTagName("Title", NAMESPACE).Item(i); XmlNode ImageUrlNode = doc.GetElementsByTagName("ImageSets", NAMESPACE).Item(i); XmlNode priceNodeRaw = doc.GetElementsByTagName("LowestNewPrice", NAMESPACE).Item(i); XmlNode PRICENODE = priceNodeRaw.LastChild; XmlNode urlNode = doc.GetElementsByTagName("DetailPageURL", NAMESPACE).Item(i); XmlNode ImageNode = ImageUrlNode.FirstChild.LastChild.FirstChild; XmlNode priceNode = priceNodeRaw.FirstChild; var id = idNode.InnerText; p.id = id; var title = titleNode.InnerText; p.title = title; var imgsrc = ImageNode.InnerText; p.imgsrc = imgsrc; var price = PRICENODE.InnerText; p.price = price; var producttype = productTypeNode.InnerText; p.productType = producttype; var website = "Amazon"; p.website = website; var url = urlNode.InnerText; p.url = url; //p.id = idNode.InnerText; //p.title = titleNode.InnerText; //p.imgsrc = ImageNode.InnerText; //p.price =Convert.ToInt32( PRICENODE.InnerText.Replace("INR","").Trim()); //p.productType = productTypeNode.InnerText; //p.website = "Amazon"; //p.url = urlNode.InnerText; lisAmazon.Add(p); p.Equals(null); } catch { } } return(lisAmazon); }
private static XmlDocument FetchItem(string id, SignedRequestHelper otsi) { string requestString = "Service=AWSECommerceService" + "&Version=2011-08-01" + "&Operation=ItemLookup" + "&AssociateTag=PutYourAssociateTagHere" + "&ItemId=" + id ; string requestUrl; requestUrl = otsi.Sign(requestString); WebRequest request = HttpWebRequest.Create(requestUrl); WebResponse response = request.GetResponse(); XmlDocument doc = new XmlDocument(); doc.Load(response.GetResponseStream()); return doc; }
private static XmlDocument FetchPage(string searchIndex, string keywords, int page, SignedRequestHelper otsi) { string requestString = "Service=AWSECommerceService" + "&Version=2011-08-01" + "&Operation=ItemSearch" + "&ItemPage="+page + "&AssociateTag=PutYourAssociateTagHere" + "&SearchIndex="+searchIndex + "&ResponseGroup=Medium" + "&MerchantId=All" + "&Keywords=" + keywords ; string requestUrl; requestUrl = otsi.Sign(requestString); WebRequest request = HttpWebRequest.Create(requestUrl); WebResponse response = request.GetResponse(); XmlDocument doc = new XmlDocument(); doc.Load(response.GetResponseStream()); return doc; }
public ItemSearch(string searchIndex, string searchKeywords, int pageNr) { _searchIndex = searchIndex; if (_searchIndex == null || _searchIndex == "") { _searchIndex = "All"; } _searchKeywords = searchKeywords; if (_searchKeywords == null || _searchKeywords == "") { _errorMessage = "Please, insert a keyword to find items!"; return; } _pageNr = pageNr; _totalResults = TotalItemResults(_searchIndex, _searchKeywords); if (_totalResults == 0 && _errorMessage == null) { _errorMessage = "No items match with keyword " + '"' + _searchKeywords + '"' + "!"; return; } else if (_totalResults == 0 && _errorMessage != null) { return; } if (_totalResults > 50 && _searchIndex == "All") { _totalResults = 50; } int initialItemsOnPage = 10; int newItemsOnPage = Globals.MAX_ITEMS_ON_PAGE; int initialPageCount = _totalResults / initialItemsOnPage; int newPageCount = _totalResults / newItemsOnPage; if ((newPageCount * newItemsOnPage) < _totalResults) { newPageCount = newPageCount + 1; } _firstItemIndex = (_pageNr - 1) * newItemsOnPage; int lastItemIndex = _firstItemIndex + (newItemsOnPage - 1); int pageNrForFirstItem = CalculatePageNr(_firstItemIndex); int pageNrForLastItem = CalculatePageNr(lastItemIndex); int pageDifference = pageNrForLastItem - pageNrForFirstItem; float numberOfRequests = (pageDifference + 1) / 2f; int _pageNrForFirstItem = pageNrForFirstItem; int firstItemIndexOnPage = _firstItemIndex - ((pageNrForFirstItem - 1) * 10); int lastItemIndexOnPage = firstItemIndexOnPage + (newItemsOnPage - 1); string pageNrString = pageNrForFirstItem.ToString(); string pageNrStringNext = pageNrForLastItem.ToString(); // loop for receiving items for (int i = 0; i < numberOfRequests; i++) { IDictionary <string, string> r1 = new Dictionary <string, string>(); r1["Service"] = "AWSECommerceService"; r1["Version"] = "2011-08-01"; r1["AssociateTag"] = Globals.ASSOCIATE_TAG; r1["Operation"] = "ItemSearch"; r1["ItemSearch.Shared.Availability"] = "Available"; r1["ItemSearch.Shared.ResponseGroup"] = "Small,Images,Offers"; r1["ItemSearch.Shared.SearchIndex"] = _searchIndex; r1["ItemSearch.Shared.Keywords"] = _searchKeywords; pageNrForFirstItem = _pageNrForFirstItem + (2 * i); pageNrString = pageNrForFirstItem.ToString(); // getting correct amount of items is an iffi business if (pageNrForFirstItem > initialPageCount) { _errorMessage = "No more items!"; return; } else if (pageNrForLastItem > initialPageCount && pageDifference == 1 || pageNrForFirstItem == initialPageCount && pageNrForFirstItem == pageNrForLastItem) { r1["ItemSearch.1.ItemPage"] = pageNrString; if (i != 0) { firstItemIndexOnPage = 0; lastItemIndexOnPage = (lastItemIndex - ((pageNrForLastItem - 1) * 10)); } } else if (pageDifference > 1) { if (pageNrForFirstItem < initialPageCount) { if (pageNrForFirstItem == pageNrForLastItem) { r1["ItemSearch.1.ItemPage"] = pageNrString; firstItemIndexOnPage = 0; lastItemIndexOnPage = (lastItemIndex - ((pageNrForLastItem - 1) * 10)); } else { int pageNrForMiddleItems = (pageNrForFirstItem + 1); pageNrStringNext = pageNrForMiddleItems.ToString(); r1["ItemSearch.1.ItemPage"] = pageNrString; r1["ItemSearch.2.ItemPage"] = pageNrStringNext; if (pageNrForMiddleItems == pageNrForLastItem) { lastItemIndexOnPage = (lastItemIndex - ((pageNrForLastItem - 2) * 10)); } else { lastItemIndexOnPage = 20; if (pageNrForMiddleItems >= initialPageCount) { numberOfRequests = 0; } } } } else { r1["ItemSearch.1.ItemPage"] = pageNrString; } } else if (pageDifference == 1) { r1["ItemSearch.1.ItemPage"] = pageNrString; r1["ItemSearch.2.ItemPage"] = pageNrStringNext; } else if (pageDifference == 0) { r1["ItemSearch.1.ItemPage"] = pageNrString; } // sign request string requestUrl = helper.Sign(r1); WebRequest request = HttpWebRequest.Create(requestUrl); WebResponse response = request.GetResponse(); XmlDocument doc = new XmlDocument(); doc.Load(response.GetResponseStream()); // Get item values int currentIndex = 0; foreach (XmlNode node in doc.GetElementsByTagName("Item")) { if (currentIndex >= firstItemIndexOnPage && currentIndex <= lastItemIndexOnPage) { var item = new Item(); item.ASIN = node["ASIN"].InnerText; item.Title = node["ItemAttributes"]["Title"].InnerText; item.ItemURL = node["DetailPageURL"].InnerText; try { item.LowestPriceInt = (int.Parse(node["OfferSummary"]["LowestNewPrice"]["Amount"].InnerText, null) / 100.0); } catch { item.LowestPriceStr = "N/A"; } try { item.ImageURL = node["MediumImage"]["URL"].InnerText; } catch { item.ImageURL = "http://g-ecx.images-amazon.com/images/G/02/misc/no-img-lg-uk._V366109917_.gif"; } try { item.CurrencyCode = node["OfferSummary"]["LowestNewPrice"]["CurrencyCode"].InnerText; } catch { item.CurrencyCode = ""; } _itemsList.Add(item); } currentIndex++; } } }
public static async Task <HttpResponseMessage> QueueImageFromAmazon( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "createimage/amazon")] HttpRequestMessage req, [Table("CreateImageFromUrls")] IQueryable <CreateImageFromUrlsEntity> imageUrls, [Table("Items")] IQueryable <Item> items, [Queue("create-image-from-urls")] ICollector <CreateImageFromUrlsRequest> queueItems, [Table("CreateImageFromUrls")] ICollector <CreateImageFromUrlsEntity> outImageUrlTable, [Table("Items")] ICollector <Item> outItemTable, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); var imageCount = 0; dynamic data = await req.Content.ReadAsAsync <object>(); string asin = data.asin; string name = data.name; ICollection <string> tags = data.tags.ToObject <List <string> >(); log.Info($"asin={asin}, name={name}, tags={string.Join(",", tags)}"); var AWS_ACCESS_KEY_ID = Environment.GetEnvironmentVariable("PAAPI_ACCESS_KEY_ID"); var AWS_SECRET_KEY = Environment.GetEnvironmentVariable("PAAPI_SECRET_KEY"); var PAAPI_ASSOCIATE_TAG = Environment.GetEnvironmentVariable("PAAPI_ASSOCIATE_TAG"); var helper = new SignedRequestHelper(AWS_ACCESS_KEY_ID, AWS_SECRET_KEY, DESTINATION, PAAPI_ASSOCIATE_TAG); IDictionary <string, string> r1 = new Dictionary <string, string> { ["Service"] = "AWSECommerceService", //r1["Version"] = "2011-08-01"; ["Operation"] = "ItemLookup", ["ItemId"] = asin, ["ResponseGroup"] = "Images" }; IEnumerable <string> images; var retryCount = 0; var retryMax = 5; while (true) { try { var requestUrl = helper.Sign(r1); log.Verbose($"requestUrl: {requestUrl}"); images = Fetch(requestUrl); break; } catch (Exception ex) { log.Warning(ex.Message); if (retryCount >= retryMax) { throw; } retryCount++; } } images.ToList().ForEach((url) => { imageCount++; var rowKey = asin + CommonHelper.MD5Hash(url); var source = "Amazon"; // XXX TrainingImageLogic に寄せる queueItems.Add(new CreateImageFromUrlsRequest() { Url = url, Tags = tags }); // XXX Existチェックしたいだけなのだが if (imageUrls.Where(y => y.PartitionKey == source && y.RowKey == rowKey).ToList().Count() == 0) { outImageUrlTable.Add(new CreateImageFromUrlsEntity() { PartitionKey = source, RowKey = rowKey, Url = url, Tags = tags }); log.Info($"{rowKey} entry to CreateImageFromUrls."); } else { log.Info($"{rowKey} is exist."); } }); if (items.Where(y => y.PartitionKey == "Amazon" && y.RowKey == asin).ToList().Count() == 0) { outItemTable.Add(new Item() { PartitionKey = "Amazon", RowKey = asin, Name = name, Tags = tags }); log.Info($"{asin} entry to Items."); } else { log.Info($"{asin} is exist."); } return(req.CreateJsonResponse(HttpStatusCode.OK, new { imageCount })); }
public ActionResult GetItem(String asin) // [HttpGet] will have api/amazon?search=usersearchword&page=2 { var items = new Item(); var result = new JsonResult(""); try { string url = ""; string endPoint = HtmlHelper.EndPointUrl(); using (SignedRequestHelper signer = new SignedRequestHelper( Environment.GetEnvironmentVariable("ACCESS_KEY"), Environment.GetEnvironmentVariable("SECRET_KEY"), endPoint)) { url = signer.Sign(StoreInDictionary(asin)); } //var url = signHelper.Sign(StoreInDictionary(asin)); WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponseAsync().Result; XmlDocument doc = new XmlDocument(); doc.Load(response.GetResponseStream()); XmlNodeList errorMessageNodes = doc.GetElementsByTagName("Message"); if (!(errorMessageNodes != null && errorMessageNodes.Count > 0)) { var itemNodeList = doc.GetElementsByTagName("Item"); var imageSets = doc.GetElementsByTagName("ImageSet"); var features = doc.GetElementsByTagName("Feature"); var isPrimeEligibleNode = doc.GetElementsByTagName("IsEligibleForPrime"); if (itemNodeList.Count > 0) { var itemNode = itemNodeList[0]; Item item = new Item(); // Get the <Offers> node var offersNode = HtmlHelper.FindNode("Offers", itemNode); // Get the <ItemAttributes> node of an <Item> var attributeNode = HtmlHelper.FindNode("ItemAttributes", itemNode); // <ItemAttributes> var titleNode = HtmlHelper.FindNode("Title", attributeNode); // <Title> // Some items does not have listed price.(ex. item with EAN# 0886424573142) var priceNode = HtmlHelper.FindNode("ListPrice", attributeNode); // <ListPrice> var itemLinkNode = HtmlHelper.FindNode("DetailPageURL", itemNode); var offersSummary = HtmlHelper.FindNode("OfferSummary", itemNode); var asinNode = HtmlHelper.FindNode("ASIN", itemNode); float aveStars = 0; var formattedPriceNode = (priceNode != null) ? HtmlHelper.FindNode("FormattedPrice", priceNode) : null; // <FormattedPrice> var smallImgNode = HtmlHelper.FindNode("SmallImage", itemNode); var smallImgUrlNode = (smallImgNode != null) ? HtmlHelper.FindNode("URL", smallImgNode) : null; var medImgNode = HtmlHelper.FindNode("MediumImage", itemNode); // <MediumImage> var medImgUrlNode = (medImgNode != null) ? HtmlHelper.FindNode("URL", medImgNode) : null; //<URL>https://someurel/src.jpg</URL> var lgImgNode = HtmlHelper.FindNode("LargeImage", itemNode); // <LargeImage> var lgImgUrlNode = (lgImgNode != null) ? HtmlHelper.FindNode("URL", lgImgNode) : null; // <URL> someurl </URL> var reviewsNode = HtmlHelper.FindNode("CustomerReviews", itemNode); // <ReviewsNode> var reviewUrlNode = (reviewsNode != null) ? HtmlHelper.FindNode("IFrameURL", reviewsNode) : null; // <IFrameUrl></IFrameURL/> var currencySign = ""; item.Title = titleNode.InnerText; // </ReviewsNode> item.DisplayedPrice = HtmlHelper.FindDisplayedPrice(offersNode); item.OfferListingId = HtmlHelper.FindOfferListingID(offersNode); item.Price = HtmlHelper.FindPrice(formattedPriceNode, out currencySign); item.CurrencySign = currencySign; item.UrlItemLink = (itemLinkNode != null) ? itemLinkNode.InnerText : string.Empty; item.UrlSmallImage = (smallImgUrlNode != null) ? smallImgUrlNode.InnerText : string.Empty; item.UrlMediumImage = (medImgUrlNode != null) ? medImgUrlNode.InnerText : string.Empty; item.UrlReview = (reviewUrlNode != null) ? reviewUrlNode.InnerText : string.Empty; item.UrlLargeImage = (lgImgUrlNode != null) ? lgImgUrlNode.InnerText : string.Empty; item.StarLabel = "";// HtmlHelper.GetStarReview(item.UrlReview, out aveStars); item.AverageStars = aveStars; item.ID = Guid.NewGuid(); item.Asin = (asinNode != null) ? asinNode.InnerText : string.Empty; item.IsPrimeEligible = HtmlHelper.IsPrimeEligible(isPrimeEligibleNode); item.ItemImages = HtmlHelper.GetImageSets(imageSets); item.Features = HtmlHelper.GetFeatures(features); item.LowestPrice = HtmlHelper.LowestPrice(offersSummary); result = new JsonResult(item); } } else { result = new JsonResult("Error: " + errorMessageNodes.Item(0).InnerText); } } catch (Exception ex) { var m = ex.Message; // TODO: Add logging. //result = new JsonResult("server error"); throw new Exception(ex.Message); } return(result); }
/// <summary> /// Retrieve Album Info using Amazon Web Services /// </summary> /// <returns></returns> public bool GetAlbumInfo() { _AbortGrab = false; _AlbumInfoList.Clear(); bool result = true; try { if (_ArtistName.Length == 0 && _AlbumName.Length == 0) { return(false); } DateTime startTime = DateTime.Now; // Build up a valid request BassRegistration.SignedRequestHelper helper = new SignedRequestHelper("com"); // Use "US" site for cover art search string requestString = helper.Sign(string.Format(itemSearch, System.Web.HttpUtility.UrlEncode(_ArtistName), System.Web.HttpUtility.UrlEncode(_AlbumName))); // Connect to AWS HttpWebRequest request = null; try { request = (HttpWebRequest)WebRequest.Create(requestString); try { // Use the current user in case an NTLM Proxy or similar is used. request.Proxy.Credentials = CredentialCache.DefaultCredentials; } catch (Exception) {} } catch (Exception e) { Log.Error("Cover Art grabber: Create request failed: {0}", e.Message); return(false); } // Get Response from AWS HttpWebResponse response = null; string responseXml = null; try { response = (HttpWebResponse)request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { responseXml = reader.ReadToEnd(); } } } catch (Exception e) { Log.Error("Cover Art grabber: Get Response failed: {0}", e.Message); return(false); } finally { if (response != null) { response.Close(); } } if (responseXml == null) { Log.Debug("Cover Art grabber: No data found for: {0} - {1}", _ArtistName, _AlbumName); return(false); } XmlDocument xml = new XmlDocument(); xml.LoadXml(responseXml); // Retrieve default Namespace of the document and add it to the NameSpacemanager string defaultNameSpace = xml.DocumentElement.GetNamespaceOfPrefix(""); XmlNamespaceManager nsMgr = new XmlNamespaceManager(xml.NameTable); nsMgr.AddNamespace("ns", defaultNameSpace); XmlNodeList nodes = xml.SelectNodes("/ns:ItemSearchResponse/ns:Items/ns:Item", nsMgr); if (nodes.Count == 0) { Log.Debug("Cover Art grabber: No data found for: {0} - {1}", _ArtistName, _AlbumName); return(false); } int imgCount = 0; int totResults = nodes.Count; bool resultsLimitExceeded = false; Log.Info("Cover Art grabber: AWS Response Returned {1} total results.", totResults); // Now loop through all the items and extract the data foreach (XmlNode node in nodes) { // Yield thread... Thread.Sleep(1); GUIWindowManager.Process(); CheckForAppShutdown(); if (resultsLimitExceeded || _AbortGrab) { break; } if (_MaxSearchResultItems != -1 && imgCount >= _MaxSearchResultItems) { resultsLimitExceeded = true; break; } AlbumInfo albumInfo = FillAlbum(node); _AlbumInfoList.Add(albumInfo); ++imgCount; DoProgressUpdate(imgCount, totResults); } string resultsText = ""; if (_AbortGrab) { resultsText = string.Format("AWS album cover art grab aborted by user before completetion. Retreived {0}/{1} records", imgCount, totResults); } else if (resultsLimitExceeded) { resultsText = string.Format("AWS retreived {0}/{1} records (max search limit set to {2} images)", imgCount, totResults, _MaxSearchResultItems); } else { resultsText = string.Format("{0} records retrieved", imgCount); } DateTime stopTime = DateTime.Now; TimeSpan elapsedTime = stopTime - startTime; double totSeconds = elapsedTime.TotalSeconds; float secondsPerImage = (float)totSeconds / (float)imgCount; string et = ""; if (imgCount > 0) { if (_AbortGrab) { et = string.Format("{0:d2}:{1:d2}:{2:d2}.{3:d3} ({4:f3} seconds per image)", elapsedTime.Hours, elapsedTime.Minutes, elapsedTime.Seconds, elapsedTime.Milliseconds, secondsPerImage); } else { et = string.Format("in {0:d2}:{1:d2}:{2:d2}.{3:d3} ({4:f3} seconds per image)", elapsedTime.Hours, elapsedTime.Minutes, elapsedTime.Seconds, elapsedTime.Milliseconds, secondsPerImage); } Log.Info("Cover art grabber:{0} {1}", resultsText, et); } } catch (Exception ex) { //string errMsg = string.Format("GetAlbumInfoAsync caused an exception: {0}\r\n{1}\r\n", ex.Message, ex.StackTrace); Log.Info("Cover art grabber exception:{0}", ex.ToString()); result = false; } //_GrabberRunning = false; if (FindCoverArtDone != null) { FindCoverArtDone(this, EventArgs.Empty); } return(result); }
public static List <Deals> getAmazonOffers() { string NAMESPACE = "http://webservices.amazon.com/AWSECommerceService/2011-08-01"; SignedRequestHelper s = new SignedRequestHelper("//Your Associate Key Id //", "//Your Associate Secret Key //", "webservices.amazon.in"); IDictionary <string, string> r1 = new Dictionary <string, string>(); r1["Service"] = "AWSECommerceService"; r1["Operation"] = "ItemSearch"; r1["AssociateTag"] = "//Your Associate Tag "; r1["SearchIndex"] = "All"; r1["ResponseGroup"] = "Images,ItemAttributes,Offers,PromotionSummary"; r1["Keywords"] = " "; r1["Version"] = "2011-08-01"; // http://webservices.amazon.in/onca/xml?Service=AWSECommerceService // AssociateTag = buyhatk - 21 & //Product p = new Product(); string signedUrl = s.Sign(r1); WebRequest request = HttpWebRequest.Create(signedUrl); WebResponse response = request.GetResponse(); XmlDocument doc = new XmlDocument(); doc.Load(response.GetResponseStream()); var nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("app", "http://webservices.amazon.com/AWSECommerceService/2011-08-01"); List <Deals> lisAmazonOffer = new List <Deals>(); for (int i = 0; i < 9; i++) { Deals p = new Deals(); XmlNode idNode = doc.GetElementsByTagName("ASIN", NAMESPACE).Item(i); XmlNode productTypeNode = doc.GetElementsByTagName("ProductGroup", NAMESPACE).Item(i); XmlNode titleNode = doc.GetElementsByTagName("Title", NAMESPACE).Item(i); XmlNode ImageUrlNode = doc.GetElementsByTagName("ImageSets", NAMESPACE).Item(i); XmlNode priceNodeRaw = doc.GetElementsByTagName("LowestNewPrice", NAMESPACE).Item(i); XmlNode PRICENODE = priceNodeRaw.LastChild; XmlNode urlNode = doc.GetElementsByTagName("DetailPageURL", NAMESPACE).Item(i); XmlNode ImageNode = ImageUrlNode.FirstChild.LastChild.FirstChild; XmlNode priceNode = priceNodeRaw.FirstChild; p.id = idNode.InnerText; p.title = titleNode.InnerText; p.url = urlNode.InnerText; p.imgurl_default = ImageNode.InnerText; p.price = PRICENODE.InnerText; p.category = productTypeNode.InnerText; p.website = "Amazon"; p.imgsrc = p.imgurl_default; lisAmazonOffer.Add(p); p.Equals(null); } return(lisAmazonOffer); }
static void Main(string[] args) { try { BestBuyProducts jsonObject = MakeWalmartAPICall(walmartURL); if (jsonObject != null) { } } catch (Exception ex) { } int total = 1479; int numItems = 25; int start = 1; int span = total / numItems; int span1 = total % numItems; if (span1 > 0) { span++; } //for (int i = 1; i <= span; i++) //{ // if (i > 1) // start += numItems; // Console.WriteLine("Start = " + start); //} HttpWebRequest request = WebRequest.Create(walmartURL) as HttpWebRequest; // Get response using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader reader = new StreamReader(response.GetResponseStream()); var serializer = new JavaScriptSerializer(); var jsonObject = serializer.Deserialize<BestBuyProducts>(reader.ReadToEnd()); span = jsonObject.TotalResults / jsonObject.numItems; span1 = jsonObject.TotalResults % jsonObject.numItems; for (int i = 1; i <= span; i++) { if (i > 1) start += jsonObject.numItems; HttpWebRequest request2 = WebRequest.Create(walmartURL + "&start=" + start) as HttpWebRequest; using (HttpWebResponse response1 = request2.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader reader1 = new StreamReader(response1.GetResponseStream()); var serializer1 = new JavaScriptSerializer(); var jsonObject1 = serializer.Deserialize<BestBuyProducts>(reader1.ReadToEnd()); } } // Console application output Console.WriteLine(reader.ReadToEnd()); } AmazonWCF(); List<Products> amazonProductList = new List<Products>(); SignedRequestHelper helper = new SignedRequestHelper(accessKeyId, secretKey, DESTINATION); //for (int p = 1; p <= 10; p++) //{ String requestString = "Service=AWSECommerceService" + "&Version=2009-03-31" + "&Operation=ItemSearch" + "&SearchIndex=Electronics" + "&ResponseGroup=Images,ItemAttributes,Small,VariationSummary" + "&BrowseNode=1292115011" + "&Keywords=4k" // + "&ItemPage=" + p + "&AssociateTag=fasforles07-20"; string requestUrl = helper.Sign(requestString); HttpWebRequest request1 = WebRequest.Create(requestUrl) as HttpWebRequest; // Get response using (HttpWebResponse response = request1.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader reader = new StreamReader(response.GetResponseStream()); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(response.GetResponseStream()); XmlNodeList xmlnodelstTrack = xmlDoc.GetElementsByTagName("Item"); XmlNodeList xmlnodelstTrack1 = xmlDoc.GetElementsByTagName("TotalPages"); Products product = new Products(); foreach (XmlNode NodeObj in xmlnodelstTrack) { product = new Products(); for (int i = 0; i < NodeObj.ChildNodes.Count; i++) { if (NodeObj.ChildNodes[i].HasChildNodes) { for (int j = 0; j < NodeObj.ChildNodes[i].ChildNodes.Count; j++) { string key = NodeObj.ChildNodes[i].ChildNodes[j].Name == "#text" ? NodeObj.ChildNodes[i].ChildNodes[j].ParentNode.Name : NodeObj.ChildNodes[i].ChildNodes[j].Name; switch (key) { case "ASIN": product.Sku = NodeObj.ChildNodes[i].ChildNodes[j].InnerText; break; case "DetailPageURL": product.Url = NodeObj.ChildNodes[i].ChildNodes[j].InnerText; break; case "Manufacturer": product.Manufacturer = NodeObj.ChildNodes[i].ChildNodes[j].InnerText; break; case "Model": product.ModelNumber = NodeObj.ChildNodes[i].ChildNodes[j].InnerText; break; case "Color": product.Color = NodeObj.ChildNodes[i].ChildNodes[j].InnerText; break; case "Title": product.Name = NodeObj.ChildNodes[i].ChildNodes[j].InnerText; break; case "Size": product.ScreenSizeIn = NodeObj.ChildNodes[i].ChildNodes[j].InnerText.Split('-')[0]; break; case "ListPrice": product.SalePrice = Convert.ToDecimal(NodeObj.ChildNodes[i].ChildNodes[j].InnerText.Split('$')[1]); product.RegularPrice = Convert.ToDecimal(NodeObj.ChildNodes[i].ChildNodes[j].InnerText.Split('$')[1]); break; case "URL": product.Image = NodeObj.ChildNodes[i].ChildNodes[j].InnerText; break; } Console.WriteLine("--------------------------------------------"); Console.WriteLine(key); Console.WriteLine(NodeObj.ChildNodes[i].ChildNodes[j].InnerText); Console.WriteLine("--------------------------------------------"); } } else { Console.WriteLine("--------------------------------------------"); Console.WriteLine(NodeObj.ChildNodes[i].Name); Console.WriteLine(NodeObj.ChildNodes[i].InnerText); Console.WriteLine("--------------------------------------------"); } } amazonProductList.Add(product); } } //} Console.ReadLine(); // Create a configuration object //MarketplaceWebServiceProductsConfig config = new MarketplaceWebServiceProductsConfig(); //config.ServiceURL = serviceURL; //// Set other client connection configurations here if needed //// Create the client itself //var client = new MarketplaceWebServiceProductsClient(appName, appVersion, accessKey, secretKey, config); //MarketplaceWebServiceProductsSample sample = new MarketplaceWebServiceProductsSample(client); // Uncomment the operation you'd like to test here // TODO: Modify the request created in the Invoke method to be valid try { //IMWSResponse response = null; // response = sample.InvokeGetCompetitivePricingForASIN(); // response = sample.InvokeGetCompetitivePricingForSKU(); // response = sample.InvokeGetLowestOfferListingsForASIN(); // response = sample.InvokeGetLowestOfferListingsForSKU(); // response = sample.InvokeGetLowestPricedOffersForASIN(); // response = sample.InvokeGetLowestPricedOffersForSKU(); // response = sample.InvokeGetMatchingProduct(); // response = sample.InvokeGetMatchingProductForId(); // response = sample.InvokeGetMyPriceForASIN(); // response = sample.InvokeGetMyPriceForSKU(); // response = sample.InvokeGetProductCategoriesForASIN(); // response = sample.InvokeGetProductCategoriesForSKU(); // response = sample.InvokeGetServiceStatus(); //response = sample.InvokeListMatchingProducts(); //Console.WriteLine("Response:"); //ResponseHeaderMetadata rhmd = response.ResponseHeaderMetadata; //// We recommend logging the request id and timestamp of every call. //Console.WriteLine("RequestId: " + rhmd.RequestId); //Console.WriteLine("Timestamp: " + rhmd.Timestamp); //string responseXml = response.ToXML(); //Console.WriteLine(responseXml); } catch (Exception ex) { } }
/// <summary> /// Search on Amazon for an albums of a specific artist /// </summary> /// <param name = "artist"></param> /// <param name = "albumTitle"></param> /// <returns></returns> public List<AmazonAlbum> AmazonAlbumSearch(string artist, string albumTitle) { log.Debug("Amazon: Searching Amazon Webservices"); List<AmazonAlbum> albums = new List<AmazonAlbum>(); SignedRequestHelper helper = new SignedRequestHelper(Options.MainSettings.AmazonSite); string requestString = helper.Sign(string.Format(itemSearch, HttpUtility.UrlEncode(artist), HttpUtility.UrlEncode(albumTitle))); string responseXml = Util.GetWebPage(requestString); if (responseXml == null) { log.Debug("Amazon: Amazon Webservices did not return any data"); return albums; } XmlDocument xml = new XmlDocument(); xml.LoadXml(responseXml); XmlNamespaceManager nsMgr = new XmlNamespaceManager(xml.NameTable); nsMgr.AddNamespace("ns", "http://webservices.amazon.com/AWSECommerceService/2005-10-05"); XmlNodeList nodes = xml.SelectNodes("/ns:ItemSearchResponse/ns:Items/ns:Item", nsMgr); if (nodes.Count > 0) { foreach (XmlNode node in nodes) { AmazonAlbum newAlbum = FillAlbum(node); // Check if we already got an album with the same title. // This happens, if the same album has been released by different distributors, labels // we will skip the album in this case bool found = false; foreach (AmazonAlbum album in albums) { if (album.Title == newAlbum.Title) { found = true; break; } } if (!found) if (newAlbum.LargeImageUrl != null || newAlbum.MediumImageUrl != null || newAlbum.SmallImageUrl != null) albums.Add(newAlbum); } } return albums; }
public static void Main() { InitDB(); SignedRequestHelper helper = new SignedRequestHelper(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY, DESTINATION); String requestUrl; System.Console.WriteLine("Method 2: Query String form."); String[] Keywords = new String[] { "surprise!", "café", "black~berry", "James (Jim) Collins", "münchen", "harry potter (paperback)", "black*berry", "finger lickin' good", "!\"#$%'()*+,-./:;<=>?@[\\]^_`{|}~", "αβγδε", "ٵٶٷٸٹٺ", "チャーハン", "叉焼", }; var keyword = "men's shoes size 8"; //foreach (String keyword in Keywords) //{ String requestString = "Service=AWSECommerceService" + "&Version=2009-03-31" + "&Operation=ItemLookup" + "&SearchIndex=All" + "&ResponseGroup=VariationMatrix" + "&AssociateTag=aztag-20" + "&ItemId=B00AEVFNSY" //+ "&Keywords=" + keyword; ; requestUrl = helper.Sign(requestString); string[] topSellerTitles = FetchTitles(requestUrl); foreach (string s in topSellerTitles) { System.Console.WriteLine(s); Console.ReadLine(); } System.Console.WriteLine(); System.Console.WriteLine("Hit Enter to end"); System.Console.ReadLine(); }
//Method to do an ISBN-based lookup and return the signed URL public static string otherlookup(string UPC) { APIsettings set = new APIsettings(); ArrayList parsed = new ArrayList(); parsed = set.parse(); string MY_AWS_ACCESS_KEY_ID = parsed[0].ToString(), MY_AWS_SECRET_KEY = parsed[1].ToString(); //Helper signs the requests SignedRequestHelper helper = new SignedRequestHelper(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY, DESTINATION); //Helper looks for a dictionary containing all of the bits of the URL IDictionary<string, string> url = new Dictionary<string, String>(); url["Service"] = "AWSECommerceService"; url["Version"] = "2011-08-01"; url["Operation"] = "ItemLookup"; url["IdType"] = "UPC"; url["SearchIndex"] = "All"; url["ItemId"] = UPC; url["ResponseGroup"] = "Large"; url["AssociateTag"] = "AssociateTag=openlibrary07-20"; //Pass dictionary to helper, get the signed URL back out as a string string signedUrl = helper.Sign(url); return signedUrl; }
//Method to do an ISBN-based lookup and return the signed URL public static string lookup(string ISBN) { //Helper signs the requests SignedRequestHelper helper = new SignedRequestHelper(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY, DESTINATION); //Helper looks for a dictionary containing all of the bits of the URL IDictionary<string, string> url = new Dictionary<string, String>(); url["Service"] = "AWSECommerceService"; url["Version"] = "2011-08-01"; url["Operation"] = "ItemLookup"; url["ItemId"] = ISBN; url["ResponseGroup"] = "Large"; url["AssociateTag"] = "AssociateTag=openlibrary07-20"; //Pass dictionary to helper, get the signed URL back out as a string string signedUrl = helper.Sign(url); return signedUrl; }
public String getReqUrl(Page page, string keywords, string cat, string key1, string key2) { AWS_ACCESS_KEY_ID_IDENTIFIER = key1; AWS_SECRET_KEY_IDENTIFIER = key2; // Initializing variables SignedRequestHelper helper = new SignedRequestHelper(AWS_ACCESS_KEY_ID_IDENTIFIER, AWS_SECRET_KEY_IDENTIFIER, DESTINATION); String reqUrl; XElement xmldoc = null; byte[] bArray; //Store all the keywords to be searched in string array String[] Keywords = new String[] { keywords, }; // Creating request string foreach (String keyword in Keywords) { String reqString = "Service=AWSECommerceService" + "&Version=2013-04-04" + "&Operation=ItemSearch" + "&AssociateTag=net4ccsneue02-20" + "&SearchIndex=" + cat + "&MinimumPrice=10000" + "&MaximumPrice=50000" + "&Sort=relevancerank" + "&ResponseGroup=ItemAttributes, Variations, Offers" + "&MerchantId=All" + "&Keywords=" + keyword; // Calling sign method to sign the request url with signature reqUrl = helper.Sign(reqString); // Create POST data and convert it to a byte array. int endptlen = ENDPT.Length; string cont = reqUrl.Substring(endptlen + 1); bArray = Encoding.UTF8.GetBytes(cont); // Sending HTTP POST request to web service and returning response will be an Xml document try { // Create a request using a URL that can receive a post request. WebRequest req = HttpWebRequest.Create(ENDPT); req.Method = "POST"; req.ContentLength = bArray.Length; req.ContentType = "application/x-www-form-urlencoded"; // Get the request stream. Stream data_stream = req.GetRequestStream(); data_stream.Write(bArray, 0, bArray.Length); data_stream.Close(); // get the web response WebResponse resp = req.GetResponse(); XmlDocument doc = new XmlDocument(); Stream responseStream = resp.GetResponseStream(); doc.Load(responseStream); XmlElement root = doc.DocumentElement; string xml = root.InnerXml; string fxml = "<root>" + xml + "</root>"; TextReader tr = new StringReader(fxml); XElement lroot = XElement.Load(tr); return(fxml); } catch (Exception e) { System.Console.WriteLine("Exception Found : " + e.Message); System.Console.WriteLine("Stack Trace: " + e.StackTrace); } return(reqUrl); } return("not init"); }
/// <summary> /// Retrieve Album Info using Amazon Web Services /// </summary> /// <returns></returns> public bool GetAlbumInfo() { _AbortGrab = false; _AlbumInfoList.Clear(); bool result = true; try { if (_ArtistName.Length == 0 && _AlbumName.Length == 0) { return false; } DateTime startTime = DateTime.Now; // Build up a valid request BassRegistration.SignedRequestHelper helper = new SignedRequestHelper("com"); // Use "US" site for cover art search string requestString = helper.Sign(string.Format(itemSearch, System.Web.HttpUtility.UrlEncode(_ArtistName), System.Web.HttpUtility.UrlEncode(_AlbumName))); // Connect to AWS HttpWebRequest request = null; try { request = (HttpWebRequest)WebRequest.Create(requestString); try { // Use the current user in case an NTLM Proxy or similar is used. request.Proxy.Credentials = CredentialCache.DefaultCredentials; } catch (Exception) {} } catch (Exception e) { Log.Error("Cover Art grabber: Create request failed: {0}", e.Message); return false; } // Get Response from AWS HttpWebResponse response = null; string responseXml = null; try { response = (HttpWebResponse)request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { responseXml = reader.ReadToEnd(); } } } catch (Exception e) { Log.Error("Cover Art grabber: Get Response failed: {0}", e.Message); return false; } finally { if (response != null) { response.Close(); } } if (responseXml == null) { Log.Debug("Cover Art grabber: No data found for: {0} - {1}", _ArtistName, _AlbumName); return false; } XmlDocument xml = new XmlDocument(); xml.LoadXml(responseXml); // Retrieve default Namespace of the document and add it to the NameSpacemanager string defaultNameSpace = xml.DocumentElement.GetNamespaceOfPrefix(""); XmlNamespaceManager nsMgr = new XmlNamespaceManager(xml.NameTable); nsMgr.AddNamespace("ns", defaultNameSpace); XmlNodeList nodes = xml.SelectNodes("/ns:ItemSearchResponse/ns:Items/ns:Item", nsMgr); if (nodes.Count == 0) { Log.Debug("Cover Art grabber: No data found for: {0} - {1}", _ArtistName, _AlbumName); return false; } int imgCount = 0; int totResults = nodes.Count; bool resultsLimitExceeded = false; Log.Info("Cover Art grabber: AWS Response Returned {1} total results.", totResults); // Now loop through all the items and extract the data foreach (XmlNode node in nodes) { // Yield thread... Thread.Sleep(1); GUIWindowManager.Process(); CheckForAppShutdown(); if (resultsLimitExceeded || _AbortGrab) { break; } if (_MaxSearchResultItems != -1 && imgCount >= _MaxSearchResultItems) { resultsLimitExceeded = true; break; } AlbumInfo albumInfo = FillAlbum(node); _AlbumInfoList.Add(albumInfo); ++imgCount; DoProgressUpdate(imgCount, totResults); } string resultsText = ""; if (_AbortGrab) { resultsText = string.Format("AWS album cover art grab aborted by user before completetion. Retreived {0}/{1} records", imgCount, totResults); } else if (resultsLimitExceeded) { resultsText = string.Format("AWS retreived {0}/{1} records (max search limit set to {2} images)", imgCount, totResults, _MaxSearchResultItems); } else { resultsText = string.Format("{0} records retrieved", imgCount); } DateTime stopTime = DateTime.Now; TimeSpan elapsedTime = stopTime - startTime; double totSeconds = elapsedTime.TotalSeconds; float secondsPerImage = (float)totSeconds / (float)imgCount; string et = ""; if (imgCount > 0) { if (_AbortGrab) { et = string.Format("{0:d2}:{1:d2}:{2:d2}.{3:d3} ({4:f3} seconds per image)", elapsedTime.Hours, elapsedTime.Minutes, elapsedTime.Seconds, elapsedTime.Milliseconds, secondsPerImage); } else { et = string.Format("in {0:d2}:{1:d2}:{2:d2}.{3:d3} ({4:f3} seconds per image)", elapsedTime.Hours, elapsedTime.Minutes, elapsedTime.Seconds, elapsedTime.Milliseconds, secondsPerImage); } Log.Info("Cover art grabber:{0} {1}", resultsText, et); } } catch (Exception ex) { //string errMsg = string.Format("GetAlbumInfoAsync caused an exception: {0}\r\n{1}\r\n", ex.Message, ex.StackTrace); Log.Info("Cover art grabber exception:{0}", ex.ToString()); result = false; } //_GrabberRunning = false; if (FindCoverArtDone != null) { FindCoverArtDone(this, EventArgs.Empty); } return result; }
//Method to do an ISBN-based lookup and return the signed URL public static string lookup(string track, string album, string artist) { string signedUrl = ""; try { APIsettings set = new APIsettings(); ArrayList parsed = new ArrayList(); parsed = set.parse(); string MY_AWS_ACCESS_KEY_ID = parsed[0].ToString(), MY_AWS_SECRET_KEY = parsed[1].ToString(); //Helper signs the requests SignedRequestHelper helper = new SignedRequestHelper(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY, DESTINATION); //Helper looks for a dictionary containing all of the bits of the URL IDictionary<string, string> url = new Dictionary<string, String>(); url["Service"] = "AWSECommerceService"; url["Version"] = "2011-08-01"; url["Operation"] = "ItemSearch"; url["Keywords"] = track + ", " + album + ", " + artist; url["SearchIndex"] = "MP3Downloads"; url["ResponseGroup"] = "Large"; url["AssociateTag"] = "AssociateTag=openlibrary07-20"; //Pass dictionary to helper, get the signed URL back out as a string signedUrl = helper.Sign(url); return signedUrl; } catch { MessageBox.Show("Unfortunately, music preview isn't available for this track."); } return signedUrl; }
//別スレッド protected bool setTitleConvIsbn_Impl(TextBox textbox, BarcodeType type) { string code = textbox.Text; SignedRequestHelper helper = new SignedRequestHelper("test", "test", "ecs.amazonaws.jp"); IDictionary <string, string> requestParams = new Dictionary <string, String>(); requestParams["Service"] = "AWSECommerceService"; requestParams["Version"] = "2009-11-01"; requestParams["Operation"] = "ItemLookup"; requestParams["ItemId"] = code; if (type == BarcodeType.Isbn) { requestParams["IdType"] = "ISBN"; } //else if (type == BarcodeType.Jan) else { requestParams["IdType"] = "EAN"; } requestParams["SearchIndex"] = "All"; string url = helper.Sign(requestParams); System.Diagnostics.Debug.WriteLine(url); System.Net.WebClient webc = new System.Net.WebClient(); using (Stream st = webc.OpenRead(url)) { if (st == null) { return(false); } using (StreamReader sr = new StreamReader(st, Encoding.UTF8)) { XmlDocument xdoc = new XmlDocument(); xdoc.Load(sr); XmlNodeList xlist = xdoc.GetElementsByTagName("Title", @"http://webservices.amazon.com/AWSECommerceService/2009-11-01"); if (xlist.Count > 0) { XmlNode xtitle = xlist.Item(0); ControlUtil.SafelyOperated(this, (MethodInvoker) delegate() { textbox.Text = xtitle.InnerText; }); return(true); } } } ControlUtil.SafelyOperated(this, (MethodInvoker) delegate() { // cell.DataGridView[ColumnName.isbn, cell.RowIndex].Value = null; }); return(false); }