Solved

ASP.NET web user control

Posted on 2003-12-05
22
3,053 Views
Last Modified: 2013-11-25
I have this code in a .ascx web user control.

<table border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td>
            <asp:Button id="btnSubmit" runat="server" OnClick="Submit_Clicked" cssClass="btnAddToCart"></asp:Button>
        </td>
    </tr>
</table>

It is added to a .aspx page, (the control, not the code). It is called with this code:

<td align="right" valign="bottom">
<CommerceSite:AddToCart id="addToCartCtl" Qty="1" runat="server"></CommerceSite:AddToCart>
</td>

How do I rewrite the code so that when a user clicks on an image of a product (on the aspx page), the AddToCart code is activated, as opposed to the current setup where I user can see the image, but has to click the the AddToCart button (on the aspx page).

Thanks,
Ryan
0
Comment
Question by:rossryan
  • 13
  • 9
22 Comments
 
LVL 15

Expert Comment

by:Raisor
Comment Utility
Hi,

What does your class "behind" look like ... or isn't there any yet?


Best regards, Raisor
0
 
LVL 15

Expert Comment

by:Raisor
Comment Utility
Hi,

I've sorted this out of "real" webapp of mine -> it should show "how to"!


User Control:

<%@ Control Language="vb" AutoEventWireup="false" Codebehind="ctrl_bp_points.ascx.vb" Inherits="quickmail.ctrl_bp_points" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
<TABLE id="Table1" cellSpacing="0" cellPadding="14" width="500" height="4000" border="0" background="images/tbg.jpg">
      <TR valign="top">
            <TD align="middle">
                  <h4 class="Dark" align="center"><asp:Label id="Label1" runat="server">Here you can buy more points!</asp:Label></h4>
                  <asp:label id="Label14" runat="server" Font-Size="10pt" Font-Bold="True" Font-Names="Verdana">Pricing Table</asp:label>
                  <P></P>
                  <TABLE id="Table2" cellSpacing="1" cellPadding="1" width="100%" border="0">
                        <TR vAlign="center">
                              <TD style="HEIGHT: 21px" align="middle" width="30%">
                                    <asp:label id="Label4" runat="server" Font-Size="8pt" Font-Bold="True" Font-Names="Verdana">Points</asp:label></TD>
                              <TD style="HEIGHT: 21px" align="middle" width="30%">
                                    <asp:label id="Label9" runat="server" Font-Size="8pt" Font-Bold="True" Font-Names="Verdana">Price (exl. Tax)</asp:label></TD>
                              <TD style="HEIGHT: 21px" align="middle" width="30%">
                                    <asp:label id="Label47" runat="server" Font-Size="8pt" Font-Bold="True" Font-Names="Verdana">Price (inc. Tax)</asp:label></TD>
                              <TD style="HEIGHT: 21px" align="middle" width="10%">&nbsp;</TD>
                        </TR>
                        <TR vAlign="center">
                              <TD align="middle" width="30%">
                                    <asp:label id="Label5" runat="server" Font-Size="8pt" Font-Bold="True" Font-Names="Verdana">10.000</asp:label></TD>
                              <TD align="middle" width="30%">
                                    <asp:label id="Label10" runat="server" Font-Size="8pt" Font-Bold="True" Font-Names="Verdana">4.20 €</asp:label></TD>
                              <TD align="middle" width="30%">
                                    <asp:label id="Label48" runat="server" Font-Size="8pt" Font-Bold="True" Font-Names="Verdana">5.00 €</asp:label></TD>
                              <TD align="middle" width="10%">
                                    <asp:ImageButton id="ImageButton1" runat="server" ImageUrl="../../../images/cart.gif" AlternateText="Add to cart"></asp:ImageButton></TD>
                        </TR>
</TABLE>
                  <P>&nbsp;</P>
            </TD>
      </TR>
</TABLE>

User Control Class:

Public MustInherit Class ctrl_bp_points
    Inherits System.Web.UI.UserControl
    Protected WithEvents Label1 As System.Web.UI.WebControls.Label
    Protected WithEvents Label14 As System.Web.UI.WebControls.Label
    Protected WithEvents Label4 As System.Web.UI.WebControls.Label
    Protected WithEvents Label9 As System.Web.UI.WebControls.Label
    Protected WithEvents Label47 As System.Web.UI.WebControls.Label
    Protected WithEvents Label5 As System.Web.UI.WebControls.Label
    Protected WithEvents Label10 As System.Web.UI.WebControls.Label
    Protected WithEvents Label48 As System.Web.UI.WebControls.Label
    Protected WithEvents ImageButton1 As System.Web.UI.WebControls.ImageButton

#Region "
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

      End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim myHome As c_default
        myUserInfo = myHome.myUserInfo '<- Buffer in the c_default class that contains user data from users' logon
        myHome = Nothing
    End Sub

    Private Sub ImageButton1_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click 'This is what your question is about!
        Dim cart As ShoppingCartDB = New ShoppingCartDB()
        Dim cartId As String = myUserInfo.userLogin
        cart.AddItem(cartId, 410, 1)
        cartId = Nothing
        cart = Nothing
    End Sub

ShoppingCartDB.vb:

Imports System
Imports System.Web
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient

Public Class ShoppingCartDB

    Public Sub AddItem(ByVal cartID As String, ByVal productID As Integer, ByVal quantity As Integer)
        Dim myConnection As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString11"))
        Dim myCommand As SqlCommand = New SqlCommand("ShoppingCartAddItem", myConnection)
        myCommand.CommandType = CommandType.StoredProcedure
        Dim parameterProductID As SqlParameter = New SqlParameter("@ProductID", SqlDbType.Int, 4)
        parameterProductID.Value = productID
        myCommand.Parameters.Add(parameterProductID)
        Dim parameterCartID As SqlParameter = New SqlParameter("@CartID", SqlDbType.NVarChar, 50)
        parameterCartID.Value = cartID
        myCommand.Parameters.Add(parameterCartID)
        Dim parameterQuantity As SqlParameter = New SqlParameter("@Quantity", SqlDbType.Int, 4)
        parameterQuantity.Value = quantity
        myCommand.Parameters.Add(parameterQuantity)
        myConnection.Open()
        myCommand.ExecuteNonQuery()
        myConnection.Close()
    End Sub

End Class


This should show you how the "shopping cart stuff" can be handeled -> if your not able to append your own code at it -> just ask!


Best regards, Raisor
0
 
LVL 15

Expert Comment

by:Raisor
Comment Utility
Hi,

Maybe to be more comprehensive about user logon data (ctrl_bp_points User Control) ...

... this is also declared as:

    Private myUserInfo As New myUserProfileBuffer()

... and the profile buffer derives from:

userDB.vb

Imports System
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient


Public Class myUserProfileBuffer
    Public userID As Long
    Public siteID As Long
    Public userLogin As String
    Public userFirstName As String
    Public userSecondName As String
    Public userLastName As String
    Public userCity As String
    Public userZIP As Long
    Public userStreet As String
    Public userHouseNumber As String
    Public userContinent As String
    Public userCountry As String
    Public userCountry3D As String
    Public userLanguage As String
    Public userRegion As String
    Public userEnterprise As String
    Public userEmail As String
    Public userHomepage As String
    Public userPhone1 As String
    Public userPhone2 As String
    Public userMobile1 As String
    Public userMobile2 As String
    Public userFax1 As String
    Public userFax2 As String
    Public userPermission As Integer
    Public userCreated As Long
    Public userChanged As Long
    Public userPayed As Integer
    Public userTimeflow As Long
    Public userActive As Integer
    Public chosenProduct As String
End Class

... and much much more ... ;-))

I've added this info to give the reason why the User Buffer is important to the AddItem Function in the ShoppingCartDB -> filled at load of the above User Control!


Best regards, Raisor
0
 

Author Comment

by:rossryan
Comment Utility
Well, here ya go:

'=============================================================================
    '   METHOD: S u b m i t _ C l i c k e d
    '
    ''  <doc>
    ''      <desc>Event Handling Method</desc>
    ''      <remarks>
    ''          Handles Click event raised by Submit button.
    ''      </remarks>
    ''      <param term='sender'>Event Sender</param>
    ''      <param term='e'>Event Arguments</param>
    ''      <internalonly/>
    ''  </doc>
    '
    '=============================================================================
    Public Sub Submit_Clicked(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim LineItem As LineItem
        Dim txContext As TransactionContext = TransactionContext.Current

        '--- Check if basket size has exceeded max before adding another item..
        '
        If (txContext.CartOrderForm.LineItems.Count >= CType(CommerceApplication.ConfigurationSettings("MaxLineitemsInBasket"), Integer)) Then
            '
            '--- Basket size has exceeded - notify user and site admin for any potential DOS attack..
            'This is done by sending an error message to basket page by transferring control there..
            '
            Dim urlQueryParamNames(0) As String
            Dim urlQueryParamValues(0) As String

            urlQueryParamNames(0) = URLQueryParameterNames.TxAddToCartErrorMesg
            urlQueryParamValues(0) = ResID.txAddToCartCtrlCartExceededMaxSizeErrorMesg

            CommerceApplication.ServerTransfer("Basket.aspx", urlQueryParamNames, urlQueryParamValues)

        End If

        ' Get detailed attributes about the product and check if it really has a sku..

        Dim prodCatalog As ProductCatalog = CommerceContext.Current.CatalogSystem.GetCatalog(Catalog)
        Dim prodObj As Product = prodCatalog.GetProduct(ProductID)
        Dim prodProps As DataTable = prodObj.GetProductProperties().Tables(0)
        Dim row0 As DataRow = prodProps.Rows(0)
        Dim colClassType As DataColumn = prodProps.Columns("i_ClassType")
        Dim classType As Integer = CInt(row0(colClassType))
        Dim IsSKUSelected As Boolean = False

        ' Check if product sku has been selected..

        If classType <> CatalogClassTypes.ProductFamilyClass Then
            IsSKUSelected = True
        Else
            If Not (VariantID Is Nothing) Then
                If VariantID.Length > 0 Then
                    IsSKUSelected = True
                End If
            End If
        End If

        If IsSKUSelected Then

            ' Found a sku - now add it to cart..

            '--- Proceed to add the item to basket now..
            '
            LineItem = New LineItem()
            LineItem.ProductCatalog = Catalog
            LineItem.ProductCategory = Category
            LineItem.ProductID = ProductID
            LineItem.ProductVariantID = VariantID
            If (VariantDisplayName Is Nothing) Then
                VariantDisplayName = ""
            End If
            LineItem.Item(TxLineItemProperties.VariantDisplayName) = VariantDisplayName
            LineItem.Quantity = Qty
            LineItem.Item(TxLineItemProperties.ProductCatalogBase) = Catalog

            txContext.CartOrderForm.LineItems.Add(LineItem)
            txContext.Cart.Save()

            ' Log the event
            DataWarehouseLogging.LogTxAddToBasketEvent(Catalog, ProductID, VariantID)

            ' Redirect to basket now..

            CommerceApplication.Redirect("Basket.aspx")

        End If

    End Sub


How, or with what arguments do I call to get this code to activate? For example, the ASPX code posted well above lists quantity =1 in the tag, and the ASCX code (designer view) shows OnClick="Submit_Clicked". I want to be able to use the <A></A> tags with this code, so I can anchor text and images...something like <a quantity=1 runat="server" OnClick="Submit_Clicked"><img src="something"></a>. When they click on the image, it has the same effect as the button. I would try to modify the control, but since the asp button is already declared (designer) and to my knolwedge there is no way to put the <a></a> tags inside the control like the button (wouldn't be able to wrap the tags around the text or images) I am at a loss.

Hopes this helps.


Cheers,
Ryan
0
 
LVL 15

Expert Comment

by:Raisor
Comment Utility
Hi,

ASCX: Replace your simple button control with an imagebutton control -> edit the image source parameter (pointing to your cart image) -> If 1 click means qty=1 then there's no problem -> If you want to give the possibility to users to edit quantity you'll add a textBox control with a default text of 1 -> when the user changes that to let's say 5 then you pick this up on module level -> double click the control in the designer and edit the imagebutton_click event on module level! -> let's say like that:

    Private Sub ImageButton1_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click 'This is what I showed you before!
        Dim cart As ShoppingCartDB = New ShoppingCartDB()
        Dim cartId As String = myUserInfo.userLogin
        '... Data processing:
        If IsNumeric(TextBox1.Text) Then
                cart.AddItem(cartId, 410, clng(TextBox1.Text)) 'CartID must be tied to your user -> "410" should be the ProductID -> TextBox1.Text is keeping the Quantity
        Else
                 '... display an error message
        End If
        cartId = Nothing
        cart = Nothing
        'Only if needed: Response.Redirect("yourpage.aspx")
    End Sub




If you have multible products (maybe in a database) you should use a datagrid as a container for the above mentioned controls.


Best regards, Raisor
0
 

Author Comment

by:rossryan
Comment Utility
This code is from the Retail2002 codebase.

I add another OnClick event:

Protected Overridable Sub OnAddToCartAClick(ByVal Source As Object, ByVal E As EventArgs)

        Dim anchor As HtmlAnchor
        Dim args As New EventArgs

        ' Retrieve AddToCart HtmlButton
        anchor = CType(Source, HtmlAnchor)
        SetProductId(anchor)

        RaiseEvent AddToCartClick(Me, args)

    End Sub

Similar to the:
Protected Overridable Sub OnAddToCartClick(ByVal Source As Object, ByVal E As EventArgs)

        Dim btn As HtmlButton
        Dim args As New EventArgs()

        ' Retrieve AddToCart HtmlButton
        btn = CType(Source, HtmlButton)
        SetProductId(btn)

        RaiseEvent AddToCartClick(Me, args)
    End Sub

Except it grabs an anchor instead of a button. However, the product is not added to the basket. Which leads me to believe that the problem is below:

This code calls the button:

<CommerceSite:AddToCart id="addToCart" Catalog="<%# Me.Catalog %>" Qty="1" runat="server">
</CommerceSite:AddToCart>

It is implanted in the page. Note the Qty="1" and Catalog="<%# Me.Catalog %>" arguments. How do I pass or declare those items in the AddToCart control (the one already in the page, I think)?

Thanks,
Ryan
 
0
 
LVL 15

Expert Comment

by:Raisor
Comment Utility
Hi,

I might not have my very best day today ... but how come that "OnAddToCartAClick" and "OnAddToCartClick" perform any action if they're not declared to handle any specific event?

What I mean is: AddToCart seems to be a user control -> on that user control there should be other controls that take care of any command processing which is ... or should be ;-)) ... followed by data processing!

Please give me the complete ascx and the complete ascx.vb -> if there is critical information that you can not publish -> well, then you can contact me through my profile and send the data to me -> we'll provide a general solution to our database here then -> later on ... when this is solved!


Best regards, Raisor
0
 

Author Comment

by:rossryan
Comment Utility
You want it, you got it:

ProductsList.ascx

<%@ Register TagPrefix="CommerceSite" TagName="AddToCart" Src="..\..\Transactions\AddToCart.ascx" %>
<%@ Register TagPrefix="CommerceSite" TagName="CurrencyConverter" Src="..\..\Transactions\CurrencyConverter.ascx" %>
<%@ Control Language="vb" Codebehind="ProductsList.ascx.vb" AutoEventWireup="false" Inherits="Microsoft.CommerceServer.Site.Catalogs.ProductsList" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
<!----------------------------------------------------------------------------
  FileName :       ProductsList.ascx
  Description :    Catalog Products List control.      
 
 
  This file is part of the Microsoft Commerce Server 2002 SDK

  Copyright (C) 2002 Microsoft Corporation.  All rights reserved.

  Commerce Server 2002 and/or on-line documentation. See these other
  materials for detailed information regarding Microsoft code samples.

  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
  PURPOSE.
