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; }
/// <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); }
// 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); }
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); }
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> /// 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); }
/// <summary> /// Sets up the Model including the PageSize. Includes the Amazon /// key information for this application. /// </summary> /// <param name="virtualPageSize">the number of items to keep in the /// internal virtual page. This helps with displaying category items to the user.</param> public Model(int virtualPageSize) { // TODO: get keys from the website Amazon = new SignedRequestHelper( Constants.AMAZON_ACCESS_KEY, Constants.AMAZON_SECRET_KEY, Constants.AMAZON_BASE_URL); Breadcrumbs = new List<Category>(); PageIndex = 0; PageSize = virtualPageSize; }
private BookCache() { _books = new Dictionary<string, Book>(); _textSearches = new Dictionary<string, List<Book>>(); _similaritySearches = new Dictionary<string, List<Book>>(); _requestSigner = new SignedRequestHelper(Constants.MY_AWS_ACCESS_KEY_ID, Constants.MY_AWS_SECRET_KEY, DESTINATION); //load up any information present in the secondary cache SecondaryCache.Instance.LoadCache(_books, _textSearches, _similaritySearches); }
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 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(); }
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); }
//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 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(); }
public async Task<IEnumerable<AmazonProduct>> SimilarItems(string ASIN, Func<string, Task<XDocument>> retrievalfunc = null) { requestparameters["Operation"] = "SimilarityLookup"; requestparameters["ItemId"] = ASIN; requestparameters["ResponseGroup"] = "Images,Offers,OfferSummary,Small"; string url = new SignedRequestHelper(_awskey, _awsSecretKey, _destination).Sign(requestparameters); XNamespace ns = _xmlnamespace; if (retrievalfunc == null) retrievalfunc = InvokeAmazonService; var xml = await retrievalfunc(url); var items = xml.Descendants(ns + "Item").Where((elem) => elem.Descendants(ns + "OfferListingId").Count() != 0) .Select((e) => e.ToAmazonProduct(ns)); return items; }
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); }
public async Task<IEnumerable<AmazonProduct>> ItemLookup(string[] productids, string responsegroup, Func<string, Task<XDocument>> retrievalfunc = null) { requestparameters["Operation"] = "ItemLookup"; requestparameters["ItemId"] = string.Join(",", productids); requestparameters["ResponseGroup"] = responsegroup; string url = new SignedRequestHelper(_awskey, _awsSecretKey, _destination).Sign(requestparameters); XNamespace ns = _xmlnamespace; if (retrievalfunc == null) retrievalfunc = InvokeAmazonService; var xml = await retrievalfunc(url); var items = xml.Descendants(ns + "Item").Where((elem) => elem.Descendants(ns + "OfferListingId").Count() != 0) .Select((e) => e.ToAmazonProduct(ns)); return items; }
public async Task<AmazonProduct> ItemDetails(string ASIN, Func<string, Task<XDocument>> retrievalfunc = null) { requestparameters["Operation"] = "ItemLookup"; requestparameters["ItemId"] = ASIN; requestparameters["ResponseGroup"] = "Images,ItemAttributes,Offers,EditorialReview,OfferFull"; string url = new SignedRequestHelper(_awskey, _awsSecretKey, _destination).Sign(requestparameters); XNamespace ns = _xmlnamespace; if (retrievalfunc == null) retrievalfunc = InvokeAmazonService; var xml = await retrievalfunc(url); var items = xml.Descendants(ns + "Item").Where((elem) => elem.Descendants(ns + "OfferListingId").Count() != 0) .Select((e) => e.ToAmazonProduct(ns)); return items.First(); }
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; }
/// <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 AmazonSwapImportManager() { try { // Inizializza parametri Amazon ACCESS_KEY_ID = ConfigurationManager.AppSettings["amazon:credentials:accessKeyId"]; SECRET_KEY = ConfigurationManager.AppSettings["amazon:credentials:secretKey"]; ASSOCIATE_TAG = ConfigurationManager.AppSettings["amazon:store:associateTag"]; ENDPOINT = ConfigurationManager.AppSettings["amazon:store:endpoint"]; helper = new SignedRequestHelper(ACCESS_KEY_ID, SECRET_KEY, ENDPOINT); } catch (Exception) { //log here! return; } }
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)); }
/// <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; }
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); }
//非同期メソッド。呼び出すときは呼び出し側でイベントハンドラー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); }
//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; }
/// <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 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; }
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); }
/// <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 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 async Task<AmazonShoppingCart> AddToCart(string secondOfferlistingId, string asin, string cartId, string Hmac, Func<string, Task<XDocument>> funcForAddToCart = null) { XNamespace ns = _xmlnamespace; string url = string.Empty; requestparameters = PrepareRequestParameters(secondOfferlistingId, cartId, Hmac); url = new SignedRequestHelper(_awskey, _awsSecretKey, _destination).Sign(requestparameters); if (funcForAddToCart == null) funcForAddToCart = InvokeAmazonService; var xml = await funcForAddToCart(url); var Cart_CreateDetails = ParseCartCreateAndCartAddXml(ns, xml); return Cart_CreateDetails; }
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"); }
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); }
public async Task<AmazonSearchResult> ItemSearch(string userInput, string responsegroup, int pageNumber = 0, Func<string, Task<XDocument>> retrievalfunc = null) { requestparameters["Operation"] = "ItemSearch"; requestparameters["SearchIndex"] = "All"; requestparameters["Keywords"] = userInput; requestparameters["ResponseGroup"] = responsegroup; if (pageNumber>0) { requestparameters["ItemPage"] = Convert.ToString(pageNumber); } string url = new SignedRequestHelper(_awskey, _awsSecretKey, _destination).Sign(requestparameters); System.Xml.Linq.XDocument xml = null; XNamespace ns = _xmlnamespace; if (retrievalfunc == null) retrievalfunc = InvokeAmazonService; xml = await retrievalfunc(url); var items = xml.Descendants(ns + "Item") .Where((elem) => elem.Descendants(ns + "OfferListingId").Count() != 0) .Select((e) => e.ToAmazonProduct(ns)); var count = xml.Descendants(ns + "Items").Select(p => p.Element(ns + "TotalPages") == null ? string.Empty : p.Element(ns + "TotalPages").Value).FirstOrDefault(); var amazonSearchItems = ConvertToAmazonSearch(items); amazonSearchItems.TotalPages = Convert.ToInt32(count); return amazonSearchItems; }
/// <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); }
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); }
//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; }
//別スレッド 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); }
//別スレッド protected bool setTitleConvBarcode_Impl(DataGridViewCell cell, BarcodeType type) { if (cell.DataGridView.Columns[cell.ColumnIndex].Name != ColumnName.shouhinMei) { throw new Exception("商品名の列以外ではISBN/JANサーチはできません"); } string code = (string)cell.Value; SignedRequestHelper helper = new SignedRequestHelper("13R1P6WSEW5Y6CP6MVR2", "yv69PdUY09Mosx/k4T9mwiP2xbcDZG6HMF4fsNuX", "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() { cell.DataGridView[ColumnName.isbn, cell.RowIndex].Value = decimal.Parse(code); cell.Value = xtitle.InnerText; }); return(true); } } } ControlUtil.SafelyOperated(this, (MethodInvoker) delegate() { cell.DataGridView[ColumnName.isbn, cell.RowIndex].Value = null; }); return(false); }
public static List <Results> Search(string keywords, string searchIndex, int page) { keywords = keywords.Replace(" ", "+"); bool jargmine = false; SignedRequestHelper otsi = new SignedRequestHelper("AKIAJESQ6QJNRFAC2G7A", "MfLQGWTUqYQuDNF/tiqeerZDJ1Tjs5PWEKZLcivA", "ecs.amazonaws.com"); List <Results> tooted = new List <Results> (); int esimene = 1 + ((page - 1) * 13); //1 int leht = (esimene - 1) / 10 + 1; //1 XmlDocument doc = FetchPage(searchIndex, keywords, leht, otsi); string number = doc.GetElementsByTagName("TotalResults", NAMESPACE).Item(0).InnerText; int numVal = Int32.Parse(number); if (numVal > 100) { numVal = 100; } if (searchIndex == "All") { if (numVal > 50) { numVal = 50; } } int jargi; int alates = esimene - (10 * (leht - 1)); if (numVal > (esimene + 12)) { jargmine = true; jargi = 13; } else { jargi = numVal - esimene + 1; } float hind; while (true) { for (int i = alates - 1; i < 10; i++) { XmlNode node = doc.GetElementsByTagName("OfferSummary", NAMESPACE).Item(i); //string ID = doc.GetElementsByTagName ("ASIN", NAMESPACE).Item (i).InnerText; try{ hind = float.Parse(node.ChildNodes[0].ChildNodes[0].InnerText) / 100; } catch { hind = 0; } //XmlDocument doc2 = FetchItem(ID, otsi); string nimi, link; try{ nimi = doc.GetElementsByTagName("Title", NAMESPACE).Item(i).InnerText; } catch { nimi = "nimi"; } try{ link = doc.GetElementsByTagName("DetailPageURL", NAMESPACE).Item(i).InnerText; } catch { link = "link"; } tooted.Add(new Results() { link = link, nimi = nimi, hind = hind }); jargi--; if (jargi == 0) { break; } } alates = 1; leht++; if (jargi == 0) { break; } doc = FetchPage(searchIndex, keywords, leht, otsi); } if (jargmine == true) { tooted.Add(new Results() { nimi = "Järgmine leht", link = "results?SearchIndex=" + searchIndex + "&Search=" + keywords + "&Page=" + (page + 1), hind = 0 }); } return(tooted); }
public EdelweissLoader(SignedRequestHelper h) { m_helper=h; }
public async Task<AmazonShoppingCart> GetCart(string cartId, string hmac, Func<string, Task<XDocument>> funcForAddToCart = null) { XNamespace ns = _xmlnamespace; string url = string.Empty; requestparameters["ResponseGroup"] = ""; requestparameters.Remove("ResponseGroup"); requestparameters["Operation"] = "CartGet"; requestparameters["HMAC"] = hmac; requestparameters["CartId"] = cartId; url = new SignedRequestHelper(_awskey, _awsSecretKey, _destination).Sign(requestparameters); if (funcForAddToCart == null) funcForAddToCart = InvokeAmazonService; var xml = await funcForAddToCart(url); var Cart_CreateDetails = ParseGetCartResponse(ns, xml); return Cart_CreateDetails; }
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; } } }
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 })); }