Entries:
Comments:
Posts:

Loading User Information from Channel 9

Something went wrong getting user information from Channel 9

Latest Achievement:

Loading User Information from MSDN

Something went wrong getting user information from MSDN

Visual Studio Achievements

Latest Achievement:

Loading Visual Studio Achievements

Something went wrong getting the Visual Studio Achievements

Building a Custom eBay Watch List Using the SOAP API

  Keeping a track on changes on eBay using its web service.
Alan Lewis

Difficulty: Easy
Time Required: 1-3 hours
Cost: Free
Software: Visual Studio Express Editions, eBay web service
Hardware:
Download:

If you're like me, you're always keeping an eye on what's happening on eBay. Whenever I find something that I'm interested in tracking, I use eBay's Watch List feature to remember it for me. However, I find when I'm watching lots of items it's not so easy to sort, filter, and display them as I want. That's where eBay Web Services comes in. What I did was write a program to retrieve all my watch list items using SOAP. Now I have complete control to customize the display and add the feature I want to the interface.

In this article I'll walk you how I did this using ASP.NET 2.0. You'll learn the basics of eBay Web Services and see how easy it is to customize eBay.

Getting Registered with eBay

To get started, register with the eBay Developers Program. Signing up for the program gives you access to the Sandbox, eBay's test environment that allows you to test your applications before taking them live. For this example, we want to pull down the real eBay Watch List data, so you need to get access to eBay's production environment. Register for access to the production eBay environment by submitting the Self-Certification Form. Once you complete this form you'll receive an email with instructions on how to retrieve your production developer keys. Follow those instructions, and once you've retrieved your keys save them in a text file for later use.

Once you have access to the production environment, create an authentication token for your eBay username by going to http://cgi1.ebay.com/aw-cgi/eBayISAPI.dll?RegisterShow&ru=http%3A//www.ebay.com. (Sign up for eBay first if you haven't done so.) eBay Web Services uses authentication tokens for user authentication to keep your user data secure. This system allows authorized third party applications to make Web Services calls on your behalf without those third parties having access to your eBay username and password. Use the Single User Authentication Token tool to create an authentication token for your test user. In the tool, select the Production environment and enter the production developer keys you retrieved earlier. Go through the flow, and when you're done save the authentication token in the same place as you saved your developer keys.

Accessing the eBay Web Service

Now that you have all of that stuff out of the way, we're ready to go. eBay offers access to its web services through SOAP, XML, SDKs for .NET and Java, and even a REST API. For this example we'll be using the SOAP API. eBay exposes a WSDL file that you use to generate wrapper code for the SOAP API. In Visual Studio 2005 or Visual Web Developer 2005 Express Edition, first create a new Web Site, and then import the eBay WSDL file by right-clicking the web site root in the Solution Explorer, then selecting Add Web Reference...:

In the Add Web Reference dialog, load the WSDL URL:

http://developer.ebay.com/webservices/latest/eBaySvc.wsdl

Click here for larger image

(Click image to zoom)

It takes a few minutes to load the WSDL and generate the stubs from it. Once the WSDL is loaded, click Add Reference. If you get impatient with this process, just think: all this generated code is saving me time!

A Custom Watch List Web Form

The example we are creating displays the contents of your eBay watch list in a simple table. Create a new Web Form, and in the <div> element insert the following table:

<asp:Table BorderWidth="1" BorderStyle="Solid" ID="Table1" 
GridLines="Both" runat="server">
<asp:TableRow>
<asp:TableCell Text="Time Left" Width="90" Font-Bold="true"
HorizontalAlign="Center"></asp:TableCell>
<asp:TableCell Text="Title" Width="120" Font-Bold="true">
</asp:TableCell>
<asp:TableCell Text="Price" Width="65" Font-Bold="true"
HorizontalAlign="Center"></asp:TableCell>
<asp:TableCell Text="Item ID" Width="80" Font-Bold="true"
HorizontalAlign="Center"></asp:TableCell>
</asp:TableRow>
</asp:Table> 