------------------------------------------------------------------------------>
<!-- P R O D U C T S  L I S T  C O N T R O L -->
<asp:Repeater ID="repeaterCanonicalPath" Runat="server" OnItemDataBound="CategoryPath_OnItemDataBound">
      <ItemTemplate>
            <a href="" runat="server" onserverclick="OnCategoryClick" class="aCategoryId" id="lnkCategoryDisplayName">
            </a>
            <asp:Literal ID="ltlCategoryName" Runat="server" Text="<%# Container.DataItem %>" Visible=False>
            </asp:Literal>
      </ItemTemplate>
      <SeparatorTemplate>
            <span style="font-color:#0000FF; font-weight:bold; font-size:12px">&nbsp;>&nbsp;</span>
      </SeparatorTemplate>
      <FooterTemplate>
            <br>
            <br>
      </FooterTemplate>
</asp:Repeater>
<table id="tableProducts" width="100%" cellSpacing="0" cellPadding="0" border="0" runat="server">
      <!-- W h a t ' s N e w - H E A D E R  -->
      <tr id="trHeader" runat="server">
            <td class="tdDarkBox_TopLeft">&nbsp;</td>
            <td height="26">
                  <table height="26" cellSpacing="0" cellPadding="0" width="100%" border="0">
                        <tr>
                              <td id="prodListHeading" class="tdDarkBox_TopMiddleLeft" runat="server"></td>
                              <td class="tdDarkBox_Top">&nbsp;</td>
                              <td class="tdDarkBox_TopMiddleRight" align="right">
                                    <CommerceSite:CurrencyConverter id="currencyConverter" runat="server"></CommerceSite:CurrencyConverter>
                              </td>
                        </tr>
                  </table>
            </td>
            <td width="12" height="26">&nbsp;</td>
      </tr>
      <!-- W h a t ' s  N e w - B O D Y  -->
      <tr id="trUpper" runat="server">
            <td class="tdDarkBox_UpperLeft">&nbsp;</td>
            <td>&nbsp;</td>
            <td class="tdDarkBox_UpperRight">&nbsp;</td>
      </tr>
      <tr>
            <td id="tdLeft" runat="server" class="tdDarkBox_Left">&nbsp;</td>
            <td>
                  <table cellSpacing="0" cellPadding="0" width="100%" border="0">
                        <asp:repeater id="repeaterProductsList" onitemdatabound="ProductsList_OnItemDataBound" OnItemCommand="ProductsList_OnItemCommand"
                              Runat="server">
                              <ItemTemplate>
                                    <tr>
                                          <td rowspan="3" style="padding-right:3px" valign="top">
                                          
                                                <img id="img" height="120" width="100px" alt='<%# Container.DataItem("Name") %>' src='<%# Container.DataItem("Image_filename") %>'>
                                          
                                          
                                                
                                          </td>
                                          <td>
                                                <a href="" id="anchor" class="aProductId" runat="server" onserverclick="OnAddToCartAClick">
                                                      <%# Container.DataItem ("Name") %>
                                                      <input id="ProductId" type="hidden" name="ProductId" runat="server" value='<%# Container.DataItem("ProductId") %>'>
                                                      <input id="VariantId" type="hidden" name="VariantId" runat="server" value='<%# Container.DataItem("VariantId") %>'>
                                                </a>
                                          </td>
                                          <td align="right" valign="bottom"><%# catalogCurrency %></td>
                                    </tr>
                                    <tr>
                                          <td rowspan="2" valign="top" style="font-size:11px"><%# Container.DataItem ("Description") %></td>
                                          <td width="30%" valign="top" style="font-size:12px">
                                                <table width="100%" cellSpacing="0" cellPadding="0" border="0">
                                                      <tr>
                                                            <td id="retailPrice" align="left" style="font-size:11px; font-weight:bold; padding-right:10px;"
                                                                  runat="server"></td>
                                                            <td id="retailPriceValue" align="right" style="font-size:11px" runat="server"><%# Container.DataItem ("cy_list_price") %></td>
                                                      </tr>
                                                      <tr>
                                                            <td id="discount" align="left" style="font-size:11px; font-weight:bold" runat="server"></td>
                                                            <td align="right" style="font-size:11px"></td>
                                                      </tr>
                                                      <tr>
                                                            <td id="ourPrice" align="left" style="font-size:11px; font-weight:bold" runat="server"></td>
                                                            <td id="ourPriceValue" align="right" style="font-size:11px" runat="server"><%# Container.DataItem ("cy_list_price") %></td>
                                                      </tr>
                                                </table>
                                          </td>
                                    </tr>
                                    <tr>
                                          <td align="right" valign="bottom">
                                                <CommerceSite:AddToCart id="addToCart" Catalog="<%# Me.Catalog %>" Qty="1" runat="server">
                                                </CommerceSite:AddToCart>
                                          </td>
                                    </tr>
                              </ItemTemplate>
                              <SeparatorTemplate>
                                    <tr>
                                          <td colspan="3" height="5px">&nbsp;</td>
                                    </tr>
                              </SeparatorTemplate>
                              <FooterTemplate>
                                    <tr>
                                          <td colspan="3" height="5px">&nbsp;</td>
                                    </tr>
                              </FooterTemplate>
                        </asp:repeater>
                  </table>
            </td>
            <td id="tdRight" runat="server" class="tdDarkBox_Right">&nbsp;</td>
      </tr>
      <!-- W h a t ' s N e w - F O O T E R  -->
      <tr id="trFooter" runat="server">
            <td class="tdDarkBox_LowerLeft">&nbsp;</td>
            <td class="tdDarkBox_Bottom">&nbsp;</td>
            <td class="tdDarkBox_LowerRight">&nbsp;</td>
      </tr>
      <tr>
            <td colspan="3" height="5">&nbsp;</td>
      </tr>
</table>



ProductsList.ascx.vb

'=========================================================================
'  FileName : ProductsList.ascx.vb
'
'
'  This file is part of the Microsoft Commerce Server 2002 SDK
'
'  Copyright (C) 2002 Microsoft Corporation.  All rights reserved.
'
'  This source code is intended only as a supplement to Microsoft
'  Commerce Server 2002 and/or on-line documentation. See these other
'  materials for detailed information regarding Microsoft code samples.
'
'  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
'  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
'  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
'  PURPOSE.
'=========================================================================

Option Strict On
Option Explicit On

#Region " Namespaces "

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Threading
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls

Imports Microsoft.VisualBasic
Imports Microsoft.CommerceServer.Runtime
Imports Microsoft.CommerceServer.Runtime.Catalog
Imports Microsoft.CommerceServer.Site
Imports Microsoft.CommerceServer.Site.Constants
Imports Microsoft.CommerceServer.Site.Catalogs.Constants
Imports Microsoft.CommerceServer.Site.Catalogs
Imports Microsoft.CommerceServer.Site.Catalogs.Functions
Imports Microsoft.CommerceServer.Site.Transactions
Imports Microsoft.CommerceServer.Site.Components
Imports Microsoft.CommerceServer.Runtime.Orders

#End Region

#Region " Event Delegates "

Public Delegate Sub ProductsListProductClickEventHandler(ByVal sender As Object, ByVal e As EventArgs)
Public Delegate Sub ProductsListCategoryClickEventHandler(ByVal sender As Object, ByVal e As EventArgs)
Public Delegate Sub ProductsListAddToCartClickEventHandler(ByVal sender As Object, ByVal e As EventArgs)
Public Delegate Sub ProductsListAddToCartAClickEventHandler(ByVal sender As Object, ByVal e As EventArgs)
'Public Delegate Sub SearchEventHandler2(ByVal sender As Object, ByVal e As SearchEventArgs)



#End Region

''  <summary>
''  This class implements the products list  control. It displays the
''  products under the selected category and also displays the category path
''  This control also displays the root products.
''  </summary>
Public MustInherit Class ProductsList
    Inherits System.Web.UI.UserControl

