I`m relatively new to programming and I´m completely new to Stack overflow, so please be patient with me! Currently I work on a ASP.NET MVC project including the Ebay finding API.
The goal i want to accomplish is to create a Website on which you can search for different articles on Ebay and being able to use certain filters using the Ebay finding API. This is a training projekt for me, as the C# part of the whole thing is a good practice in my opinion. Unfortunately I´m stuck with the whole API connection to ebay part and havent done any C# programming myself.
Frankly i have no idea what im doing and I hope some of you may have an idea or some tips for me. I know I might be vague and I´m sorry, but i´m just at the beginning of programming.
What have i done so far?
I already registered on the ebay developers program and I already have my App ID, the Dev IDm the Cert ID and a Token.
Important: I currently only work with the sandbox!
I found a piece of code online which I´m using, but now im stuck. Obisously i filled in the IDs and the token but deleted it for this post. In the "Index" class at the end of my piece of code I entered the ID of a random Ebay article for testing purposes. When i debug I get this Exception:
"eBay.Service.Core.Sdk.ApiException: 'This item cannot be accessed because the listing has been deleted, is a Half.com listing, or you are not the seller."
I would really appreciate if someone can show me how to do it correctly or push me in the right direction. I have to admit that i find the whole Ebay API documentation etc. to be very confusing and I dind´t find any advice on how to start. I take any advice you guys can give me!
Here is the code I found and used so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Windows.Forms;
using System.Resources;
using eBay.Service.Call;
using eBay.Service.Core.Sdk;
using eBay.Service.Core.Soap;
namespace Ebay_API_Neu.Controllers
{
public class HomeController : Controller
{
public GetItemCall getItemDataFromEbay(String itemId)
{
ApiContext oContext = new ApiContext();
oContext.ApiCredential.ApiAccount.Developer = "//dev ID"; // use your dev ID
oContext.ApiCredential.ApiAccount.Application = "//App ID"; // use your app ID
oContext.ApiCredential.ApiAccount.Certificate = "//cert ID"; // use your cert ID
oContext.ApiCredential.eBayToken = "//Token"; //set the AuthToken
oContext.SoapApiServerUrl = "https://api.sandbox.ebay.com/wsapi";
//set the Site of the Context
oContext.Site = eBay.Service.Core.Soap.SiteCodeType.Germany;
//the WSDL Version used for this SDK build
oContext.Version = "735";
//very important, let's setup the logging
ApiLogManager oLogManager = new ApiLogManager();
oLogManager.ApiLoggerList.Add(new eBay.Service.Util.FileLogger("GetItem.log", true, true, true));
oLogManager.EnableLogging = true;
oContext.ApiLogManager = oLogManager;
GetItemCall oGetItemCall = new GetItemCall(oContext);
//' set the Version used in the call
oGetItemCall.Version = oContext.Version;
//' set the Site of the call
oGetItemCall.Site = oContext.Site;
//' enable the compression feature
oGetItemCall.EnableCompression = true;
oGetItemCall.DetailLevelList.Add(eBay.Service.Core.Soap.DetailLevelCodeType.ReturnAll);
oGetItemCall.ItemID = itemId;
try
{
oGetItemCall.GetItem(oGetItemCall.ItemID);
}
catch (Exception E)
{
Console.Write(E.ToString());
oGetItemCall.GetItem(itemId);
}
GC.Collect();
return oGetItemCall;
}
public ActionResult Index()
{
getItemDataFromEbay("173354849991");
return View();
}
From the error you are getting I would guess that you are trying to get information regarding a "random listing" you have not entered yourself on the eBay sandbox. In order to use GetItem the listing you are retrieving has to have been created using your sandbox user id.
Take a look at the below link to API doc for GetItem() - specifically the requirements for "Testing GetItem". If you think I might be correct then try creating a listing in the sandbox using either the Web Interface or eBay API AddItem() before retrieving it with GetItem().
https://developer.ebay.com/devzone/xml/docs/reference/ebay/getitem.html
Related
Preface:
This is a part of my personal project of building a control GUI for several communication devices - using WinForms unfortunately.
The part of code running into trouble is rested inside the Constructor of a Form.
Additional NuGet packages installed are: Newtonsoft.Json, RestSharp, SpecFlow and SpecFlow.Assist.Dynamic.
LoginForm and SeatsInfo are two basic classes created only to store and organize my data, they have no additional coding besides properties declartions.
Execution code:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CONTROL_UI
{
public partial class RunningConfig : Form
{
public RunningConfig()
{
InitializeComponent();
var client = new RestClient("CLIENT_URL");
var loginRequest = new RestRequest("api/login", Method.POST);
loginRequest.RequestFormat = DataFormat.Json;
loginRequest.AddHeader("Content-type", "application/json");
loginRequest.AddJsonBody(new LoginForm() { username = "admin", password = "", #override = true });
var loginRespone = client.Execute(loginRequest);
JObject sessionInfo = JObject.Parse(loginRespone.Content);
var sessionID = sessionInfo["sid"];
var seatAvailRequest = new RestRequest("api/seats", Method.GET);
seatAvailRequest.AddHeader("sid", sessionID.ToString());
seatAvailRequest.AddHeader("Cookie", "sid = " + sessionID.ToString());
var seatResponse = client.Execute(seatAvailRequest);
List<SeatsInfo> seatsInfo = JsonConvert.DeserializeObject<List<SeatsInfo>>(seatResponse.Content);
//Further Implementation
}
}
}
Expected packet view in WireShark:
Actual packet view in WireShark:
sids are generated each time I successfully authorized to connect to the device, so they obviously differ.
The screenshot of my expected view is taken from the exact same block of codes in a plain console app. Everything works fine there. All the NuGet packages installed on the two programmes are of the same version, I even tried running them side-by-side but it did not help.
Debugging screenshots showed that the Parameters did, in fact, contain the Cookie header:
The header just did not go through for some reason. Would love to hear some thoughts in regards to this issue, many thanks in advance!
Current solution, just add another AddCookie() method:
seatAvailRequest.AddHeader("sid", sessionID.ToString());
seatAvailRequest.AddHeader("Cookie","sid = " + sessionID.ToString());
seatAvailRequest.AddCookie("sid", sessionID.ToString());
This somehow does not work with just AddCookie() or AddHeader(), so for now they are both going in. Hope this helps someone, and thank yall for reading!
So, in recap I was lacking the Cookie Header in the API call thus making the call being unsuccessful (the device did not authorized it).
After messing around with the AddCookie() method, particularly:
seatAvailRequest.AddCookie("sid", sessionID.ToString());
The device gave me a different error - 404 Not Found, before was 401 Unauthorized:
Finally my dumb mind resorted using both the AddCookie() along with AddHeader() and voilà:
It works! Only after 5 hours of painful debugging and mind-numbing searches. Although the new packet is a bit larger, but I do not have to worry about that for now, or in the future realistically speaking.
Thanks you all for just following along, still open for suggestions and improvements!
Me and a friend had an idea to build some kind of web-scraping software and eventually we settled for a mobile app (Android). The main idea is: We provide the user with a list of music festivals, the user selects one and when he does, a list of the current confirmed artists for that festival is displayed (we want it to display an up-to-date list). The list is retrieved via python scripts (note that the goal is not deployment or profit (at least right now), thus this very summarized explanation).
My question is, how would I go about integrating the python scripts with the mobile application? At this moment I know you can call them with C# but I'm not sure if that would work on a mobile environment. Plus I saw someone saying one should host the scripts on a web server and then execute them via API calls but the person didn't expand and I'm not sure how to do that.
Any insight on the matter or useful references would be helpful.
Thanks!
You can do it in C# using HttpClient and HtmlAgilityPack;
You would need:
using System.Net.Http;
using HtmlAgilityPack;
Make methods like this:
public static HtmlNode GetNodeById(HttpClient client, string url, string divId)
{
string pageHtml = "";
using (HttpResponseMessage response = client.GetAsync(url).Result)
{
using (HttpContent content = response.Content)
{
pageHtml = content.ReadAsStringAsync().Result;
}
}
var doc = new HtmlDocument();
doc.LoadHtml(pageHtml);
HtmlNode node = doc.GetElementbyId(divId);
return node;
}
And call like this (where "musiciansDiv" is the div that contains the info your app needs):
static HttpClient client = new HttpClient();
var musicians = GetNodeById(client, "http://gigs.example.com", "musiciansDiv");
I have finally got the Amazon product advertising API to work on my MVC 5 site. I am using the "SignedRequestHelper" class that was provided on one of the downloads from the Amazon site. I have actually got a ref to the Amazon API but I do not seem to be using it at all at present.
What I am using so far is (controller):
SignedRequestHelper helper = new SignedRequestHelper("myAWSaccessKeyID",
"mysecretKey", "webservices.amazon.co.uk");
Dictionary<String, String> items = new Dictionary<String, String>();
items.Add("Service", "AWSECommerceService");
items.Add("Operation", "ItemSearch");
items.Add("AWSAccessKeyId", "myAWSaccessKeyID");
items.Add("AssociateTag", "myTag");
items.Add("SearchIndex", SearchIndex);//This is a string value (selectbox)
items.Add("ResponseGroup", "Images,ItemAttributes,OfferFull,Offers,OfferSummary,Reviews");
items.Add("Keywords", keyword);//This is a string value
string requestUrl = helper.Sign(items);
ViewBag.Stuff = requestUrl;//Just so I could see the whole URL!
WebRequest request = HttpWebRequest.Create(requestUrl);
WebResponse response = request.GetResponse();
XmlDocument doc = new XmlDocument();
doc.Load(response.GetResponseStream());
XmlNodeList titleNodes = doc.GetElementsByTagName("Item");
ViewBag.Titles = titleNodes;
You may notice I partially the copied the style of JAVA code from the scratch pad.
From that point on in the view I just deal with each part as it comes. It is kind of messy and horrid and dealing with switches like this:
foreach (System.Xml.XmlNode item in ViewBag.Titles)
{
<h3>Item: #count</h3>
foreach (System.Xml.XmlNode child in item.ChildNodes)
{
switch (child.Name)
{
case "ASIN":
<p>ASIN: #child.InnerText</p>
break;
case "MediumImage":
<img src="#child.ChildNodes[0].InnerText" />
break;
case "ItemAttributes":
foreach (System.Xml.XmlNode child1 in child.ChildNodes)
{
if(child1.Name == "Title")
{
<p>#child1.InnerText</p>
}
}
break;
}
}
count++;
}
It works and I can use the XML document etc. I just need to know if there is a way to change it so that it is actually using the API part that was given as a reference. I would rather use proper tools than do it with raw XML like this. I had such difficulty connecting with the Amazon documentation that I basically just tried to connect in the JAVA style code on Amazon's scratchpad.
You can use the following nuget Nager.AmazonProductAdvertising package.
PM> Install-Package Nager.AmazonProductAdvertising
Example Controller
public ActionResult ProductSearch(string search)
{
var authentication = new AmazonAuthentication();
authentication.AccessKey = "accesskey";
authentication.SecretKey = "secretkey";
var wrapper = new AmazonWrapper(authentication, AmazonEndpoint.DE);
var result = wrapper.Search(search);
return View(result);
}
Example View
#model Nager.AmazonProductAdvertising.Model.AmazonItemResponse
#{
ViewBag.Title = "Search";
}
<table class="table">
<tr>
<th>ASIN</th>
<th>SalesRank</th>
</tr>
#foreach (var item in Model.Items.Item)
{
<tr>
<td>#item.ASIN</td>
<td>#item.SalesRank</td>
</tr>
}
</table>
Take a look to AWS SDK for .Net. Also you can find some guides and how to work with it's APIs.
The AWS SDK for .NET includes the following:
The current version of the AWS SDK for .NET.
All previous major versions of the AWS SDK for .NET.
Sample code that demonstrates how to use the AWS SDK for .NET with several AWS services.
There is a library that is incredibly thorough for dealing with the Amazon Product Advertising API (PAAPI). When you make a request, you can receive a variety of responses, but this library can handle them all! It reads the XML and puts all the information in an object.
I'm working on two MVC 5 sites right now that interact with the PAAPI. I have a separate folder with the files and a couple files I wrote to make requests and process responses by pulling the data I need out of the object created by the library.
I made a C# console app demo, and you can view it here:
https://github.com/zoenberger/AmazonProductAdvertising
I used this for guidance:
https://flyingpies.wordpress.com/2009/08/01/17/
However, I ran into a couple errors:
In some instances, large responses require you to modify the
MaxReceivedMessageSize and is show on the demo.
I ran into an error with the ImageSets[] in the library. May people have and the fix is here.
I believe that I have finally found a way to use the actual Amazon Prod Adv API now. The problem was working out how to sign the request using the latest API (that I had added as a reference). The reference was added in a similar way to the getting started guide even though that was making reference to VS2005. That is obviously 10 years old but I somehow did get it working with a bit of problem solving. I just never got the signing correct so I ended up using that horrid REST bodge (in my original question)!
The post that has helped me now is this one:
amazon product advertising api - item lookup request working example
It is the one marked as the answer. It has only 4 up-votes but it is the best thing I have found. I put all the classes into the controller to test it but I will now have to do it properly using models or extension classes. It worked anyway though.
I'm usinng skybrud social to allow users to log into my site via Facebook, but am having a problem.
For some reason, the response never contains anything other than the Name and Id of the user... everything else is null.
var url = client.GetAuthorizationUrl(state, "public_profile", "email");
var service = FacebookService.CreateFromAccessToken(userAccessToken);
FacebookMeResponse user = service.Methods.Me();
Has anyone experienced this before? What could be the problem?
Facebook has multiple versions of their Graph API. In the most recent version (2.4), less fields are returned by default, and you instead have to tell the API to return the fields that you need. What version of the API you're using depends on the time you registered your app with Facebook.
Based on your code, it seems that you're using an older version of Skybrud.Social. If you update to the most recent version (0.9.4.1), you can do something like this:
// Declare the options for the call to the API
FacebookGetUserOptions options = new FacebookGetUserOptions("me") {
Fields = "name,email,gender"
};
// Make the call to the API
FacebookUserResponse response = service.Users.GetUser(options);
Hope this answers your questions ;)
Using OAuth I do get access token from Google. The sample that comes with Google and even this one:
http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.SimpleOAuth2/Program.cs?repo=samples
show how to use Tasks API. However, I want to use Calendar API. I want to get access to user's calendar. Can anybody tell me how do I do that?
Take a look at the samples:
Getting Started with the .NET Client Library
On the right side of the page linked above there is a screen shot showing the sample projects contained in the Google Data API solution. They proofed to be very helpful (I used them to start my own Google Calendar application).
I recommend keeping both your own solution and the sample solution open. This way you can switch between the examples and your own implementation.
I also recommend to use the NuGet packages:
Google.GData.AccessControl
Google.GData.Calendar
Google.GData.Client
Google.GData.Extensions
and more ...
This way you easily stay up to date.
Sample to get the users calendars:
public void LoadCalendars()
{
// Prepare service
CalendarService service = new CalendarService("Your app name");
service.setUserCredentials("username", "password");
CalendarQuery query = new CalendarQuery();
query.Uri = new Uri("https://www.google.com/calendar/feeds/default/allcalendars/full");
CalendarFeed calendarFeed = (CalendarFeed)service.Query(query);
Console.WriteLine("Your calendars:\n");
foreach(CalendarEntry entry in calendarFeed.Entries)
{
Console.WriteLine(entry.Title.Text + "\n");
}
}