The table headers are declared in the markup. The rest of the table rows with the watch list data will be added dynamically once the web service call is made.

The generated code allows you to make calls to any of the 100+ methods exposed by the eBay SOAP API. Once you have figured out how to make one eBay Web Service call, the rest is easy. The Page_Load method in the code behind file contains the following code that sets up the call (you'll find the complete code in the download that accompanies this article):

Visual C#

string endpoint = "https://api.ebay.com/wsapi";
string callName = "GetMyeBayBuying";
string siteId = "0";
string appId = "YOUR_APPID"; // use your app ID
string devId = "YOUR_DEVID"; // use your dev ID
string certId = "YOUR_CERTIFICATE"; // use your cert ID
string version = "437";
// Build the request URL
string requestURL = endpoint
+ "?callname=" + callName
+ "&siteid=" + siteId
+ "&appid=" + appId
+ "&version=" + version
+ "&routing=default";
// Create the service
eBayAPIInterfaceService service = new eBayAPIInterfaceService();
// Assign the request URL to the service locator.
service.Url = requestURL;
// Set credentials
service.RequesterCredentials = new CustomSecurityHeaderType();
service.RequesterCredentials.eBayAuthToken = "YOUR_TOKEN"; // use your token
service.RequesterCredentials.Credentials = new UserIdPasswordType();
service.RequesterCredentials.Credentials.AppId = appId;
service.RequesterCredentials.Credentials.DevId = devId;
service.RequesterCredentials.Credentials.AuthCert = certId;

Visual Basic

Dim endpoint As String = "https://api.ebay.com/wsapi"
Dim callName As String = "GetMyeBayBuying"
Dim siteId As String = "0"

Dim appId As String = "YOUR_APPID" 'TODO: Enter your AppID
Dim devId As String = "YOUR_DEVID" 'TODO: Enter your DevID
Dim certId As String = "YOUR_CERTIFICATE" 'TODO: Enter your CertID

Dim version As String = "437"

' Build the request URL
Dim requestURL As String = endpoint _
& "?callname=" & callName _
& "&siteid=" & siteId _
& "&appid=" & appId _
& "&version=" & version _
& "&routing=default"

' Create the service
Dim service As New eBayAPIInterfaceService()
With service
' Assign the request URL to the service locator.
.Url = requestURL
' Set credentials
.RequesterCredentials = New CustomSecurityHeaderType()
.RequesterCredentials.eBayAuthToken = "YOUR_TOKEN" 'TODO: Enter your production token
.RequesterCredentials.Credentials = New UserIdPasswordType()
With .RequesterCredentials.Credentials
.AppId = appId
.DevId = devId
.AuthCert = certId
End With
End With

Replace the "YOUR" strings with the developer keys and authentication token that you retrieved earlier. This code sets the SOAP header with the authentication information and creates the URL parameters that are passed in.

The one line in this code that will change from call to call is this:

Visual C# 

string callName = "GetMyeBayBuying"; 

Visual Basic

Dim callName As String = "GetMyeBayBuying"

For whatever call you are making, set the callName accordingly.

The GetMyeBayBuying call retrieves all sorts of information about items you have purchased, items in your watch list, items you are bidding on, and more. The call to GetMyeBayBuying is very simple:

Visual C# 

// Make the call to GetMyeBayBuying 
GetMyeBayBuyingRequestType buyingRequest = new GetMyeBayBuyingRequestType();
ItemListCustomizationType watchListOptions = new ItemListCustomizationType();
watchListOptions.Sort = ItemSortTypeCodeType.TimeLeft;
buyingRequest.WatchList = watchListOptions;
buyingRequest.Version = version;
GetMyeBayBuyingResponseType buyingResponse = service.GetMyeBayBuying(buyingRequest);
ItemType[] items = buyingResponse.WatchList.ItemArray;

Visual Basic

' Make the call to GetMyeBayBuying 
Dim buyingRequest As New GetMyeBayBuyingRequestType()
Dim watchListOptions As New ItemListCustomizationType()
watchListOptions.Sort = ItemSortTypeCodeType.TimeLeft
buyingRequest.WatchList = watchListOptions
buyingRequest.Version = version
Dim buyingResponse As GetMyeBayBuyingResponseType = _
service.GetMyeBayBuying(buyingRequest)
Dim items() As ItemType = buyingResponse.WatchList.ItemArray

The instance of GetMyeBayBuyingRequestType contains the call input options. To specify that we want to retrieve the contents of the watch list, we set the WatchList property with the ItemListCustomizationType options that we have created. We also set the Version property to the same version string as we are passing in the URL. The eBayAPIInterfaceService object contains a method for each call exposed by the SOAP API, and each method takes a "request type" object as a parameter. We pass in the request object that we've created and set the result to an instance of GetMyeBayBuyingResponseType. Finally, we extract the watch list items from the WatchList.ItemArray property of the response object, and set it to an array of ItemType.

Once we have retrieved the items, it is up to us to display the information we want or make further calculations:

Visual C# 

// Add table rows
for (int i = 0; i < items.Length; i++)
{
TableCell timeLeftCell = new TableCell();
DateTime endTime = items[i].ListingDetails.EndTime;
DateTime now = DateTime.Now;
// Display that the item has ended, or how much time is left
if (endTime < now)
{
timeLeftCell.Text = "Ended";
}
else
{
TimeSpan timeLeft = endTime - now;
string timeLeftDisplay = "";
int days = timeLeft.Days;
if (days > 0)
timeLeftDisplay += days.ToString() + " days, ";
int hours = timeLeft.Hours;
if (hours > 0)
timeLeftDisplay += hours.ToString() + " hours";
int minutes = timeLeft.Minutes;
if (minutes > 0 && days == 0)
timeLeftDisplay += ", " + minutes.ToString() + " min";
int seconds = timeLeft.Seconds;
if (days == 0 && hours == 0)
timeLeftDisplay += ", " + seconds.ToString() + " sec";
timeLeftCell.Text = timeLeftDisplay;
}
// Display the item title
TableCell titleCell = new TableCell();
titleCell.Text = items[i].Title;
// Display the current price
TableCell currentPriceCell = new TableCell();
currentPriceCell.Text = items[i].SellingStatus.CurrentPrice.Value.ToString();
// Display the Item ID
TableCell itemIDCell = new TableCell();
itemIDCell.Text = "<a href=\"http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item="
+ items[i].ItemID + "\">" + items[i].ItemID + "</a>";

TableRow row = new TableRow();
if ((i % 2) == 1)
{
row.BackColor = System.Drawing.Color.LightGray;
}
row.Cells.Add(timeLeftCell);
row.Cells.Add(titleCell);
row.Cells.Add(currentPriceCell);
row.Cells.Add(itemIDCell);

Table1.Rows.Add(row);
}

Visual Basic

' Add table rows
For i As Integer = 0 To items.Length - 1 Step i + 1
Dim timeLeftCell As New TableCell()
Dim endTime As DateTime = items(i).ListingDetails.EndTime
Dim now As DateTime = DateTime.Now

' Display that the item has ended, or how much time is left
If endTime < now Then
timeLeftCell.Text = "Ended"
Else
Dim timeLeft As TimeSpan = endTime - now
Dim timeLeftDisplay As String = String.Empty
Dim days As Integer = timeLeft.Days
If days > 0 Then
timeLeftDisplay &= days.ToString() & " days, "
End If

Dim hours As Integer = timeLeft.Hours
If hours > 0 Then
timeLeftDisplay &= hours.ToString() & " hours"
End If
Dim minutes As Integer = timeLeft.Minutes
If minutes > 0 And days = 0 Then
timeLeftDisplay &= ", " & minutes.ToString() & " min"
End If
Dim seconds As Integer = timeLeft.Seconds
If days = 0 And hours = 0 Then
timeLeftDisplay &= ", " & seconds.ToString() & " sec"
End If
timeLeftCell.Text = timeLeftDisplay
End If

' Display the item title
Dim titleCell As New TableCell()
titleCell.Text = items(i).Title

' Display the current price
Dim currentPriceCell As New TableCell()
currentPriceCell.Text = items(i).SellingStatus.CurrentPrice.Value.ToString()

' Display the Item ID
Dim itemIDCell As New TableCell()
itemIDCell.Text = "<a href=""http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=" _
& items(i).ItemID & """>" & items(i).ItemID & "</a>"

Dim row As New TableRow()
If (i Mod 2) = 1 Then
row.BackColor = System.Drawing.Color.LightGray
End If

With row.Cells
.Add(timeLeftCell)
.Add(titleCell)
.Add(currentPriceCell)
.Add(itemIDCell)
End With

Table1.Rows.Add(row)
Next

The most complex code in this example actually has nothing to do with the web service call: the end time is passed back as a DateTime, but we want to show how much time is left for each item. First, for items that have not already ended, we calculate a TimeSpan between now and the end time. Then, we apply some simple heuristics on that TimeSpan to create a more friendly string representation. Modern platforms like .NET make it easy to get data from web services, so you'll often find yourself spending much more time manipulating the data that you've retrieved.

Each cell in the table row is represented by a TableCell object. For each field in each item that we retrieve, a TableCell is created and its Text property is populated with what we want to display. We then create a TableRow object and call the Add method on its Cells property. And last, we add the row to the Rows property on the Table1 object that is declared on the form.

That's it! With one simple form and little more than 100 lines of code, you have a working application that integrates with eBay Web Services to do something useful. In a future article I'll show you how to integrate other calls and use more sophisticated XML processing to add unique features not available in the standard eBay watch list.

Follow the Discussion

  • Clint RutkasClint I'm a "developer"

    Looks like from the error you're attempting to subtract 2 date objects.

    Switch to a DateTime object and you'll be able to do that.  Something along the lines of

    DateTime.Now - start

  • daivagnadaivagna

    i am getting "application name invalid"..error...i passed all four parameters i.e APPID,DEVID,CERTID and AUTHtOKEN...but it fires above error

  • Clint RutkasClint I'm a "developer"

    @daivagna and @haojian jin:  are you sure you have eBayAuthToken property using your ebay auth token?

    If you're still having problems contact us @ via the contact link at the top of the blog.  I'll email you from there.

  • haojian jinhaojian jin

    I am meeting with the same problem with daivagna .

    There is a error called "application name invalid".

  • RanjitRanjit

    Very Good Sample. its working fine. But can any body will help me to get the order Details using the same process ? i have tried alot but... i am not getting any response.

    please help me. ...

  • haojian jinhaojian jin

    Hi. I have a question. How can i finish the search function like the one in ebayDesktop.Which api can lead me there? Waiting for response . i will very appreciate your help if u can contact me @ email.

  • VictorVictor

    Does anybody tried this on Visual Studio 2008 ?  If I try to build it, the build hangs and takes 100% resources.

    On 2005 eveything is OK.

  • Clint RutkasClint I'm a "developer"

    @Victor:  This happened to me when I was adding the reference, but it built fine under VS 2008.  The ebay API takes a bit to download.  That could be it.  I think it took me about 15+ minutes when I did it.

  • XavierXavier

    1) Hi! I am confuse with the callName.

    string callName = "GetMyeBayBuying";

    Where can i find the call name?

    2) I had a "Application name invalid." Server error page.

  • simstersimster

    System.NullReferenceException: Object reference not set to an instance of an object.

    ItemType items = buyingResponse.WatchList.ItemArray;

    i am having problem with this line..

    please help!!

    very urgent!!

    thanks

  • BarryBarry

    The following line of code is giving me a hell of a time:

    eBayAPIInterfaceService service = new eBayAPIInterfaceService();

    Yields ->

    The type or namespace name 'eBayAPIInterfaceService' could not be found (are you missing a using directive or an assembly reference?)

    I can't find any resources to explain where/what the assembly is.

    I

  • Clint RutkasClint I'm a "developer"

    @Xavier: No clue why it does that, you may want to contact Alan who wrote the article.

    @simster:  You're watchlist may be null which may imply you got zero search results from a quick glance.

  • Clint RutkasClint I'm a "developer"

    @Barry:  Are you copying code or did you use the source we provided?  If you are just copying code, did you include the web service then at the top of the class include the using block to say You're using the ebay API?

  • Clint RutkasClint I'm a "developer"

    @Barry:

    This worked for me.

    using ebayTest.com.ebay.developer;

    ebayTest is my project name.  My web service name is com.ebay.developer too.

    This is from a fresh project too.

  • BarryBarry

    @Coding4Fun

    I am copying the C# code from the blocks above.

    I add the Service Reference from http://developer.ebay.com/webservices/latest/eBaySvc.wsdl

    And as far as namespaces, the only 3 I can find are:

    using eBay.ServiceReference;

    using eBay.Properties;

    using eBay;

    However I might be missing something, I can't find the eBayAPIInterfaceService object in the entire eBay namespace

    I'm using VS 2008, .NET 3.5 if that would make a difference

  • MartyMarty

    I just tried the C# version from the download link above.

    I am using VS 2008 Express.

    I created a New Web site, imported the WSDL file as above.

    Copied the source code from the download.

    Inserted my AUTHID etc.

    When compiling, I get one error on line 11

    Line 11 is in Default.aspx.cs

    using eBayWebServices;

    Error 1 The type or namespace name 'eBayWebServices' could not be found (are you missing a using directive or an assembly reference?)

  • MartyMarty

    Hi

    I left a question a few days ago and it has not shown up.

    Any reason why?

  • Clint RutkasClint I'm a "developer"

    @Marty:  Sorry, I was at Mix 08 and am only now catching up.  When you created your web service, what did you name it?  That is what your using block for that should be.  The author of this article renamed his from the default generated to "eBayWebService"

    Do me a favor, type "using " then hit control-space.  I'll bet your'll see one of the items in the list be the item that you named your web service.

  • MartyMarty

    HI,

    Figured you must have been away.

    I am new to all this so be gentle with me.

    When creating the Web service, is that when you are doing the

    Add Web Reference?

    Where do I type the using CRTL-space?

    Marty

  • Clint RutkasClint I'm a "developer"

    @Marty:  Email me by clicking the contact button up on the top and we'll take this offline from this thread.  I'll be able to respond quicker then I'll post a response on this thread on how we fixed the issue.

    I'll be able to do a screen cast possibly to help out and talk you through it.

  • Clint RutkasClint I'm a "developer"

    @Desperate Student TT:  Put in a break point, I bet your WatchList is null.

    You'll need to do more defensive coding and verify the buyingResponse.WatchList != null before moving foward

  • Desperate Student TTDesperate Student TT

    I have this error!!

    Object reference not set to an instance of an object.

    Line 51:        ItemType[] items = buyingResponse.WatchList.ItemArray;

    HELP PLS T.T

  • BunBun

    solved this problem

    Line 51:        ItemType[] items = buyingResponse.WatchList.ItemArray

    replace it with this code

     if (buyingResponse.WatchList != null)

           {

               items = buyingResponse.WatchList.ItemArray;

           }

    and  if (items != null), put this 'if' loop to cover the entire 'add table raw' code

  • Clint RutkasClint I'm a "developer"

    @Hemanth one question is are you sure what you're querying has values getting returned?

    Does the source code download work?

  • HemanthHemanth

    Getting null values in response then how could i get items, where i have given valid production appid, devid & certid with relative usertoken.

    Please guide me

Remove this comment

Remove this thread

close

Comments Closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.