#Region " Events "

    Public Event ProductClick As ProductsListProductClickEventHandler
    Public Event CategoryClick As ProductsListProductClickEventHandler
    Public Event AddToCartClick As ProductsListAddToCartClickEventHandler
    Public Event AddToCartAClick As ProductsListAddToCartClickEventHandler
    'Public Event SearchEvent As SearchEventHandler2

#End Region

#Region " Fields "

    '--- Private data members
    '
    Private productIdVal As String = ""
    Private variantIdVal As String = ""
    Private currencyInfo As currencyInfo

    '--- Protected data members (member controls)
    '
    Protected catalogCurrency As String
    Protected tableProducts As HtmlTable
    Protected tdLeft As HtmlTableCell
    Protected tdRight As HtmlTableCell

    Protected prodListHeading As HtmlTableCell
    Protected trHeader As HtmlTableRow
    Protected trFooter As HtmlTableRow
    Protected trUpper As HtmlTableRow


    Protected WithEvents repeaterProductsList As Repeater
    Protected WithEvents repeaterCanonicalPath As Repeater
    Protected WithEvents currencyConverter As CurrencyConverterControl
    'Public Event Click As CartProductClickEventHandler

#End Region

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

#Region " Properties "

    '=============================================================================
    '   PROPERTY: Catalog
    '
    ''  <doc>
    ''      <desc>Read-Write Property</desc>
    ''      <remarks>To be used in receiving pages.</remarks>
    ''      <retvalue>
    ''            Returns/sets the selected catalog
    ''      </retvalue>
    ''  </doc>
    '
    '=============================================================================

    Property Catalog() As String
        Get
            Dim obj As Object = ViewState("Catalog")
            If obj Is Nothing Then
                Return String.Empty
            End If
            Return CStr(obj)
        End Get
        Set(ByVal Value As String)
            ViewState("Catalog") = Value
        End Set
    End Property

    '=============================================================================
    '   PROPERTY: Category
    '
    ''  <doc>
    ''      <desc>Read-Write Property</desc>
    ''      <remarks>To be used in receiving pages.</remarks>
    ''      <retvalue>
    ''            Returns/sets the selected Category
    ''      </retvalue>
    ''  </doc>
    '
    '=============================================================================
    Property Category() As String
        Get
            Dim obj As Object = ViewState("Category")
            If obj Is Nothing Then
                Return String.Empty
            End If
            Return CStr(obj)
        End Get
        Set(ByVal Value As String)
            ViewState("Category") = Value
            SetPath()
        End Set
    End Property

    '=============================================================================
    '   PROPERTY: Path
    '
    ''  <doc>
    ''      <desc>Read-Write Property</desc>
    ''      <remarks>To be used in receiving pages.</remarks>
    ''      <retvalue>
    ''            Returns/sets the category hierarchy for this product
    ''      </retvalue>
    ''  </doc>
    '
    '=============================================================================
    Property Path() As String()
        Get
            Return Split(CType(ViewState("Path"), String), SEPARATOR)
        End Get
        Set(ByVal Value As String())
            ViewState("Path") = Join(Value, SEPARATOR)
        End Set
    End Property

    '=============================================================================
    '   PROPERTY: ProductId
    '
    ''  <doc>
    ''      <desc>Read-Only Property</desc>
    ''      <remarks>To be used in receiving pages.</remarks>
    ''      <retvalue>
    ''            Returns the ProductId of the selected product
    ''      </retvalue>
    ''  </doc>
    '
    '=============================================================================

    ReadOnly Property ProductId() As String
        Get
            Return productIdVal
        End Get
    End Property

    '=============================================================================
    '   PROPERTY: VariantId
    '
    ''  <doc>
    ''      <desc>Read-Only Property</desc>
    ''      <remarks>To be used in receiving pages.</remarks>
    ''      <retvalue>
    ''            Returns the VariantId of the selected variant
    ''      </retvalue>
    ''  </doc>
    '
    '=============================================================================
    ReadOnly Property VariantId() As String
        Get
            Return variantIdVal
        End Get
    End Property

#End Region

