Samedi le 4 février 2012 . 17:11

Creating a RelatedProductsBox custom control

This guide explains how to create a custom DataList to show a box with products related to the content of a page using a specific set of keywords, a bit like Google AdSense if you want. Here is a screenshot of what the example box looks like.

RelatedProductsBox Example Screenshot

Using AmazonECS.Net, this kind of control is very easy to create and implement. The following lines explain how to create the control and how to use it in your pages. You can download the control source code and example here.

Requirements

In order to use AmazonECS.Net, you need to register for an Amazon Subscription Id (now called Access Key) to use the library. It is an essential step that will enable you to use Amazon services.

Also, in order to make money, you will need an Amazon associate tag which you can obtain here. This step is optional but suggested.

Creating the RelatedProductsBox custom control

As mentioned before, our custom control will inherit from the DataList server control. We will add a few properties to the control and only one method. So, the first step is to create a Web Control Library named RelatedProductsBox inheriting a DataList and add a reference to the AmazonECS.Net library (Matizha.AmazonECS.Net.dll). Then, we need to add a reference to the Matizha.AmazonECSNet.WebServices namespace.

Adding the properties

We need to add 5 properties to our new control:

  • Keywords: what the products should be related to.
  • Size: the number of products to list in the box.
  • SearchIndex: the category where to search the products (using the SearchIndex enum from AmazonECS.Net)
  • AssociateTag: Amazon associate tag.
  • SubscriptionId: Amazon subscription id required for all requests to Amazon webservices.

Also, make sure to add Designer support for the properties, it will be easier to configure your custom control later.

Your code should now look like something like this:

using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using Matizha.AmazonECSNet.WebServices;

namespace Matizha.AmazonECSNet.CustomControls
{
    /// <summary>
    /// Summary description for RelatedProductsBox.
    /// </summary>
    [ToolboxData("<{0}:RelatedProductsBox runat=server></{0}:RelatedProductsBox>")]
    public class RelatedProductsBox : System.Web.UI.WebControls.DataList
    {
        private string keywords;
        private string associateTag = "webservices-20";
        private string subscriptionId;
        private int size = 3;
        private SearchIndex searchIndex = SearchIndex.Blended;

        [Category("Keywords"),
        DefaultValue(""),
        Description("Keywords to which the products should be related to.")]
        public string Keywords
        {
            get
            {
                return keywords;
            }

            set
            {
                keywords = value;
            }
        }

        [Browsable(false)]
        public string AssociateTag
        {
            get
            {
                return associateTag;
            }

            set
            {
                associateTag = value;
            }
        }

        [Browsable(false)]
        public string SubscriptionId
        {
            get
            {
                return subscriptionId;
            }

            set
            {
                subscriptionId = value;
            }
        }

        [Category("Search Index"),
        DefaultValue(SearchIndex.Blended),
        Description("The category in which to search for the products.")]
        public SearchIndex SearchIndex
        {
            get
            {
                return searchIndex;
            }

            set
            {
                searchIndex = value;
            }
        }

        [Category("Size"),
        DefaultValue(3),
        Description("The number of products to list in the box.")]
        public int Size
        {
            get
            {
                return size;
            }

            set
            {
                size = value;
            }
        }
    }
}

Adding the method that will fill the box

All we have to do now is create a method that will send the request to Amazon and automatically load the data using the specified properties. Let’s call this method FillProductsBox.

Making the request is pretty straight forward. We use the search request from AmazonECS.Net. We specify the necessary properties and then call the Search method of SearchRequest. The true parameter specifies that the result to the request will be cached (using ASP.Net Caching) and that if the same request is made within the next 24 hours, it will be loaded from cache instead.

[...]

SearchRequest rq = new SearchRequest();

rq.SubscriptionId = this.subscriptionId;
rq.AssociateTag = this.associateTag;

rq.Keywords = this.keywords;
rq.ItemPage = "1";
rq.SearchIndex = this.searchIndex;

Items items = rq.Search(true);

[...]

Once the request is made, we should have a set of items related to the keywords specified. The next step is to create a DataTable to store our product descriptions. In this control, I only created columns for the most generic item properties (price, availability, etc.) so it can be used with almost any search index or with a blended search without any problem. If you know you will only use the control with a particular category, like DVD, then you could add columns for the properties used in DVD. For instance, you could add columns for ReleaseDate or AudienceRating.

Also, most requests will return 10 items (or less), so we have to limit the number of products to bind to the size specified.

Finally, all there is left to do is to automatically bind our DataTable to our custom control using a DataView. Here is the full listing for the method:

public void FillProductsBox()
{
    SearchRequest rq = new SearchRequest();

    rq.SubscriptionId = this.subscriptionId;
    rq.AssociateTag = this.associateTag;

    rq.Keywords = this.keywords;
    rq.ItemPage = "1";
    rq.SearchIndex = this.searchIndex;

    Items items = rq.Search(true);

    if ( items != null )
    {
        Item [] itemArray = items.Item;
        if ( itemArray != null )
        {
            DataTable productTable = new DataTable();
            productTable.Columns.Add(new DataColumn("Title", typeof(string)));
            productTable.Columns.Add(new DataColumn("Availability", typeof(string)));
            productTable.Columns.Add(new DataColumn("SmallImage", typeof(string)));
            productTable.Columns.Add(new DataColumn("AmazonPrice", typeof(string)));
            productTable.Columns.Add(new DataColumn("DetailPageURL", typeof(string)));

            int maxIndex = itemArray.Length;
            if (itemArray.Length > this.size) maxIndex = this.size;

            for ( int i = 0; i < maxIndex; i++ )
            {
                Item item = itemArray[i];
                DataRow row = productTable.NewRow();

                if (item.ItemAttributes.Title != null)
                    row["Title"] = item.ItemAttributes.Title;

                if (item.SmallImage != null)
                    row["SmallImage"] = item.SmallImage.URL;

                if (item.DetailPageURL != null)
                    row["DetailPageURL"] = item.DetailPageURL;

                if (item.Offers != null)
                {
                    Offer [] offerArray  = item.Offers.Offer;
                    if (offerArray != null)
                    {
                        if (offerArray[0].OfferListing != null)
                        {
                            if (offerArray[0].OfferListing[0].Price != null)
                                row["AmazonPrice"] = offerArray[0].OfferListing[0].Price.FormattedPrice;
                            if (offerArray[0].OfferListing[0].Availability != null)
                                row["Availability"] = offerArray[0].OfferListing[0].Availability;
                        }
                    }
                }

                productTable.Rows.Add(row);
            } 

            DataView dv = new DataView(productTable);
            this.DataSource = dv;
            this.DataBind();
        }
    }
}

That’s it! We now have a simple control based on AmazonECS.Net that shows products related to the specified keyword.

Using the RelatedProductsBox

To use your new custom control in an application, you need to add a reference to the assembly file of your control. In the above example, the assembly was Matizha.AmazonECS.Net.CustomControls.dll.

Adding the control to your page

Then, at the top of the page you want to use the box in, you need to register the control like this:

<%@ Register TagPrefix="ecs" Namespace="Matizha.AmazonECSNet.CustomControls"
Assembly="Matizha.AmazonECS.Net.CustomControls" %>

Then, somewhere in your form, you have insert your control. You can modify most of the control properties using the Designer. Also, it can be used to see the list of all the available SearchIndexes. To search in all categories at once, use the Blended SearchIndex. Customize the ItemTemplate content as you need. Also, I included the corresponding CSS classes in the example package.

<ecs:relatedproductsbox id="relatedbox" runat="server"
    searchindex="Books"
    keywords="ASP.Net"
    repeatdirection="Horizontal"
    cssclass="box"
    cellpadding="0"
    horizontalalign="Center">

    <itemtemplate>
        <a href='<%# DataBinder.Eval(Container, "DataItem.DetailPageURL") %>'>
            <%# DataBinder.Eval(Container, "DataItem.Title") %>
        </a>
        <br>
        <p><a href='<%# DataBinder.Eval(Container, "DataItem.DetailPageURL") %>'>
        <img src='<%# DataBinder.Eval(Container, "DataItem.SmallImage") %>' border="0" align="left"></a>
            <b>Availability</b><br>
            <%# DataBinder.Eval(Container, "DataItem.Availability") %>
        </p>
        <p><b>Price</b><br>
            <span class="price">
                <%# DataBinder.Eval(Container, "DataItem.AmazonPrice") %>
            </span>
        </p>
    </itemtemplate>

    <headertemplate>
        Suggested ASP.Net Books
    </headertemplate>
    <itemstyle cssclass="itemtemplate"></itemstyle>
    <headerstyle cssclass="headertemplate"></headerstyle>
</ecs:relatedproductsbox>

Code-Behind

Finally, in the code-behind of your page, you need to call the FillProductsBox method somewhere after you specified your subscription id and associate tag. Most of the time, you should call it in the Page_Load event. Also, make sure you replace the question marks with your own subscription id. If you want to be rewarded money for your referals, specify your own associate tag, otherwise, you can use the default one.

protected Matizha.AmazonECSNet.CustomControls.RelatedProductsBox relatedbox;

