Page 1 of 1
How to add BuyProductDialog Control to the Product Grid?
Posted: Wed Jul 22, 2009 10:36 pm
by princeatapi
Hi ,
I gotta prob while embeding the ByuProductDialog to the products grid , if i try ckicking the 'add to cart' or 'add to wish list' its reporting me with an error .. 'Instance not Initialized!!'
how to resolve this issue ?
Thanks
-Prince
Re: How to add BuyProductDialog Control to the Product Grid?
Posted: Thu Jul 23, 2009 3:34 am
by mazhar
Make sure that you are providing product id properly to the control, because out of the box BuyProductDialog control gets product id from query string and indented to be used on product details page. In your case there is no product id in query string because its product listing page and there are a number of products. So make sure that you are passing and product is being loaded properly for BuyProductDialog.
Re: How to add BuyProductDialog Control to the Product Grid?
Posted: Fri Jul 24, 2009 7:19 am
by princeatapi
Thanks for your comments , i knew well that the dialog Control gets product Id from the querystring , im trying to pass the same product ID from the GategoryGridPage.ascx Page Using the #Eval("ProductId") from the DataList , <asp:DataList ID="ProductList" ... />
ive also made some property to get and set the value of _ProductId in the BuyProductsDialog Control, if i try to launch the control still the _ProductId Doesn't get initiated , So how to resolve this problem
- Prince
Re: How to add BuyProductDialog Control to the Product Grid?
Posted: Fri Jul 24, 2009 7:26 am
by mazhar
Hard to comment without seeing actual code for your custom Grid with BuyProductDialog.
Re: How to add BuyProductDialog Control to the Product Grid?
Posted: Fri Jul 24, 2009 7:40 am
by princeatapi
hi !
Some how i made it , but i got little bugs,
here is the modified GategoryGridPage.ascx
<asp:DataList ID="ProductList" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" Width="100%"
OnItemDataBound="ProductList_ItemDataBound" DataKeyField="ProductId" CssClass="catalog" EnableViewState="false" HorizontalAlign="left">
<ItemStyle HorizontalAlign="center" VerticalAlign="bottom" Width="33%" CssClass="tableNode" />
<ItemTemplate>
<asp:PlaceHolder ID="phItemTemplate1" runat="server"></asp:PlaceHolder>
<uc:ProductPrice ID="Price" runat="server" Product='<%#Container.DataItem%>' ShowRetailPrice="true" />
<asp:PlaceHolder ID="phItemTemplate2" runat="server"></asp:PlaceHolder>
<div style="margin-top:10px;margin-bottom:20px">
<%-- <uc:Add2WishList ID="Add2WishList" runat="server" ProductId ='<%#Eval("ProductId") %>' /> --%>
<%-- <uc:AddToCartLink ID="Add2Cart" runat="server" ProductId='<%#Eval("ProductId")%>' /> --%>
<uc:AddToWishList ID ="Ad2WishLIst" runat ="server" ProductId ='<%#Eval("ProductId")%>' />
</div>
</ItemTemplate>
<SeparatorTemplate> </SeparatorTemplate>
<SeparatorStyle CssClass="separator" Width="1" />
</asp:DataList>
AddToWishList.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="AddToWishList.ascx.cs" Inherits="ConLib_Custom_AddToWishList" %>
<%@ Register Assembly="CommerceBuilder.Web" Namespace="CommerceBuilder.Web.UI.WebControls" TagPrefix="cb" %>
<%@ Register Src="~/ConLib/Utility/ProductPrice.ascx" TagName="ProductPrice" TagPrefix="uc" %>
<ajax:UpdatePanel ID="BuyProductPanel" runat="server" UpdateMode="Always">
<ContentTemplate>
<table class="buyProductForm" cellpadding="0" cellspacing="0">
<tr id="trSku" runat="server" enableviewstate="false">
<th class="rowHeader">
<asp:Localize ID="SkuLocalize" runat="server" Text="Item #:" EnableViewState="false"></asp:Localize>
</th>
<td>
<asp:Literal ID="Sku" runat="server"></asp:Literal>
</td>
</tr>
<tr id="trPartNumber" runat="server" enableviewstate="false">
<th class="rowHeader">
<asp:Localize ID="PartNumberLocalize" runat="server" Text="Part #:" EnableViewState="false"></asp:Localize>
</th>
<td>
<asp:Literal ID="PartNumber" runat="server"></asp:Literal>
</td>
</tr>
<tr id="trRegPrice" runat="server" enableviewstate="false">
<th class="rowHeader">
<asp:Localize ID="RegPriceLocalize" runat="server" Text="Reg. Price:" EnableViewState="false"></asp:Localize>
</th>
<td>
<asp:Label ID="RegPrice" runat="server" SkinID="MSRP" EnableViewState="false"></asp:Label>
</td>
</tr>
<tr id="trOurPrice" runat="server" EnableViewState="false">
<th class="rowHeader" valign="top">
<asp:Localize ID="OurPriceLocalize" runat="server" Text="Our Price:" EnableViewState="false"></asp:Localize>
</th>
<td>
<uc:ProductPrice ID="OurPrice" runat="server" EnableDefaultKitProducts="false" />
</td>
</tr>
<tr id="trVariablePrice" runat="server" enableviewstate="false">
<th class="rowHeader">
<asp:Localize ID="VariablePriceLabel" runat="server" Text="Enter Price:" EnableViewState="false"></asp:Localize>
</th>
<td>
<asp:TextBox ID="VariablePrice" runat="server" MaxLength="8" Width="60px" ValidationGroup="AddToBasket"></asp:TextBox>
<asp:PlaceHolder ID="phVariablePrice" runat="server"></asp:PlaceHolder>
</td>
</tr>
<tr id="rowSubscription" runat="server" enableviewstate="false">
<td> </td>
<td>
<asp:Localize ID="RecuringPaymentMessage" runat="server" Text="This item includes a recurring payment." EnableViewState="false"></asp:Localize><br />
<asp:Localize ID="InitialPayment" runat="server" Text="Initial Payment: {0:ulc}<br />" EnableViewState="false"></asp:Localize>
<asp:Localize ID="RecurringPayment" runat="server" Text="Recurring Payment: {0} payments of {1:ulc}, every {2}." EnableViewState="false"></asp:Localize>
</td>
</tr>
<asp:PlaceHolder runat="server" id="phOptions" EnableViewState="false"></asp:PlaceHolder>
<asp:PlaceHolder ID="phAddToBasketWarningOpt" runat="server" EnableViewState="false" Visible="false">
<tr>
<td> </td>
<td colspan="8">
<asp:Label ID="AddToBasketWarningOpt" runat="server" EnableViewState="false" SkinID="ErrorCondition" Text="Please make your selections above."></asp:Label>
</td>
</tr>
</asp:PlaceHolder>
<asp:PlaceHolder runat="server" id="phKitOptions" EnableViewState="false"></asp:PlaceHolder>
<asp:PlaceHolder ID="phAddToBasketWarningKit" runat="server" EnableViewState="false" Visible="false">
<tr>
<td> </td>
<td colspan="8">
<asp:Label ID="AddToBasketWarningKit" runat="server" EnableViewState="false" SkinID="ErrorCondition" Text="Please make your selections above."></asp:Label>
</td>
</tr>
</asp:PlaceHolder>
<tr id="rowQuantity" runat="server" enableviewstate="false">
<th class="rowHeader">
<asp:Localize ID="QuantityLocalize" runat="server" Text="Quantity:"></asp:Localize>
</th>
<td nowrap>
<cb:updowncontrol Width="30" id="Quantity" runat="server" DownImageUrl="~/images/down.gif" UpImageUrl="~/images/up.gif" Columns="2" MaxLength="5" Text='1' MaxValue="32767" onFocus="this.select()"></cb:updowncontrol>
<asp:CustomValidator ID="QuantityValidaor" runat="server" ValidationGroup="AddToBasket" ErrorMessage="Quantity can not exceed the available stock of {0}." ControlToValidate="Quantity">*</asp:CustomValidator>
<asp:PlaceHolder ID="QuantityLimitsPanel" runat="server" EnableViewState="false"></asp:PlaceHolder>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:PlaceHolder ID="InventoryDetailsPanel" runat="server" EnableViewState="false"></asp:PlaceHolder>
</td>
</tr>
<tr>
<td colspan="2">
<asp:ValidationSummary ID="ValidationSummary" runat="server" ValidationGroup="AddToBasket" />
<asp:LinkButton ID="AddToWishlistButton" runat="server" SkinID="Button" Visible="true" OnClick="AddToWishlistButton_Click" Text="Add to Wishlist" EnableViewState="false" ValidationGroup="AddToBasket"></asp:LinkButton>
<asp:LinkButton ID="AddToBasketButton" runat="server" SkinID="Button" Visible="true" OnClick="AddToBasketButton_Click" Text="Add to Cart" EnableViewState="false" ValidationGroup="AddToBasket"></asp:LinkButton>
<asp:HiddenField ID="VS" runat="server" />
<asp:LinkButton ID="AC" runat="server" SkinID="BuyNowButton" CausesValidation="false" Visible = "false">
<%-- <asp:Image ID="LI" runat="server" SkinID="BuyNowButton" AlternateText='<%# String.Format("Add {0} to Cart",ProductName) %>' /> --%>
<asp:Literal ID="LT" runat="server" Text=""></asp:Literal></asp:LinkButton>
</td>
</tr>
</table>
</ContentTemplate>
</ajax:UpdatePanel>
Here is the Code Behind File For AddToWishList.ascx.cs ( Modified Version of BuyProductsDialog )
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using CommerceBuilder.Common;
using CommerceBuilder.DigitalDelivery;
using CommerceBuilder.Orders;
using CommerceBuilder.Products;
using CommerceBuilder.Users;
using CommerceBuilder.Stores;
using CommerceBuilder.Utility;
using CommerceBuilder.Taxes;
public partial class ConLib_Custom_AddToWishList : System.Web.UI.UserControl
{
int _ProductId = 0;
Product _Product = null;
Dictionary<int, int> _SelectedOptions = null;
List<int> _SelectedKitProducts = null;
private bool _ShowSku = true;
public bool ShowSku
{
get { return _ShowSku; }
set { _ShowSku = value; }
}
private bool _ShowPrice = true;
public bool ShowPrice
{
get { return _ShowPrice; }
set { _ShowPrice = value; }
}
private bool _ShowSubscription = true;
public bool ShowSubscription
{
get { return _ShowSubscription; }
set { _ShowSubscription = value; }
}
private bool _ShowMSRP = true;
public bool ShowMSRP
{
get { return _ShowMSRP; }
set { _ShowMSRP = value; }
}
private bool _ShowPartNumber = false;
/// <summary>
/// Indicates whether the Part/Model Number will be shown or not.
/// </summary>
[Personalizable, WebBrowsable]
public bool ShowPartNumber
{
get { return _ShowPartNumber; }
set { _ShowPartNumber = value; }
}
public int ProductId
{
get { return _ProductId; }
set { _ProductId = value; }
}
public Product Product
{
set
{
if (value != null)
_ProductId = value.ProductId;
}
}
public String ProductName
{
get
{
Product product = ProductDataSource.Load(_ProductId);
if (product != null)
{
return product.Name;
}
else return String.Empty;
}
}
private void LoadCustomViewState()
{
if (Page.IsPostBack)
{
UrlEncodedDictionary customViewState = new UrlEncodedDictionary(EncryptionHelper.DecryptAES(Request.Form[VS.UniqueID]));
_ProductId = AlwaysConvert.ToInt(customViewState.TryGetValue("P"));
}
}
protected void Page_Init(object sender, System.EventArgs e)
{
LoadCustomViewState();
string key = "AddToCartLink_" + AC.UniqueID;
if (Request.Form["__EVENTTARGET"] == AC.UniqueID)
{
string value = (string)Context.Items[key];
if (string.IsNullOrEmpty(value))
{
//AddToCart();
Context.Items[key] = "ADDED";
}
}
//_ProductId = AlwaysConvert.ToInt(Request.QueryString["ProductId"]);
_Product = ProductDataSource.Load(_ProductId);
/* if (_Product != null)
{
//DISABLE PURCHASE CONTROLS BY DEFAULT
AddToBasketButton.Visible = false;
rowQuantity.Visible = false;
//HANDLE SKU ROW
trSku.Visible = (ShowSku && (_Product.Sku != string.Empty));
if (trSku.Visible)
{
Sku.Text = _Product.Sku;
}
//HANDLE PART/MODEL NUMBER ROW
trPartNumber.Visible = (ShowPartNumber && (_Product.ModelNumber != string.Empty));
if (trPartNumber.Visible)
{
PartNumber.Text = _Product.ModelNumber;
}
//HANDLE REGPRICE ROW
if (ShowMSRP)
{
LSDecimal msrpWithVAT = TaxHelper.GetShopPrice(_Product.MSRP, _Product.TaxCodeId);
if (msrpWithVAT > 0)
{
trRegPrice.Visible = true;
RegPrice.Text = msrpWithVAT.ToString("ulc");
}
else trRegPrice.Visible = false;
}
else trRegPrice.Visible = false;
// HANDLE PRICES VISIBILITY
if (ShowPrice)
{
if (!_Product.UseVariablePrice)
{
trOurPrice.Visible = true;
trVariablePrice.Visible = false;
}
else
{
trOurPrice.Visible = false;
trVariablePrice.Visible = true;
VariablePrice.Text = _Product.Price.ToString("F2");
string varPriceText = string.Empty;
Currency userCurrency = Token.Instance.User.UserCurrency;
LSDecimal userLocalMinimum = userCurrency.ConvertFromBase(_Product.MinimumPrice);
LSDecimal userLocalMaximum = userCurrency.ConvertFromBase(_Product.MaximumPrice);
if (userLocalMinimum > 0)
{
if (userLocalMaximum > 0)
{
varPriceText = string.Format("(between {0:ulcf} and {1:ulcf})", userLocalMinimum, userLocalMaximum);
}
else
{
varPriceText = string.Format("(at least {0:ulcf})", userLocalMinimum);
}
}
else if (userLocalMaximum > 0)
{
varPriceText = string.Format("({0:ulcf} maximum)", userLocalMaximum);
}
phVariablePrice.Controls.Add(new LiteralControl(varPriceText));
}
}
//UPDATE QUANTITY LIMITS
if ((_Product.MinQuantity > 0) && (_Product.MaxQuantity > 0))
{
string format = " (min {0}, max {1})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MinQuantity, _Product.MaxQuantity)));
}
else if (_Product.MinQuantity > 0)
{
string format = " (min {0})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MinQuantity)));
}
else if (_Product.MaxQuantity > 0)
{
string format = " (max {0})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MaxQuantity)));
}
if (_Product.MinQuantity > 0) Quantity.Text = _Product.MinQuantity.ToString();
//BUILD PRODUCT ATTRIBUTES
_SelectedOptions = ProductHelper.BuildProductOptions(_Product, phOptions);
//BUILD PRODUCT CHOICES
ProductHelper.BuildProductChoices(_Product, phOptions);
//BUILD KIT OPTIONS
_SelectedKitProducts = ProductHelper.BuildKitOptions(_Product, phKitOptions);
}
else
{
this.Controls.Clear();
}*/
}
private void UpdateInventoryDetails(InventoryManagerData inv)
{
if ((inv.InventoryMode == InventoryMode.None) || (inv.AllowBackorder)) return;
if (inv.InStock > 0)
{
string inStockformat = Token.Instance.Store.Settings.InventoryInStockMessage;
string inStockMessage = string.Format(inStockformat, inv.InStock);
InventoryDetailsPanel.Controls.Clear();
InventoryDetailsPanel.Controls.Add(new LiteralControl(inStockMessage));
Quantity.MaxValue = inv.InStock;
}
else
{
string outOfStockformat = Token.Instance.Store.Settings.InventoryOutOfStockMessage;
string outOfStockMessage = string.Format(outOfStockformat, inv.InStock);
InventoryDetailsPanel.Controls.Clear();
InventoryDetailsPanel.Controls.Add(new LiteralControl(outOfStockMessage));
}
}
private void HideAddToBasket()
{
AddToBasketButton.Visible = false;
AddToWishlistButton.Visible = false;
rowQuantity.Visible = false;
}
private void ShowAddToBasket()
{
AddToBasketButton.Visible = true;
AddToWishlistButton.Visible = true;
rowQuantity.Visible = true;
}
protected BasketItem GetBasketItem()
{
//GET THE QUANTITY
int tempQuantity = AlwaysConvert.ToInt(Quantity.Text, 1);
if (tempQuantity < 1) return null;
if (tempQuantity > System.Int16.MaxValue) tempQuantity = System.Int16.MaxValue;
//RECALCULATE SELECTED KIT OPTIONS
GetSelectedKitOptions();
// DETERMINE THE OPTION LIST
string optionList = ProductVariantDataSource.GetOptionList(_ProductId, _SelectedOptions, false);
//CREATE THE BASKET ITEM WITH GIVEN OPTIONS
Basket basket = Token.Instance.User.Basket;
BasketItem basketItem = BasketItemDataSource.CreateForProduct(_ProductId, (short)tempQuantity, optionList, AlwaysConvert.ToList(",", _SelectedKitProducts));
basketItem.BasketId = basket.BasketId;
//ADD IN VARIABLE PRICE
if (_Product.UseVariablePrice)
{
Currency userCurrency = Token.Instance.User.UserCurrency;
decimal userLocalPrice = AlwaysConvert.ToDecimal(VariablePrice.Text);
basketItem.Price = userCurrency.ConvertToBase(userLocalPrice);
}
ProductHelper.CollectProductTemplateInput(basketItem, this);
return basketItem;
}
private bool ValidateVariablePrice()
{
if (!_Product.UseVariablePrice) return true;
Currency userCurrency = Token.Instance.User.UserCurrency;
LSDecimal userLocalPrice = AlwaysConvert.ToDecimal(VariablePrice.Text);
LSDecimal price = userCurrency.ConvertToBase(userLocalPrice);
bool priceValid = ((price >= _Product.MinimumPrice) && ((_Product.MaximumPrice == 0) || (price <= _Product.MaximumPrice)));
if (!priceValid)
{
CustomValidator invalidPrice = new CustomValidator();
invalidPrice.IsValid = false;
invalidPrice.Text = "*";
invalidPrice.ErrorMessage = "Price does not fall within the accepted range.";
invalidPrice.ControlToValidate = "VariablePrice";
invalidPrice.ValidationGroup = "AddToBasket";
phVariablePrice.Controls.Add(invalidPrice);
}
return priceValid;
}
private bool AllProductOptionsSelected()
{
if (_SelectedOptions.Count != _Product.ProductOptions.Count)
{
phAddToBasketWarningOpt.Visible = true;
return false;
}
else
{
phAddToBasketWarningOpt.Visible = false;
return true;
}
}
private int AvailableProductOptionsCount()
{
int count = 0;
for (int i = 0; i < _Product.ProductOptions.Count; i++)
{
Option option = _Product.ProductOptions.Option;
// GET THE COLLECTION OF OPTIONS THAT ARE AVAILABLE FOR THE CURRENT SELECTIONS
OptionChoiceCollection availableChoices = OptionChoiceDataSource.GetAvailableChoices(_Product.ProductId, option.OptionId, _SelectedOptions);
if (availableChoices.Count > 0) count++;
}
return count;
}
private bool RequiredKitOptionsSelected()
{
bool requiredKitOptionsSelected = ProductHelper.RequiredKitOptionsSelected(_Product, _SelectedKitProducts);
if (requiredKitOptionsSelected)
{
phAddToBasketWarningKit.Visible = false;
return true;
}
else
{
phAddToBasketWarningKit.Visible = true;
return false;
}
}
protected bool ValidateQuantity()
{
string optionList = ProductVariantDataSource.GetOptionList(_ProductId, _SelectedOptions, true);
if (!string.IsNullOrEmpty(optionList))
{
int currentQuanity = AlwaysConvert.ToInt(Quantity.Text);
if (currentQuanity == 0)
{
QuantityValidaor.ErrorMessage = "Please enter a valid quantity.";
QuantityValidaor.IsValid = false;
return false;
}
InventoryManagerData inv = InventoryManager.CheckStock(_ProductId, optionList, _SelectedKitProducts);
if (inv.InventoryMode != InventoryMode.None && !inv.AllowBackorder && inv.InStock > 0 && currentQuanity > inv.InStock)
{
//Quantity.Text = inv.InStock.ToString();
QuantityValidaor.ErrorMessage = String.Format(QuantityValidaor.ErrorMessage, inv.InStock);
QuantityValidaor.IsValid = false;
return false;
}
}
return true;
}
protected void AddToBasketButton_Click(object sender, System.EventArgs e)
{
if (Page.IsValid && ValidateVariablePrice() && ValidateQuantity()
&& AllProductOptionsSelected() && RequiredKitOptionsSelected())
{
BasketItem basketItem = GetBasketItem();
if (basketItem != null)
{
// DETERMINE IF THE LICENSE AGREEMENT MUST BE REQUESTED
BasketItemLicenseAgreementCollection basketItemLicenseAgreements = new BasketItemLicenseAgreementCollection(basketItem, LicenseAgreementMode.OnAddToBasket);
if ((basketItemLicenseAgreements.Count > 0))
{
// THESE AGREEMENTS MUST BE ACCEPTED TO ADD TO CART
List<BasketItem> basketItems = new List<BasketItem>();
basketItems.Add(basketItem);
string guidKey = Guid.NewGuid().ToString("N");
Cache.Add(guidKey, basketItems, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 10, 0), System.Web.Caching.CacheItemPriority.NotRemovable, null);
string acceptUrl = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("~/Basket.aspx"));
string declineUrl = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(Page.ResolveClientUrl(_Product.NavigateUrl)));
Response.Redirect("~/BuyWithAgreement.aspx?Items=" + guidKey + "&AcceptUrl=" + acceptUrl + "&DeclineUrl=" + declineUrl);
}
// THERE ARE NO AGREEMENTS, SO SAVE THIS ITEM INTO THE BASKET
Basket basket = Token.Instance.User.Basket;
basket.Items.Add(basketItem);
basketItem.Save();
//Determine if there are associated Upsell products
if (basketItem.Product.GetUpsellProducts(basket).Count > 0)
{
//redirect to upsell page
string returnUrl = NavigationHelper.GetEncodedReturnUrl();
Response.Redirect("~/ProductAccessories.aspx?ProductId=" + basketItem.ProductId + "&ReturnUrl=" + returnUrl);
}
// IF BASKET HAVE SOME VALIDATION PROBLEMS MOVE TO BASKET PAGE
List<string> basketMessages;
if (!basket.Validate(out basketMessages))
{
Session.Add("BasketMessage", basketMessages);
Response.Redirect(NavigationHelper.GetBasketUrl());
}
//IF THERE IS NO REGISTERED BASKET CONTROL, WE MUST GO TO BASKET PAGE
if (!PageHelper.HasBasketControl(this.Page)) Response.Redirect(NavigationHelper.GetBasketUrl());
}
}
}
protected void AddToWishlistButton_Click(object sender, System.EventArgs e)
{
if (Page.IsValid && ValidateVariablePrice() && ValidateQuantity()
&& AllProductOptionsSelected() && RequiredKitOptionsSelected())
{
BasketItem wishlistItem = GetBasketItem();
if (wishlistItem != null)
{
// DETERMINE IF THE LICENSE AGREEMENT MUST BE REQUESTED
BasketItemLicenseAgreementCollection basketItemLicenseAgreements = new BasketItemLicenseAgreementCollection(wishlistItem, LicenseAgreementMode.OnAddToBasket);
if ((basketItemLicenseAgreements.Count > 0))
{
// THESE AGREEMENTS MUST BE ACCEPTED TO ADD TO CART
List<BasketItem> basketItems = new List<BasketItem>();
basketItems.Add(wishlistItem);
string guidKey = Guid.NewGuid().ToString("N");
Cache.Add(guidKey, basketItems, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 10, 0), System.Web.Caching.CacheItemPriority.NotRemovable, null);
string acceptUrl = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("~/Members/MyWishlist.aspx"));
string declineUrl = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(Page.ResolveClientUrl(_Product.NavigateUrl)));
Response.Redirect("~/BuyWithAgreement.aspx?Items=" + guidKey + "&AcceptUrl=" + acceptUrl + "&DeclineUrl=" + declineUrl + "&ToWishlist=True");
}
Wishlist wishlist = Token.Instance.User.PrimaryWishlist;
wishlist.Items.Add(wishlistItem);
wishlist.Save();
Response.Redirect("~/Members/MyWishlist.aspx");
}
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
//GET THE SELECTED KIT OPTIONS
//GetSelectedKitOptions();
string optionList = ProductVariantDataSource.GetOptionList(_ProductId, _SelectedOptions, true);
//SET THE CURRENT CALCULATED PRICE
OurPrice.Product = _Product;
OurPrice.OptionList = optionList;
OurPrice.SelectedKitProducts = _SelectedKitProducts;
bool allProductOptionsSelected = (_SelectedOptions.Count == _Product.ProductOptions.Count);
bool requiredKitOptionsSelected = ProductHelper.RequiredKitOptionsSelected(_Product, _SelectedKitProducts);
InventoryManagerData inv = null;
//UPDATE THE SKU FOR THE SELECTED PRODUCT VARIANT
if (_Product.ProductOptions.Count > 0 && _SelectedOptions.Count > 0)
{
ProductVariant variant = ProductVariantDataSource.LoadForOptionList(_ProductId, optionList);
if (variant != null) Sku.Text = variant.Sku;
}
//SHOW SUBSCRIPTIONS
SubscriptionPlan sp = _Product.SubscriptionPlan;
rowSubscription.Visible = (this.ShowSubscription && sp != null && sp.IsRecurring && ShowPrice);
if (rowSubscription.Visible)
{
InitialPayment.Visible = (sp.RecurringChargeSpecified);
if (InitialPayment.Visible) InitialPayment.Text = string.Format(InitialPayment.Text, _Product.Price);
string period;
if (sp.PaymentFrequency > 1) period = sp.PaymentFrequency + " " + sp.PaymentFrequencyUnit.ToString().ToLowerInvariant() + "s";
else period = sp.PaymentFrequencyUnit.ToString().ToLowerInvariant();
int numPayments = (sp.RecurringChargeSpecified ? sp.NumberOfPayments - 1 : sp.NumberOfPayments);
if (sp.NumberOfPayments == 0)
{
RecurringPayment.Text = string.Format("Recurring Payment: {0:ulc}, every {1} until canceled", sp.CalculateRecurringCharge(_Product.Price), period);
}
else
{
RecurringPayment.Text = string.Format(RecurringPayment.Text, numPayments, sp.CalculateRecurringCharge(_Product.Price), period);
}
}
CommerceBuilder.Stores.Store store = Token.Instance.Store;
if (store.EnableInventory && store.Settings.InventoryDisplayDetails
&& (_Product.InventoryMode != InventoryMode.None) && (!_Product.AllowBackorder))
{
if (allProductOptionsSelected && requiredKitOptionsSelected)
{
inv = InventoryManager.CheckStock(_ProductId, optionList, _SelectedKitProducts);
UpdateInventoryDetails(inv);
}
else
{
InventoryDetailsPanel.Controls.Clear();
}
}
HideAddToBasket();
if (!_Product.DisablePurchase && !Token.Instance.Store.Settings.ProductPurchasingDisabled)
{
if (requiredKitOptionsSelected)
{
if (inv != null)
{
if (inv.InventoryMode == InventoryMode.None || inv.InStock > 0 || inv.AllowBackorder)
{
ShowAddToBasket();
}
}
// IF NO VARIANT ARE AVAILABLE IN STOCK
else if (_Product.InventoryMode == InventoryMode.Variant && AvailableProductOptionsCount() == 0)
{
string outOfStockformat = Token.Instance.Store.Settings.InventoryOutOfStockMessage;
string outOfStockMessage = string.Format(outOfStockformat, 0);
InventoryDetailsPanel.Controls.Add(new LiteralControl(outOfStockMessage));
}
else
{
ShowAddToBasket();
}
}
}
}
protected void GetSelectedKitOptions()
{
_SelectedKitProducts = new List<int>();
//COLLECT ANY KIT VALUES
foreach (ProductKitComponent pkc in _Product.ProductKitComponents)
{
// FIND THE CONTROL
KitComponent component = pkc.KitComponent;
if (component.InputType == KitInputType.IncludedHidden)
{
foreach (KitProduct choice in component.KitProducts)
{
_SelectedKitProducts.Add(choice.KitProductId);
}
}
else
{
WebControl inputControl = (WebControl)PageHelper.RecursiveFindControl(this, component.UniqueId);
if (inputControl != null)
{
List<int> kitProducts = component.GetControlValue(inputControl);
foreach (int selectedKitProductId in kitProducts)
{
_SelectedKitProducts.Add(selectedKitProductId);
}
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
// LoadCustomViewState();
//_ProductId = AlwaysConvert.ToInt(Request.QueryString["ProductId"]);
_Product = ProductDataSource.Load(_ProductId);
if (_Product != null)
{
//DISABLE PURCHASE CONTROLS BY DEFAULT
AddToBasketButton.Visible = false;
rowQuantity.Visible = false;
//HANDLE SKU ROW
trSku.Visible = (ShowSku && (_Product.Sku != string.Empty));
if (trSku.Visible)
{
Sku.Text = _Product.Sku;
}
//HANDLE PART/MODEL NUMBER ROW
trPartNumber.Visible = (ShowPartNumber && (_Product.ModelNumber != string.Empty));
if (trPartNumber.Visible)
{
PartNumber.Text = _Product.ModelNumber;
}
//HANDLE REGPRICE ROW
if (ShowMSRP)
{
LSDecimal msrpWithVAT = TaxHelper.GetShopPrice(_Product.MSRP, _Product.TaxCodeId);
if (msrpWithVAT > 0)
{
trRegPrice.Visible = true;
RegPrice.Text = msrpWithVAT.ToString("ulc");
}
else trRegPrice.Visible = false;
}
else trRegPrice.Visible = false;
// HANDLE PRICES VISIBILITY
if (ShowPrice)
{
if (!_Product.UseVariablePrice)
{
trOurPrice.Visible = true;
trVariablePrice.Visible = false;
}
else
{
trOurPrice.Visible = false;
trVariablePrice.Visible = true;
VariablePrice.Text = _Product.Price.ToString("F2");
string varPriceText = string.Empty;
Currency userCurrency = Token.Instance.User.UserCurrency;
LSDecimal userLocalMinimum = userCurrency.ConvertFromBase(_Product.MinimumPrice);
LSDecimal userLocalMaximum = userCurrency.ConvertFromBase(_Product.MaximumPrice);
if (userLocalMinimum > 0)
{
if (userLocalMaximum > 0)
{
varPriceText = string.Format("(between {0:ulcf} and {1:ulcf})", userLocalMinimum, userLocalMaximum);
}
else
{
varPriceText = string.Format("(at least {0:ulcf})", userLocalMinimum);
}
}
else if (userLocalMaximum > 0)
{
varPriceText = string.Format("({0:ulcf} maximum)", userLocalMaximum);
}
phVariablePrice.Controls.Add(new LiteralControl(varPriceText));
}
}
//UPDATE QUANTITY LIMITS
if ((_Product.MinQuantity > 0) && (_Product.MaxQuantity > 0))
{
string format = " (min {0}, max {1})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MinQuantity, _Product.MaxQuantity)));
}
else if (_Product.MinQuantity > 0)
{
string format = " (min {0})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MinQuantity)));
}
else if (_Product.MaxQuantity > 0)
{
string format = " (max {0})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MaxQuantity)));
}
if (_Product.MinQuantity > 0) Quantity.Text = _Product.MinQuantity.ToString();
//BUILD PRODUCT ATTRIBUTES
_SelectedOptions = ProductHelper.BuildProductOptions(_Product, phOptions);
//BUILD PRODUCT CHOICES
ProductHelper.BuildProductChoices(_Product, phOptions);
//BUILD KIT OPTIONS
_SelectedKitProducts = ProductHelper.BuildKitOptions(_Product, phKitOptions);
}
else
{
this.Controls.Clear();
}
}
}
Re: How to add BuyProductDialog Control to the Product Grid?
Posted: Fri Jul 24, 2009 7:45 am
by princeatapi
A small bug with the above code is , if i try to add a product to the wishlist from the productsgrid ( if the product consist of more than one option ) validator throws an error regarding all the values to be selected for all the products in the same page
Re: How to add BuyProductDialog Control to the Product Grid?
Posted: Fri Jul 24, 2009 7:58 am
by mazhar
I have placed posted mods and its working for me no error. CategoryGridPage is listing the products with BuyProductDialog layout. It seems to me that there may be some sort of problem for example some invalid product id being passed to the control. Give a try create a new category with only two products and then navigate to that category via preview option available when editing the products and see if it makes any difference.