#Region " Methods "

    '=============================================================================
    '   METHOD: P a g e _ L o a d
    '
    ''  <doc>
    ''      <desc>Page Load Event-Handling Method</desc>
    ''      <param term='sender'>Event Sender</param>
    ''      <param term='e'>Event Arguments</param>
    ''      <internalonly/>
    ''  </doc>
    '
    '=============================================================================
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    '=============================================================================
    '   METHOD: CategoryPath_OnItemDataBound
    '
    ''  <doc>
    ''      <desc>OnItemDataBound - event handler</desc>
    ''      <remarks>
    ''          Handles OnItemDataBound event
    ''      </remarks>
    ''      <param term='sender'>Event Sender</param>
    ''      <param term='e'>Event Arguments</param>
    ''      <internalonly/>
    ''  </doc>
    '
    '=============================================================================
    Protected Sub CategoryPath_OnItemDataBound(ByVal Source As Object, ByVal E As RepeaterItemEventArgs)

        Dim categoryName As String
        Dim ltlCategoryName As Literal
        Dim lnkCategoryDisplayName As HtmlAnchor

        Static catalogObject As ProductCatalog = CommerceContext.Current.CatalogSystem.GetCatalog(Me.Catalog)

        If (E.Item.ItemType = ListItemType.Item) Or _
           (E.Item.ItemType = ListItemType.AlternatingItem) Then

            '--- Retrieve controls to store Category Name and DisplayName
            '
            ltlCategoryName = CType(E.Item.FindControl("ltlCategoryName"), Literal)
            lnkCategoryDisplayName = CType(E.Item.FindControl("lnkCategoryDisplayName"), HtmlAnchor)

            '--- Set Category Display Name
            '
            lnkCategoryDisplayName.InnerText = GetCategoryDisplayName(catalogObject, ltlCategoryName.Text)
        End If

    End Sub

    '=============================================================================
    '   METHOD: CurrencyConverter_OnSelectedIndexChanged
    '
    ''  <doc>
    ''      <desc>Event Handling Method</desc>
    ''      <remarks>
    ''          Handles Index Changed event raised by underlying Currency Converter.
    ''      </remarks>
    ''      <param term='Source'>Object</param>
    ''      <param term='E'>EventArgs</param>
    ''      <internalonly/>
    ''  </doc>
    '
    '=============================================================================
    Private Sub CurrencyConverter_OnSelectedIndexChanged(ByVal Source As Object, ByVal E As CurrencyChangedEventArgs) Handles currencyConverter.SelectedIndexChanged

        '--- Render List using new Currency Symbol and Multiplier
        '
        RenderList()
    End Sub

    '=============================================================================
    '   Private Function: GetProductsList
    '
    ''  <doc>
    ''      <desc>Gets the products belonging to the selected category</desc>
    ''  </doc>
    '
    '=============================================================================
    Private Function GetProductsList() As DataSet

        Dim products As DataSet
        Dim category As category
        Dim categories As String()
        Dim canonicalPath As String()
        Dim productCatalog As productCatalog

        ' Retrieve Product Catalog object
        productCatalog = CommerceContext.Current.CatalogSystem.GetCatalog(Me.Catalog)
        If (Me.Category = "") Then
            ' Retrieve root products
            products = productCatalog.GetRootProducts()
            ' Unbind any previous settings
            canonicalPath = Nothing
        Else
            'Retrieve Category object
            category = productCatalog.GetCategory(Me.Category)
            ' Retrive child products for category
            products = category.GetProducts()
            ' Retrieve Category Canonical Path
            categories = Me.Path
        End If

        ' Bind Categories List
        repeaterCanonicalPath.DataSource = categories
        repeaterCanonicalPath.DataBind()

        ' Return products DataSet
        GetProductsList = products
    End Function

    '=============================================================================
    '   METHOD: OnProductClick
    '
    ''  <doc>
    ''      <desc>OnProductClick - event handler</desc>
    ''      <remarks>
    ''          ServerClick event handler for all HtmlAnchor controls
    ''          corresponding to Products in list
    ''      </remarks>
    ''      <param term='sender'>Event Sender</param>
    ''      <param term='e'>Event Arguments</param>
    ''      <internalonly/>
    ''  </doc>
    '
    '=============================================================================
    Protected Overridable Sub OnProductClick(ByVal Source As Object, ByVal E As EventArgs)

        Dim anchor As HtmlAnchor
        Dim args As New EventArgs()

        ' Retrieve Product's HtmlAnchor
        anchor = CType(Source, HtmlAnchor)
        SetProductId(anchor)

        RaiseEvent ProductClick(Me, args)
    End Sub

    '=============================================================================
    '   METHOD: OnCategoryClick
    '
    ''  <doc>
    ''      <desc>OnCategoryClick - event handler</desc>
    ''      <remarks>
    ''          ServerClick event handler for all HtmlAnchor controls
    ''          corresponding to Categories Category Canonical Path list
    ''      </remarks>
    ''      <param term='sender'>Event Sender</param>
    ''      <param term='e'>Event Arguments</param>
    ''      <internalonly/>
    ''  </doc>
    '
    '=============================================================================
    Protected Overridable Sub OnCategoryClick(ByVal Source As Object, ByVal E As EventArgs)

        Dim anchor As HtmlAnchor
        Dim args As New EventArgs()
        Dim ltlCategoryName As Literal

        ' Retrieve controls holding Category Name/DisplayName values
        anchor = CType(Source, HtmlAnchor)
        ltlCategoryName = CType(anchor.Parent.FindControl("ltlCategoryName"), Literal)

        ' Persist Category and Catalog settings
        Me.Category = ltlCategoryName.Text.Trim
        SetPath()

        RaiseEvent CategoryClick(Me, args)
    End Sub

    '=============================================================================
    '   METHOD: OnAddToCartClick
    '
    ''  <doc>
    ''      <desc>OnAddToCartClick - event handler</desc>
    ''      <remarks>
    ''          ServerClick event handler for all HtmlAnchor controls
    ''          corresponding to AddToCart buttons in list
    ''      </remarks>
    ''      <param term='sender'>Event Sender</param>
    ''      <param term='e'>Event Arguments</param>
    ''      <internalonly/>
    ''  </doc>
    '
    '=============================================================================
    Protected Overridable Sub OnAddToCartClick(ByVal Source As Object, ByVal E As EventArgs)

        Dim btn As HtmlButton
        Dim args As New EventArgs()

        ' Retrieve AddToCart HtmlButton
        btn = CType(Source, HtmlButton)
        SetProductId(btn)

        RaiseEvent AddToCartClick(Me, args)
    End Sub

    '=============================================================================
    '   METHOD: OnAddToCartAClick
    '
    ''  <doc>
    ''      <desc>OnAddToCartAClick - event handler</desc>
    ''      <remarks>
    ''          ServerClick event handler for all HtmlAnchor controls
    ''          corresponding to AddToCart buttons in list
    ''      </remarks>
    ''      <param term='sender'>Event Sender</param>
    ''      <param term='e'>Event Arguments</param>
    ''      <internalonly/>
    ''  </doc>
    '
    '=============================================================================
    Protected Overridable Sub OnAddToCartAClick(ByVal Source As Object, ByVal E As EventArgs)

        Dim anchor As HtmlAnchor
        Dim args As New EventArgs

        ' Retrieve AddToCart HtmlButton
        anchor = CType(Source, HtmlAnchor)
        SetProductId(anchor)

        RaiseEvent AddToCartClick(Me, args)

    End Sub

    '=============================================================================
    '   METHOD: ProductsList_OnItemDataBound
    '
    ''  <doc>
    ''      <desc>OnItemDataBound - event handler</desc>
    ''      <remarks>
    ''          Handles OnItemDataBound event
    ''      </remarks>
    ''      <param term='sender'>Event Sender</param>
    ''      <param term='e'>Event Arguments</param>
    ''      <internalonly/>
    ''  </doc>
    '
    '=============================================================================
    Protected Sub ProductsList_OnItemDataBound(ByVal Source As Object, ByVal E As RepeaterItemEventArgs)

        Dim ctrl As AddToCart
        Dim productId As HtmlInputHidden
        Dim priceValue As HtmlTableCell

        Static multiplier As Decimal = currencyInfo.Multiplier

        If (E.Item.ItemType = ListItemType.Item) Or _
           (E.Item.ItemType = ListItemType.AlternatingItem) Then

            '--- Apply Current Multiplier to All Currency Values
            '
            priceValue = CType(E.Item.FindControl("retailPriceValue"), HtmlTableCell)
            priceValue.InnerText = (CType(priceValue.InnerText, Decimal) * multiplier).ToString("C")
            priceValue = CType(E.Item.FindControl("ourPriceValue"), HtmlTableCell)
            priceValue.InnerText = (CType(priceValue.InnerText, Decimal) * multiplier).ToString("C")

            ' Retrieve AddToCart control instance
            productId = CType(E.Item.FindControl("ProductId"), HtmlInputHidden)
            ctrl = CType(E.Item.FindControl("addToCart"), AddToCart)

            ctrl.ProductID = productId.Value

            Dim item As RepeaterItem = E.Item
            Dim cell As HtmlTableCell

            cell = CType(item.FindControl("discount"), HtmlTableCell)
            cell.InnerText = CommerceApplication.ResourceString(ResID.discount)
            cell = CType(item.FindControl("retailPrice"), HtmlTableCell)
            cell.InnerText = CommerceApplication.ResourceString(ResID.retailPrice)
            cell = CType(item.FindControl("ourPrice"), HtmlTableCell)
            cell.InnerText = CommerceApplication.ResourceString(ResID.ourPrice)

        End If

    End Sub

    '=============================================================================
    '   METHOD: ProductsList_OnItemCommand
    '
    ''  <doc>
    ''      <desc>OnItemCommand - event handler</desc>
    ''      <remarks>
    ''          Handler attached to the OnCommand event of the repeater.
    ''          This is used to redirect to productdetails if addtocart is pressed on a variant product.
    ''      </remarks>
    ''      <param term='sender'>Event Sender</param>
    ''      <param term='e'>Event Arguments</param>
    ''      <internalonly/>
    ''  </doc>
    '
    '=============================================================================
    Protected Sub ProductsList_OnItemCommand(ByVal Source As Object, ByVal E As RepeaterCommandEventArgs)

        Dim ctlProductId As HtmlInputHidden

        If (E.Item.ItemType = ListItemType.Item) Or _
           (E.Item.ItemType = ListItemType.AlternatingItem) Then

            Dim ctrl As AddToCart = CType(E.Item.FindControl("addToCart"), AddToCart)

            ctlProductId = CType(E.Item.FindControl("ProductId"), HtmlInputHidden)
            productIdVal = ctlProductId.Value

            Dim prodCatalog As ProductCatalog = CommerceContext.Current.CatalogSystem.GetCatalog(Me.Catalog)
            Dim prodObj As Product = prodCatalog.GetProduct(productIdVal)
            Dim prodProps As DataTable = prodObj.GetProductProperties().Tables(0)
            Dim row0 As DataRow = prodProps.Rows(0)
            Dim colClassType As DataColumn = prodProps.Columns(CLASS_TYPE)
            Dim classType As Integer = CInt(row0(colClassType))

            If classType = CatalogClassTypes.ProductFamilyClass And VariantId = "" Then
                RaiseEvent ProductClick(Me, New System.EventArgs)
            End If

        End If
    End Sub

    '=============================================================================
    '   Public method: RenderList
    '
    ''  <doc>
    ''      <desc>Renders the products belonging to the selected category</desc>
    ''  </doc>
    '
    '=============================================================================
    Public Sub RenderList()

        Dim visible As Boolean
        Dim products As DataSet

        If (Me.Catalog = "") Then
            tableProducts.Visible = False
            'RaiseEvent SearchEvent(Me, New SearchEventArgs("Appear"))
            Exit Sub
        End If

        products = GetProductsList()
        If (products.Tables(0).Rows.Count = 0) Then
            tableProducts.Visible = False
            'RaiseEvent SearchEvent(Me, New SearchEventArgs("Appear"))
        Else
            If (Me.Category = "") Then
                visible = True
                'RaiseEvent SearchEvent(Me, New SearchEventArgs("Disappear"))
            Else
                visible = False
                'RaiseEvent SearchEvent(Me, New SearchEventArgs("Appear"))
            End If

            ' Remove What's New frame
            trHeader.Visible = visible
            trUpper.Visible = visible
            trFooter.Visible = visible
            tdLeft.Visible = visible
            tdRight.Visible = visible

            tableProducts.Visible = True

            'RaiseEvent SearchEvent(Me, New SearchEventArgs("Disappear"))

            prodListHeading.InnerText = CommerceApplication.ResourceString(ResID.prodListHeading)

            ' Hard-code "Images\Catalog" prefix in ImageFileName field
            UpdateImageFileNames(products)

            '--- Set Currency Symbol for the current thread
            '
            SetCurrencyInfo()

            ' Bind products list
            repeaterProductsList.DataSource = products
            repeaterProductsList.DataBind()
        End If

    End Sub

    '=============================================================================
    '   Private Method: SetProductId
    '
    ''  <doc>
    ''      <desc>Retrieves and Persists ProductId and VariantId values
    ''            for the current selection based on an HtmlControl
    ''            (either HtmlButton or HtmlAnchor) source of a Click event  </desc>
    ''  </doc>
    '
    '=============================================================================
    Private Sub SetProductId(ByVal source As HtmlControl)

        Dim hidden As HtmlInputHidden

        ' Retrieve/Persist ProductId value
        hidden = CType(source.FindControl("ProductId"), HtmlInputHidden)
        productIdVal = hidden.Value

        ' Retrieve/Persist ProductId value
        hidden = CType(source.FindControl("VariantId"), HtmlInputHidden)
        variantIdVal = hidden.Value

    End Sub

    '=============================================================================
    '   Private Method: SetPath
    '
    ''  <doc>
    ''      <desc>Sets internal representation of current
    ''            Category Canonical Path</desc>
    ''  </doc>
    '
    '=============================================================================
    Private Sub SetPath()

        Dim index As Integer
        Dim pathArray As String()

        If (Me.Category = "") Then Exit Sub

        If (CStr(ViewState("Path")) = "") Then
            ViewState("Path") = Me.Category
        Else
            pathArray = Me.Path
            index = Array.IndexOf(pathArray, Me.Category)
            If (index = -1) Then
                ReDim Preserve pathArray(pathArray.Length)
                pathArray(UBound(pathArray)) = Me.Category
            Else
                ' Truncate path array
                ReDim Preserve pathArray(index)
            End If

            ' Persist path
            Me.Path = pathArray
        End If

    End Sub
    '=============================================================================
    '   Private Method: UpdateImageFileNames
    '
    ''  <doc>
    ''      <desc>Displays the images for the products</desc>
    ''  </doc>
    ''  <remarks>Hard-codes the "Images\Catalog" prefix ImageFileName
    ''           fields of products DataTable <remarks>
    '
    '=============================================================================
    Private Sub UpdateImageFileNames(ByVal products As DataSet)

        Dim fileName As Object
        Dim table As DataTable

        Dim rowIndex As Integer

        table = products.Tables(0)
        For rowIndex = 0 To table.Rows.Count - 1

            fileName = table.Rows(rowIndex).Item("Image_filename")
            If (Not IsDBNull(table.Rows(rowIndex).Item("Image_filename"))) Then
                table.Rows(rowIndex).Item("Image_filename") = Replace(CType(fileName, String), "images/", "Images/Catalog/")
            End If
        Next
    End Sub

    '=============================================================================
    '   METHOD: SetCurrencyInfo
    '
    ''  <doc>
    ''      <desc>Private Method</desc>
    ''      <remarks>
    ''          Retrieves CurrencyInfo from Profile Ticket.
    ''          Sets Currency Symbol for Current Thread.
    ''      </remarks>
    ''      <internalonly/>
    ''  </doc>
    '
    '=============================================================================
    Private Sub SetCurrencyInfo()

        Dim currencySymbol As String

        '--- Get CurrencyInfo from Profile Ticket
        '
        Me.currencyInfo = CommerceApplication.CurrencyInfo
        catalogCurrency = Me.currencyInfo.CurrencyCode
        currencySymbol = Me.currencyInfo.CurrencySymbol

        '--- Set Currency Symbol for Current Thread
        '
        Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencySymbol = currencySymbol

    End Sub