private void Page_Load(object sender, System.EventArgs e)
{
    if (!Page.IsPostBack)
    {
        relatedbox.SubscriptionId = "????????????????????";
        relatedbox.AssociateTag = "webservices-20";
        relatedbox.FillProductsBox();
    }
}

That’s it! You can download the full source code and example. Feel free to modify and improve it as much as you need. You can also send your comments here.

viagra costs walmart
cipla canada
Cialis generic alternative
depoxetine
buy dapoxetine online
dsicount viagra
order cialis 20mg
where can I buy cialis 20mg
viagra loest prise
discount cialis 20mg
viagra sale
buy super viagra
viagrasuperforte
cialis no prescription canada
viagra paypal payment canada
viagra soft tabs
sildenafil
Generic Levitra
buy levitra
viagra cheap
levitra bayer
36 hour cialis mg
causes of irectal dysfuction
generic viagra 50mg
generic cialis
cialis black 800mg
montreal online pharmacy
buy generic viagra
canada customs and cialis
calis
generic viagra from india
order viagra from canada
cialis 20mg price
cialis coupons
buy cialis using paypal
cialis 10mg
viagra by mail
walmart pharmacy viagra
pfizer viagra online
viagra price
Vardenafil HCL
ed pro trial pack
buy generic levitra no prescription
china Pharmacy
proscar 5mg
VIAGRA online
cialis 20mg prices
viagra cialis combo
levitra
cialis with dapoxetine
drugstore 1st
cialis 20 mg from united kingdom
cialis black
viagra low cost
cialis for daily use
tadalafil daily use
cialis
generic viagara
buy DAPOXETINE
canada viagra overnight
accutane for sale online
viagra free trial offer
Sildenafil
real viagra paypal
levitra forum
Sildenafil citrate 50mg
buy viagra online ireland
Cheap viagra
cialis professional
20mg cialis
cialis promise program
viagra coupon
viagRA online
cialis sales
VIAGRA FOR DAILY USE
generic levitra overnight delivery
edtrustedmedstore
cialis tablets
Generic Viagra
viagra canada
where can i buy finasteride
viagra trial sample
order viagra
buy viagra
nolvadex
cheap generic viagra pills
discount viagra
HTMLGIANT LEVITRA
generic cialis in canada
buying viagra with next day shipping
mixing cocaine and viagra
dapoxetine
viagra prices walmart
buy strong viagra
original cialis
Viagra on line
genuine viagra australia
generic viargra
cialis online canada
cialis paypal payment
us cialis online pharmacy
ordering cialias
where to buy cialis
100mg Viagra
buy viagra for women germany
cheap generic viagra 100mg
walmart cialis price
whats the least expensive place to buy viagra
Levitra
levitra 10mg buy
Buy viagra online
buy dapoxetine
cheap generic cialis
generic propecia
generic viagia
sildenafil online canada
cialis super active review
cialis viagra cocktail
buy viagra in canada fast
viagra online
generic cialis cipla
buying viagra online in montreal
kamagra for sale
i need cialis
VIAGRA IN USA
cialis super active vs professional
cialis without prescription
cialis viagra levitra canada
is super active cialis a scam
european cialis
tadalifil
sildenafil tablets
next day shipping viagra
10mg cialis
viagra and pregancy
where to buy viagra in calgary
low dose cialis
cheapest generic levitra
liquid viagra to buy
viagra no prescription
cheap sildenafil
Sildenafil citrate 100mg
sildenafil citrate overnight delivery
buy viagra using paypal
generic cialis
viagra no perscription
where to buy viagra in toronto
alternatives to viagra
canada generic viagra
viagra online without prescription
price of tadalafil 20 mg
cialis 36 hour
cheap sildenafil citrate
cialis 20 mg
viagra and dapoxetine
generic viagra
viagra for sale australia
walmartcanadapharmacy
cialis online nz
buy generic propecia
30 day free cialis
Viagra for sale
levitra buy
viagra no prescription
viagra generic
what works as well as viagra
generis cialis
buy propecia
viagra jelly sachet
viagra mail order
buy viagra no prescription
BUYING EGYPT VIAGRA
buy viagra online
vardenafil
viagra in uk
viagra softtabs
cealis generic
viagra patent expiration date
viagra canada free sample
levitra coupons pharmacy
buy viagra canada
buy viagra online
finasteride
sildenafil citrate generic
Lowest prices on Viagra Super Force 100mg/60mg pills
cheaP viagra
100mg viagra
Cialis
viagra usa
status 365 pills
Cheap Viagra
cialis soft tabs canada
sildenafil 100mg
viagra online netherlands
cheapest cialis 20mg
tadalafil soft gelatin capsules
noriskpharmacy
street value for viagra
VIAGRA ONLINE
pfizer viagra price
Nolvadex
chip viagra
Dapoxetine
buy levitra online
generic viagra soft tabs
cialis canada pharmacy
drugstore 365 org order levitra online
canada viagra paypal
centerpill
viagra nz
cialis online
viagra from tijuana
overnight pharma
cialis + dapoxetine
viagra price comparison
cialis men
pills house
cialis generic
Viagra cheap
generic viagra
kamagra tablets
+viagra
propecia
where can i buy generic viagra
Sildenafil Citrate
canadian levitra vs usa levitra
30 day free trial of cialis
viagra suppliers canada
buy proscar
buy cialis no prescription
pillshouse
low cost viagra
cialis overnight
finasteride sale
cialis no prescrition
viagra on line
viagra melbourne
cialis+price
buy viagra usa
best viagra deals from India
canadian cialis online
super viagra uk
brand name viagra canada
viagra for sale
buy viagra without prescription
canadian pharmacies selling viagra
propecia generic finasteride
cialis black reviews
viagra paypal checkout
viagra for women for sale
cheap cialis generic online
can i take cialis with daxpoteine
generic cialas
where can i get viagra across the counter in the uk
cialis online uk
buy cialis
viagra no prescription canada pfizer
viagra online without a prescription
cialis coupon
tadalafil dosage
propecia
viagra alcohol effects
Finasteride purchase
cialis daily
cialis for sale nz
Generic viagra
cheap vigra
free viagra sample pack
cialis south africa
clomid
order cialis 20 online
cilias 20mg
PROSCAR
brand cialis
nolvadex for sale
viagra canada sales
cheapest cialis tadalafil 20 mg
cialis 40 mg
walmartprices for viagra
buy real viagra with a echeck
cheapest viagra
viagra no prescription overnight
what is the ingredients in viagra
cialis no prescription
lilly cialis 20mg
viagra next day delivery usa
viagra online nz
viagraonline\
buy original cialis 10 mg
CIALIS No prescription
viagra single tabs
generic Viagra
cialis 5mg
ordering viagra onl
indo viagral
viagra for sale in ireland
black tab cialis
viagra 100 tablets
buy nolvadex
viagra video
viagra deals
cost of viagra
GENERIC CIALIS WITH DAPOXETINE 80MG
genaric viagra
buy finasteride
tramadol side effects dysfunction
buy cialis 20 mg
1 800 490 0365
cialis no perscription
viagra vs cialis which is better
online overnight viagra
generic ciallis
cialis 200 mg price
compralviagra
propecia cost
how to buy viagra from canada
viragra
viagra uk
Viagra
generic viagra 50 mg
cialis for sale canada
finasteride 1mg generic
viagra no prescrition
Viagra prices
cheap viagra 50 mg
cialis voucher
Generic Viagra
cheap levitra online india
order viagra online
Proscar
generic viagra canada
pharmacy express
viagra without a script
viagra australia no prescription
planet pharma warehouse pvt ltd
cailis online
super active cialis with no prescription
Cialis online
viagra sales
levitra professional 100mg
where to buy viagra
levitra substitute
viagra no prescription
vpxl
overnightpharmacy4u
viagra uk
finasteride 1mg
viagra canada no prescription
Cialis 50mg price
viagra for sell
NEXIUM FOR SALE
cialis overnight shipping
levitra generic
viagra in united states
buy generic cialis
1 mg propecia
cialis for daily use disount
levitra coupon
buy wholesale viagra
pfizer viagra without prescription
viagra quebec
generic cialis 20mg
cialis without prescriptions
buy Dapoxetine
ebay + cialis
viagra levitra which is best
viagra levitra cialis offers
canada pharmacy generic cialis
generic viagra price
viagra express
where to buy Propecia
tadalafil
generic vs brand name viagra
generic levitra for sale
generic levitra
levitra online canadian
Female Cialis
cialis daily
viAGRA ONLINE
sildenafil citrate
viagra prices
viagra for boys
walmart canada pharmacy
cialis to buy
.buy viagra
buy viagra Australia
cialisonline
viagra online, no prescription
cheap viagra online
buy cialis generic
buy viagra online sydney
ggeneric viagra for sale
viagra for sale online
original viagra for sale
100 ml viagra for sale
levitra 100mg uk
order levitra
Sildenafil Citrate
viagra 100mg
supreme suppliers cialis
levitra dosage 40 mg
sildenafil citrate 100mg
purchase propecia
viagra patent date
CHEAP VIAGRa
Finasteride 1mg
Buy Viagra online
cialis onlilne
where to buy genuine viagra online
inderal overnight
online viagra no prescription
cialis vs viagra