#End Region

End Class

Public Class SearchEventArgs
    Private _myvalue As String = ""
    Public Sub New(ByVal TheValue As String)
        _myvalue = TheValue
    End Sub
    Public ReadOnly Property ThisIsTheValue() As String
        Get
            Return _myvalue
        End Get
    End Property

End Class






 AddToCart.ascx


<!----------------------------------------------------------------------------
  FileName:       AddToCart.ascx
  Description:    Control provides the UI and logic to add product (variant)
                  to Shopping Cart. It is used extensively in product
                  catalog pages.

 
  This file is part of the Microsoft Commerce Server 2002 SDK

  Copyright (C) 2002 Microsoft Corporation.  All rights reserved.

  Commerce Server 2002 and/or on-line documentation. See these other
  materials for detailed information regarding Microsoft code samples.

  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
  PURPOSE.
------------------------------------------------------------------------------>
<%@ Control Language="vb" AutoEventWireup="false" Codebehind="AddToCart.ascx.vb" Inherits="Microsoft.CommerceServer.Site.Transactions.AddToCart" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
<table border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td>
            <asp:Button id="btnSubmit" runat="server" OnClick="Submit_Clicked" cssClass="btnAddToCart"></asp:Button>
        </td>
    </tr>
</table>










AddToCart.ascx.vb







'=========================================================================
'  FileName : AddToCart.ascx.vb
'
'
'  This file is part of the Microsoft Commerce Server 2002 SDK
'
'  Copyright (C) 2002 Microsoft Corporation.  All rights reserved.
'
'  This source code is intended only as a supplement to Microsoft
'  Commerce Server 2002 and/or on-line documentation. See these other
'  materials for detailed information regarding Microsoft code samples.
'
'  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
'  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
'  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
'  PURPOSE.
'=========================================================================

Option Strict On
Option Explicit On

#Region " Namespaces "

Imports System.Web.UI
Imports System.Data
Imports System.Exception

Imports Microsoft.CommerceServer.Runtime
Imports Microsoft.CommerceServer.Runtime.Orders
Imports Microsoft.CommerceServer.Runtime.Catalog

Imports Microsoft.CommerceServer.Site
Imports Microsoft.CommerceServer.Site.Constants
Imports Microsoft.CommerceServer.Site.Components

#End Region

'=============================================================================
'   CLASS: AddToCart
'
''  <doc>
''      <desc>AddToCart Control Class</desc>
''      <remarks>
''          This User Control contains all the UI and logic to add an item
''          a product (variant) to the Cart object.
''          It is used extensively in product catalog pages.
''      </remarks>
''  </doc>
'
'=============================================================================
Public MustInherit Class AddToCart
    Inherits System.Web.UI.UserControl

#Region " Fields "

    '--- Protected data members (Member controls)
    '
    Protected WithEvents btnSubmit As System.Web.UI.WebControls.Button

#End Region

#Region " Properties "

    '=============================================================================
    '   PROPERTY: C a t a l o g
    '
    ''  <doc>
    ''      <desc>Property</desc>
    ''      <remarks>To be used in receiving pages.</remarks>
    ''      <retvalue>
    ''          Catalog property of the item being added to Cart.
    ''          A non-empty string is required.
    ''      </retvalue>
    ''  </doc>
    '
    '=============================================================================
    Public Property Catalog() As String
        Get
            Return CType(ViewState("Catalog"), String)
        End Get
        Set(ByVal Value As String)
            ViewState("Catalog") = Value
        End Set
    End Property

    '=============================================================================
    '   PROPERTY: C a t e g o r y
    '
    ''  <doc>
    ''      <desc>Property</desc>
    ''      <remarks>To be used in receiving pages.</remarks>
    ''      <retvalue>
    ''          Category property of the item being added to Cart. Optional.
    ''      </retvalue>
    ''  </doc>
    '
    '=============================================================================
    Public Property Category() As String
        Get
            Return CType(ViewState("Category"), String)
        End Get
        Set(ByVal Value As String)
            ViewState("Category") = Value
        End Set
    End Property

    '=============================================================================
    '   PROPERTY: ProductId
    '
    ''  <doc>
    ''      <desc>Property</desc>
    ''      <remarks>To be used in receiving pages.</remarks>
    ''      <retvalue>
    ''          ProductId property of the item being added to Cart.
    ''          A non-empty string is required.
    ''      </retvalue>
    ''  </doc>
    '
    '=============================================================================
    Public Property ProductID() As String
        Get
            Return CType(ViewState("ProductId"), String)
        End Get
        Set(ByVal Value As String)
            ViewState("ProductId") = Value
        End Set
    End Property

    '=============================================================================
    '   PROPERTY: VariantId
    '
    ''  <doc>
    ''      <desc>Property</desc>
    ''      <remarks>To be used in receiving pages.</remarks>
    ''      <retvalue>
    ''          VariantId property of the item being added to Cart.
    ''          Optional for non-variant products.
    ''      </retvalue>
    ''  </doc>
    '
    '=============================================================================
    Public Property VariantID() As String
        Get
            Return CType(ViewState("VariantId"), String)
        End Get
        Set(ByVal Value As String)
            ViewState("VariantId") = Value
        End Set
    End Property

    '=============================================================================
    '   PROPERTY: VariantDisplayName
    '
    ''  <doc>
    ''      <desc>Property</desc>
    ''      <remarks>To be used in pages using add-to-cart button.</remarks>
    ''      <retvalue>
    ''          Variant display name string used on product display - and is set by product detail pages.
    ''          Optional for non-variant products.
    ''      </retvalue>
    ''  </doc>
    '
    '=============================================================================
    Public Property VariantDisplayName() As String
        Get
            Return CType(ViewState(TxLineItemProperties.VariantDisplayName), String)
        End Get
        Set(ByVal Value As String)
            ViewState(TxLineItemProperties.VariantDisplayName) = Value
        End Set
    End Property

    '=============================================================================
    '   PROPERTY: Quantity
    '
    ''  <doc>
    ''      <desc>Property</desc>
    ''      <remarks>To be used in receiving pages.</remarks>
    ''      <retvalue>
    ''          Non-zero, positive integer upto 4 billion (?)
    ''          Validation will be performed using RangeValidator controls
    ''      </retvalue>
    ''  </doc>
    '
    '=============================================================================
    Public Property Qty() As Integer
        Get
            Return CType(ViewState("Qty"), Integer)
        End Get
        Set(ByVal Value As Integer)
            ViewState("Qty") = Value
        End Set
    End Property

#End Region

#Region " Web Form Designer Generated Code "


    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

#Region " Methods "

    '=============================================================================
    '   METHOD: P a g e _ L o a d
    '
    ''  <doc>
    ''      <desc>Page Load Event-Handling Method</desc>
    ''      <param term='sender'>Event Sender</param>
    ''      <param term='e'>Event Arguments</param>
    ''      <internalonly/>
    ''  </doc>
    '
    '=============================================================================
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        ' Set page localizable resources
        SetLocalizableResources()

    End Sub

    '=============================================================================
    '   METHOD: S u b m i t _ C l i c k e d
    '
    ''  <doc>
    ''      <desc>Event Handling Method</desc>
    ''      <remarks>
    ''          Handles Click event raised by Submit button.
    ''      </remarks>
    ''      <param term='sender'>Event Sender</param>
    ''      <param term='e'>Event Arguments</param>
    ''      <internalonly/>
    ''  </doc>
    '
    '=============================================================================
    Public Sub Submit_Clicked(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim LineItem As LineItem
        Dim txContext As TransactionContext = TransactionContext.Current

        '--- Check if basket size has exceeded max before adding another item..
        '
        If (txContext.CartOrderForm.LineItems.Count >= CType(CommerceApplication.ConfigurationSettings("MaxLineitemsInBasket"), Integer)) Then
            '
            '--- Basket size has exceeded - notify user and site admin for any potential DOS attack..
            'This is done by sending an error message to basket page by transferring control there..
            '
            Dim urlQueryParamNames(0) As String
            Dim urlQueryParamValues(0) As String

            urlQueryParamNames(0) = URLQueryParameterNames.TxAddToCartErrorMesg
            urlQueryParamValues(0) = ResID.txAddToCartCtrlCartExceededMaxSizeErrorMesg

            CommerceApplication.ServerTransfer("Basket.aspx", urlQueryParamNames, urlQueryParamValues)

        End If

        ' Get detailed attributes about the product and check if it really has a sku..

        Dim prodCatalog As ProductCatalog = CommerceContext.Current.CatalogSystem.GetCatalog(Catalog)
        Dim prodObj As Product = prodCatalog.GetProduct(ProductID)
        Dim prodProps As DataTable = prodObj.GetProductProperties().Tables(0)
        Dim row0 As DataRow = prodProps.Rows(0)
        Dim colClassType As DataColumn = prodProps.Columns("i_ClassType")
        Dim classType As Integer = CInt(row0(colClassType))
        Dim IsSKUSelected As Boolean = False

        ' Check if product sku has been selected..

        If classType <> CatalogClassTypes.ProductFamilyClass Then
            IsSKUSelected = True
        Else
            If Not (VariantID Is Nothing) Then
                If VariantID.Length > 0 Then
                    IsSKUSelected = True
                End If
            End If
        End If

        If IsSKUSelected Then

            ' Found a sku - now add it to cart..

            '--- Proceed to add the item to basket now..
            '
            LineItem = New LineItem()
            LineItem.ProductCatalog = Catalog
            LineItem.ProductCategory = Category
            LineItem.ProductID = ProductID
            LineItem.ProductVariantID = VariantID
            If (VariantDisplayName Is Nothing) Then
                VariantDisplayName = ""
            End If
            LineItem.Item(TxLineItemProperties.VariantDisplayName) = VariantDisplayName
            LineItem.Quantity = Qty
            LineItem.Item(TxLineItemProperties.ProductCatalogBase) = Catalog

            txContext.CartOrderForm.LineItems.Add(LineItem)
            txContext.Cart.Save()

            ' Log the event
            DataWarehouseLogging.LogTxAddToBasketEvent(Catalog, ProductID, VariantID)

            ' Redirect to basket now..

            CommerceApplication.Redirect("Basket.aspx")

        End If

    End Sub

    '=============================================================================
    '   METHOD: S e t L o c a l i z a b l e R e s o u r c e s
    '
    ''  <doc>
    ''      <desc>Private Method</desc>
    ''      <remarks>
    ''          Relies on Resource Manager to retrieve localized
    ''          resources depending on current user's culture.
    ''      </remarks>
    ''      <internalonly/>
    ''  </doc>
    '
    '=============================================================================
    Private Sub SetLocalizableResources()

        btnSubmit.Text = CommerceApplication.ResourceString(ResID.txAddToCartCtrlText)
        btnSubmit.Attributes("Title") = CommerceApplication.ResourceString(ResID.txAddToCartCtrlTitle)
        btnSubmit.Attributes("AccessKey") = CommerceApplication.ResourceString(ResID.txAddToCartCtrlAccessKey)
    End Sub

#End Region


End Class














Good luck. Ryan.
0
 

Author Comment

by:rossryan
Comment Utility
Wow, that's a lot of code. The OnAddToCartAClick was added to the ProductsList.ascx file, in the anchor <a>. You can see where I attempted to replicate the methods, and modify them...to no avail.

The Retail2002 codebase is composed of many technologies: XML, SQL, ASP.NET, VB.NET, C#....you name it, it's probably in there...

Regards,

Ryan
0
 
LVL 15

Expert Comment

by:Raisor
Comment Utility
Hi,

OK! ... another night in the late, dark and cold Germany, Europe spoiled ... ;-))

Well, I know -> when I ask "how urgent is this?" you'll say "a result on yesterday would be the best!" ... but serious ... how urgent is this? ... why I ask? -> it'll take some time to implement your code in a testing enviroment of mine ... so how much time can you give?


Best regards, Raisor
0
 
LVL 15

Expert Comment

by:Raisor
Comment Utility
PS: Unfortunately I have uninstalled Commerce Server a few weeks ago ... but as I see that the code you've provided is part of the SDK ... well, I might return to run Commerce Server and sample your code "live" then ;-))
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:rossryan
Comment Utility
As much as you want. Microsoft is set to give me a call from their *shudder* escalation engineers *shudder* sometime tomorrow for a seperate piece of code (apparently, I have a keen sense for finding Commerce Server's most horrific faults), and as this is more of a...superficial piece, it will not be needed.

As a programmer, I assure you that I will never label anything 'urgent.' Urgent == SQL server on fire, Urgent != one piece of code that is already implemented (as a button) somewhere. Let the customers figure out how the website works...

Anyways, I have a XML shipping service to implement somewhere. Then I have to find out why the customCatalogBrowser control (not in this code, don't worry) is acting up on the ProductDetails page. Then I get to fix up the email submission form. Then I get to fix some javascript coding. And so on...

If anything, I'm happy for all the help I can get. :)

Good night,
Ryan
0
 
LVL 15

Expert Comment

by:Raisor
Comment Utility
Hi,

ok ok ok ... ;-)) ... so there's no time pressure ...

I'll try to get this one going and then we'll have a look at the CatalogueActs up on ProdDets ... in email submission forms I have special skill and JavaScript coding is what I hate since I think IT but could never avoid -> so skills enough on my side -> and to tell you (well, you know already!), if it's too much of a workload => there are thousands of experts here that help you too! -> just a suggestion -> if not one of the required solutions depends on another ... you shouldn't work it the serial way -> parallel threading …. Multitasking ;-)) … might bring more value in shorter time delays than any other approach!


Best regards, Raisor
0
 

Author Comment

by:rossryan
Comment Utility
Heh, I multitask on a daily basis. Something about being the only knowledgeable person in the company has its effects. I was merely laying out the other tasks I have to occupy me (I have the code in hand, am well versed in the laguages I need, with you working on this piece I can head off to take care of those things, etc. a.k.a. multi-tasking). I assure you, I understand the difference between serial and parallel thinking, and am an active advocate of the latter :).

 
0
 
LVL 15

Expert Comment

by:Raisor
Comment Utility
... ;-)) ..
0
 

Author Comment

by:rossryan
Comment Utility
*languages

Quick comment on the code (forgot to add this earlier). The ASPX file creates a control with a set quantity and catalog. Quantity = 1, Catalog = Me.Catalog. These values are passed when the button is clicked (open ended assumption). An instance is created.

My code does not do that. Similar method, invoked by the clicking on a link, but the link does not create an instance nor does it set those arguments. Ah well, you'll figure it out.

Cheers,
Ryan
0
 
LVL 15

Expert Comment

by:Raisor
Comment Utility
Hi,

Exactly that was what I thought of when stating:

"I might not have my very best day today ... but how come that "OnAddToCartAClick" and "OnAddToCartClick" perform any action if they're not declared to handle any specific event?"

... that is also the WHY I wanted to see ALL of it -> it makes no sense to solve 2, 3 or 4 little errors and leaving all the other ones "@work" ... but let's see if that's the point!


Best regards, Raisor
0
 
LVL 15

Expert Comment

by:Raisor
Comment Utility
Hi,

I've played around a little and here's my idea: -> let's build up an equal dev envirionment to play this and other scenarios  together!


I have build this:


==========
rossryan.aspx:
==========

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="rossryan.aspx.vb" Inherits="exex002.rossryan"%>
<%@ Register TagPrefix="uc1" TagName="AddToCart" Src="rossryan/AddToCart.ascx" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
      <HEAD>
            <title>rossryan</title>
            <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
            <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
            <meta name="vs_defaultClientScript" content="JavaScript">
            <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
      </HEAD>
      <body MS_POSITIONING="GridLayout">
            <form id="Form1" method="post" runat="server">
                  <uc1:AddToCart id="AddToCart1" runat="server"></uc1:AddToCart>
            </form>
      </body>
</HTML>


============
rossryan.aspx.vb:
============

Public Class rossryan
    Inherits System.Web.UI.Page

#Region

     <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

      End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
       
    End Sub

End Class


============
AddToCart.ascx:
============

<%@ Control Language="vb" AutoEventWireup="false" Codebehind="AddToCart.ascx.vb" Inherits="exex002.AddToCart" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
<table border="0" cellspacing="0" cellpadding="0">
      <tr>
            <td>
                  <asp:Button id="btnSubmit" runat="server" OnClick="Submit_Clicked" cssClass="btnAddToCart"></asp:Button>
            </td>
      </tr>
</table>
<P>&nbsp;</P>
<P>
      <asp:Label id="Label1" runat="server"></asp:Label></P>


=============
AddToCart.ascx.vb:
=============

Public MustInherit Class AddToCart
    Inherits System.Web.UI.UserControl
      Protected WithEvents Label1 As System.Web.UI.WebControls.Label
      Protected WithEvents btnSubmit As System.Web.UI.WebControls.Button
#Region

    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

      End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            If Page.IsPostBack = False Then
                  SetLocalizableResources()
            End If
    End Sub

      Public Sub Submit_Clicked(ByVal sender As Object, ByVal e As System.EventArgs)
            Dim btn As Button
            Dim args As New EventArgs()
            btn = CType(sender, Button)
            Label1.Text = btn.Attributes("AccessKey").ToString
            'Response.Redirect("Basket.aspx")
      End Sub

      Private Sub SetLocalizableResources()
            btnSubmit.Text = "SubmitText"              ' CommerceApplication.ResourceString(ResID.txAddToCartCtrlText)
            btnSubmit.Attributes("Title") = "YourTitle"              'CommerceApplication.ResourceString(ResID.txAddToCartCtrlTitle)
            btnSubmit.Attributes("AccessKey") = "YourKey"              'CommerceApplication.ResourceString(ResID.txAddToCartCtrlAccessKey)
      End Sub

End Class




From this basis on we can continue to find a solution to any specific problem -> having the same conditions!

Best regards, Raisor
0
 

Author Comment

by:rossryan
Comment Utility
Great idea. I received the conference call from MS, and that is all sorted. If you have a ftp, I can upload the project files (PuP doesn't work right now).

I went ahead and implemented CVV2 (3-digit credit card security) code, and will modify that tomorrow. It also looks like I will be implementing real-time currency conversion (courtesy of the European International Bank), but that is something to sit on.

Thanks,
Ryan
0
 
LVL 15

Accepted Solution

by:
Raisor earned 250 total points
Comment Utility
Hi,

I would start with the

==========
rossryan.aspx:
==========

and them three other files -> what I meant was that we use this litte project as model to simulate the reason of any problem and to demonstrate any solution logically.

You can modify parts of it showing what you want the code to do or where to lead any result -> then I'll have a look at it and will be able to change it to the way you need it -> so that I can assist you from the distance ...

Please try to modify the four files the way you think that AddToCart should function!


Best regards, Raisor
0
 

Author Comment

by:rossryan
Comment Utility
Had to declare the control within VB file. Thanks,

Ryan
0
 
LVL 15

Expert Comment

by:Raisor
Comment Utility
Hi,

Thanks for the feedback ... I'll be around when any further questions come up!


Best regards, Raisor
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

When designing a form there are several BorderStyles to choose from, all of which can be classified as either 'Fixed' or 'Sizable' and I'd guess that 'Fixed Single' or one of the other fixed types is the most popular choice. I assume it's the most p…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now