protected void SaveButton_Click(object sender, EventArgs e)
 {
     if (Page.IsValid)
     {
         // UPDATE THE SETTINGS
         StoreSettingsManager settings = AbleContext.Current.Store.Settings;
         settings.AffiliateParameterName   = StringHelper.Truncate(AffiliateParameter.Text.Trim(), 200);
         settings.AffiliateTrackerUrl      = StringHelper.Truncate(TrackerUrl.Text.Trim(), 200);
         settings.AffiliateAllowSelfSignup = SelfSignup.Checked;
         settings.AffiliateReferralRule    = AlwaysConvert.ToEnum <ReferralRule>(AffiliateReferralRule.SelectedValue, ReferralRule.NewSignupsOnly);
         settings.AffiliatePersistence     = ((AffiliateReferralPeriod)AlwaysConvert.ToByte(AffiliatePersistence.SelectedValue));
         AffiliateReferralPeriod referralPeriod = ((AffiliateReferralPeriod)AlwaysConvert.ToByte(AffiliatePersistence.SelectedValue));
         if ((referralPeriod != AffiliateReferralPeriod.Persistent && referralPeriod != AffiliateReferralPeriod.FirstOrder))
         {
             settings.AffiliateReferralPeriod = AlwaysConvert.ToInt16(ReferralPeriod.Text);
         }
         else
         {
             settings.AffiliateReferralPeriod = 0;
         }
         settings.AffiliateCommissionRate      = AlwaysConvert.ToDecimal(CommissionRate.Text);
         settings.AffiliateCommissionIsPercent = (CommissionType.SelectedIndex > 0);
         settings.AffiliateCommissionOnTotal   = (CommissionType.SelectedIndex == 2);
         settings.Save();
         AffiliateSettingsMessage.Text    = string.Format(AffiliateSettingsMessage.Text, LocaleHelper.LocalNow);
         AffiliateSettingsMessage.Visible = true;
     }
 }
        protected PaymentFilter GetPaymentsFilter()
        {
            // CREATE CRITERIA INSTANCE
            PaymentFilter criteria = new PaymentFilter();

            if (StartDate.SelectedStartDate > DateTime.MinValue)
            {
                criteria.DateStart = StartDate.SelectedStartDate;
            }
            if (EndDate.SelectedEndDate > DateTime.MinValue && EndDate.SelectedEndDate < DateTime.MaxValue)
            {
                criteria.DateEnd = EndDate.SelectedEndDate;
            }
            criteria.PaymentStatusId  = AlwaysConvert.ToInt16(PaymentStatusFilter.SelectedValue);
            criteria.OrderNumberRange = OrderNumberFilter.Text.Trim();
            criteria.TransactionId    = TransactionIdFilter.Text.Trim();

            List <int> paymentMethodIds = new List <int>();

            foreach (ListItem item in PaymentMethodFilter.Items)
            {
                if (item.Selected)
                {
                    paymentMethodIds.Add(AlwaysConvert.ToInt(item.Value));
                }
            }
            if (paymentMethodIds.Count > 0)
            {
                criteria.PaymentMethodIds = paymentMethodIds.ToArray();
            }

            return(criteria);
        }
Beispiel #3
0
 protected void SaveButton_Click(object sender, EventArgs e)
 {
     if (Page.IsValid)
     {
         PaymentMethod _PaymentMethod = PaymentMethodDataSource.Load(PaymentMethodId);
         _PaymentMethod.Name = Name.Text;
         _PaymentMethod.PaymentInstrumentType = (PaymentInstrumentType)AlwaysConvert.ToInt16(PaymentInstrumentList.SelectedValue);
         _PaymentMethod.PaymentGateway        = PaymentGatewayDataSource.Load(AlwaysConvert.ToInt(GatewayList.SelectedValue));
         _PaymentMethod.AllowSubscriptions    = AllowSubscriptionPayments.Checked;
         //GROUP RESTRICTION
         _PaymentMethod.Groups.Clear();
         _PaymentMethod.Save();
         if (UseGroupRestriction.SelectedIndex > 0)
         {
             foreach (ListItem item in GroupList.Items)
             {
                 Group group = GroupDataSource.Load(AlwaysConvert.ToInt(item.Value));
                 if (item.Selected)
                 {
                     _PaymentMethod.Groups.Add(group);
                 }
             }
         }
         _PaymentMethod.Save();
         //TRIGER ANY EVENT ATTACHED TO THE UPDATE
         if (ItemUpdated != null)
         {
             ItemUpdated(this, new PersistentItemEventArgs(PaymentMethodId, _PaymentMethod.Name));
         }
     }
 }
Beispiel #4
0
        private void SaveInputField()
        {
            _InputField.Name = Name.Text;
            if (!_InputField.IsMerchantField)
            {
                _InputField.IsRequired = Required.Checked;
            }
            _InputField.UserPrompt  = UserPrompt.Text;
            _InputField.InputTypeId = AlwaysConvert.ToInt16(InputTypeId.SelectedValue);
            _InputField.Columns     = AlwaysConvert.ToByte(Columns.Text);
            _InputField.Rows        = AlwaysConvert.ToByte(Rows.Text);
            _InputField.MaxLength   = AlwaysConvert.ToInt16(MaxLength.Text);
            if (_InputField.IsMerchantField)
            {
                _InputField.UseShopBy = UseShopBy.Checked;
            }
            //_InputField.IsMerchantField = (bool)ViewState["IsMerchantField"];
            //LOOP THROUGH GRID ROWS AND SET MATRIX
            int rowIndex       = 0;
            int selectedChoice = AlwaysConvert.ToInt(Request.Form["SelectedChoice"]);

            foreach (GridViewRow row in ChoicesGrid.Rows)
            {
                string      choiceText  = ((TextBox)row.FindControl("ChoiceText")).Text;
                string      choiceValue = ((TextBox)row.FindControl("ChoiceValue")).Text;
                bool        isSelected  = ((CheckBox)row.FindControl("IsSelected")).Checked;
                InputChoice thisChoice  = _InputField.InputChoices[rowIndex];
                thisChoice.ChoiceText  = choiceText;
                thisChoice.ChoiceValue = choiceValue;
                thisChoice.IsSelected  = isSelected;
                rowIndex++;
            }
            _InputField.Save();
        }
        protected void SubscriptionGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridViewRow row = SubscriptionGrid.Rows[e.RowIndex];

            int          subscriptionId = (int)SubscriptionGrid.DataKeys[e.RowIndex].Value;
            Subscription subscription   = SubscriptionDataSource.Load(subscriptionId);

            if (subscription != null)
            {
                DropDownList AutoDeliveryInterval = row.FindControl("AutoDeliveryInterval") as DropDownList;
                if (AutoDeliveryInterval != null && !string.IsNullOrEmpty(AutoDeliveryInterval.SelectedValue))
                {
                    subscription.PaymentFrequency = AlwaysConvert.ToInt16(AutoDeliveryInterval.SelectedValue);
                    subscription.RecalculateNextOrderDueDate();
                    subscription.RecalculateExpiration();

                    try
                    {
                        EmailProcessor.NotifySubscriptionUpdated(subscription);
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("Error sending subscription updated email.", ex);
                    }

                    subscription.Save();
                }
            }

            SubscriptionGrid.EditIndex = -1;
            e.Cancel = true;
        }
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            short quantity = AlwaysConvert.ToInt16(KitQuantity.Text);

            if (quantity > 0)
            {
                ProductVariant productVariant = null;
                if (_KitProduct.Product.ProductOptions.Count > 0)
                {
                    productVariant = ProductVariantDataSource.LoadForOptionList(_KitProduct.Product.Id, selectedOptions);
                }
                if (productVariant != null)
                {
                    _KitProduct.OptionList = productVariant.OptionList;
                }
                _KitProduct.Name         = DisplayName.Text;
                _KitProduct.Quantity     = quantity;
                _KitProduct.PriceModeId  = AlwaysConvert.ToByte(PriceMode.SelectedIndex);
                _KitProduct.Price        = AlwaysConvert.ToDecimal(Price.Text);
                _KitProduct.WeightModeId = AlwaysConvert.ToByte(WeightMode.SelectedIndex);
                _KitProduct.Weight       = AlwaysConvert.ToDecimal(Weight.Text);
                _KitProduct.IsSelected   = IsSelected.Checked;
                _KitProduct.Save();
            }
            Response.Redirect(string.Format("EditKit.aspx?CategoryId={0}&ProductId={1}", _CategoryId, _ProductId));
        }
        private void SaveOrder()
        {
            if (AlwaysConvert.ToInt16(ItemType.SelectedValue) == (Int16)OrderItemType.Coupon)
            {
                //IF IT IS A COUPON, VALIDATE THE ENTERED SKU ( COUPON CODE )
                if (CouponDataSource.LoadForCouponCode(Sku.Text) == null)
                {
                    CustomValidator skuValidator = new CustomValidator();
                    skuValidator.IsValid           = false;
                    skuValidator.ControlToValidate = "Sku";
                    skuValidator.ValidationGroup   = ValidationSummary.ValidationGroup;
                    skuValidator.ErrorMessage      = "Sku is not a valid coupon code.";
                    skuValidator.Text = "*";
                    phSkuValidators.Controls.Add(skuValidator);
                    return;
                }
            }
            //add the custom item
            OrderItem oi = new OrderItem();

            oi.OrderId         = _OrderId;
            oi.OrderItemTypeId = AlwaysConvert.ToInt16(ItemType.SelectedValue);
            if (_OrderShipment == null)
            {
                oi.OrderShipmentId = AlwaysConvert.ToInt(ShipmentsList.SelectedValue);
            }
            else
            {
                oi.OrderShipmentId = _OrderShipmentId;
            }
            oi.Name = Name.Text;
            oi.Sku  = Sku.Text;
            Decimal price = AlwaysConvert.ToDecimal(Price.Text);

            //We should not allow positive values for Discount or Credit.  We should not
            //  allow negative values for Charge.
            switch (oi.OrderItemTypeId)
            {
            case ((short)OrderItemType.Discount):
            case ((short)OrderItemType.Credit):
                if (price > 0)
                {
                    price = Decimal.Negate(price);
                }
                break;

            case ((short)OrderItemType.Charge):
                if (price < 0)
                {
                    price = Decimal.Negate(price);
                }
                break;
            }

            oi.Price    = price;
            oi.Quantity = AlwaysConvert.ToInt16(Quantity.Text);
            _Order.Items.Add(oi);
            _Order.Save(true, false);
        }
        protected void CheckoutButton_Click(object sender, EventArgs e)
        {
            Basket basket = AbleContext.Current.User.Basket;

            foreach (RepeaterItem saveItem in BasketRepeater.Items)
            {
                int         basketItemId      = 0;
                HiddenField basketItemIdField = (HiddenField)saveItem.FindControl("BasketItemId");
                if (basketItemIdField != null)
                {
                    basketItemId = AlwaysConvert.ToInt(basketItemIdField.Value);
                }

                if (basketItemId > 0)
                {
                    int itemIndex = basket.Items.IndexOf(basketItemId);
                    if ((itemIndex > -1))
                    {
                        BasketItem item     = basket.Items[itemIndex];
                        TextBox    quantity = (TextBox)saveItem.FindControl("Quantity");
                        if (!item.IsChildItem && item.OrderItemType == OrderItemType.Product && quantity != null)
                        {
                            item.Quantity = AlwaysConvert.ToInt16(quantity.Text);
                            // Update for Minimum Maximum quantity of product
                            if (item.Quantity < item.Product.MinQuantity)
                            {
                                item.Quantity = item.Product.MinQuantity;
                                quantity.Text = item.Quantity.ToString();
                            }
                            else if ((item.Product.MaxQuantity > 0) && (item.Quantity > item.Product.MaxQuantity))
                            {
                                item.Quantity = item.Product.MaxQuantity;
                                quantity.Text = item.Quantity.ToString();
                            }
                            item.Save();
                        }
                    }
                }
            }

            // IF THE ORDER AMOUNT DOES NOT FALL IN VALID RANGE SPECIFIED BY THE MERCHENT
            OrderItemType[] args = new OrderItemType[] { OrderItemType.Charge,
                                                         OrderItemType.Coupon, OrderItemType.Credit, OrderItemType.Discount,
                                                         OrderItemType.GiftCertificate, OrderItemType.GiftWrap, OrderItemType.Handling,
                                                         OrderItemType.Product, OrderItemType.Shipping, OrderItemType.Tax };
            decimal orderTotal     = AbleContext.Current.User.Basket.Items.TotalPrice(args);
            var     settings       = AbleContext.Current.Store.Settings;
            decimal minOrderAmount = settings.OrderMinimumAmount;
            decimal maxOrderAmount = settings.OrderMaximumAmount;

            if ((minOrderAmount > orderTotal) || (maxOrderAmount > 0 && maxOrderAmount < orderTotal))
            {
                Response.Redirect(AbleCommerce.Code.NavigationHelper.GetBasketUrl());
            }

            Response.Redirect(AbleCommerce.Code.NavigationHelper.GetCheckoutUrl());
        }
Beispiel #9
0
 protected void AddShipMethodButton_Click(object sender, EventArgs e)
 {
     if (Page.IsValid)
     {
         ShipMethod method             = new ShipMethod();
         string     selectedMethodType = AddShipMethodType.SelectedValue;
         method.ShipMethodType = ((ShipMethodType)(AlwaysConvert.ToInt16(AddShipMethodType.SelectedValue)));
         method.Name           = AddShipMethodName.Text;
         method.Save();
         Response.Redirect(GetEditUrl(method));
     }
 }
Beispiel #10
0
        protected void SaveButton_Click(object sender, System.EventArgs e)
        {
            if (Page.IsValid)
            {
                _Affiliate.Name                = Name.Text;
                _Affiliate.ReferralDays        = AlwaysConvert.ToInt16(ReferralDays.Text);
                _Affiliate.CommissionRate      = AlwaysConvert.ToDecimal(CommissionRate.Text);
                _Affiliate.CommissionIsPercent = (CommissionType.SelectedIndex > 0);
                _Affiliate.CommissionOnTotal   = (CommissionType.SelectedIndex == 2);
                _Affiliate.WebsiteUrl          = WebsiteUrl.Text;
                _Affiliate.Email               = Email.Text;
                _Affiliate.Group               = GroupDataSource.Load(AlwaysConvert.ToInt(AffiliateGroup.SelectedValue));

                AffiliateReferralPeriod referralPeriod = (AffiliateReferralPeriod)AlwaysConvert.ToByte(ReferralPeriod.SelectedValue);
                _Affiliate.ReferralPeriodId = (byte)referralPeriod;
                _Affiliate.ReferralPeriod   = referralPeriod;

                if (referralPeriod != AffiliateReferralPeriod.Persistent && referralPeriod != AffiliateReferralPeriod.FirstOrder)
                {
                    _Affiliate.ReferralDays = AlwaysConvert.ToInt16(ReferralDays.Text);
                }
                else
                {
                    _Affiliate.ReferralDays = 0;
                }

                //ADDRESS INFORMATION
                _Affiliate.FirstName    = FirstName.Text;
                _Affiliate.LastName     = LastName.Text;
                _Affiliate.Company      = Company.Text;
                _Affiliate.Address1     = Address1.Text;
                _Affiliate.Address2     = Address2.Text;
                _Affiliate.City         = City.Text;
                _Affiliate.Province     = Province.Text;
                _Affiliate.PostalCode   = PostalCode.Text;
                _Affiliate.CountryCode  = CountryCode.SelectedValue;
                _Affiliate.PhoneNumber  = PhoneNumber.Text;
                _Affiliate.FaxNumber    = FaxNumber.Text;
                _Affiliate.MobileNumber = MobileNumber.Text;
                _Affiliate.Save();

                // SAVE TAX ID
                User user = _Affiliate.Group != null && _Affiliate.Group.Users.Count > 0 ? _Affiliate.Group.Users[0] : null;
                if (user != null)
                {
                    user.TaxExemptionReference = TaxId.Text;
                    user.Save();
                }

                SavedMessage.Visible = true;
                SavedMessage.Text    = string.Format(SavedMessage.Text, LocaleHelper.LocalNow);
            }
        }
 protected void SaveButton_Click(object sender, System.EventArgs e)
 {
     //Save the option itself
     _Option.Name             = OptionName.Text;
     _Option.HeaderText       = HeaderText.Text;
     _Option.ShowThumbnails   = ShowThumbnails.Checked;
     _Option.ThumbnailColumns = AlwaysConvert.ToByte(ThumbnailColumns.Text);
     _Option.ThumbnailHeight  = AlwaysConvert.ToInt16(ThumbnailHeight.Text);
     _Option.ThumbnailWidth   = AlwaysConvert.ToInt16(ThumbnailWidth.Text);
     _Option.Save();
     SavedMessage.Text    = string.Format(SavedMessage.Text, LocaleHelper.LocalNow);
     SavedMessage.Visible = true;
 }
Beispiel #12
0
        protected void MultipleAddToBasketButton_Click(object sender, EventArgs e)
        {
            string lastShoppingUrl = AbleCommerce.Code.NavigationHelper.GetLastShoppingUrl();
            Basket basket          = AbleContext.Current.User.Basket;
            //A LIST TO HOLD BASKET ITEMS THAT NEED A LICENCE AGREEMENT TO BE ACCEPTED
            List <BasketItem> agreementItems = new List <BasketItem>();

            foreach (DataListItem item in ProductList.Items)
            {
                TextBox quantityBox = (TextBox)AbleCommerce.Code.PageHelper.RecursiveFindControl(item, "Quantity");
                if (quantityBox != null)
                {
                    short quantity = AlwaysConvert.ToInt16(quantityBox.Text);
                    if (quantity > 0)
                    {
                        int        productId  = AlwaysConvert.ToInt(((HiddenField)AbleCommerce.Code.PageHelper.RecursiveFindControl(item, "HiddenProductId")).Value);
                        BasketItem basketItem = GetBasketItem(productId, quantity);
                        // DETERMINE IF THE LICENSE AGREEMENT MUST BE REQUESTED
                        IList <LicenseAgreement> basketItemLicenseAgreements = new List <LicenseAgreement>();
                        basketItemLicenseAgreements.BuildCollection(basketItem, LicenseAgreementMode.OnAddToBasket);
                        if ((basketItemLicenseAgreements.Count > 0))
                        {
                            // THESE AGREEMENTS MUST BE ACCEPTED TO ADD TO CART
                            agreementItems.Add(basketItem);
                        }
                        else
                        {
                            basket.Items.Add(basketItem);
                        }
                    }
                }
            }

            basket.Save();

            if (agreementItems.Count > 0)
            {
                // THESE AGREEMENTS MUST BE ACCEPTED TO ADD TO CART
                string guidKey = Guid.NewGuid().ToString("N");
                Cache.Add(guidKey, agreementItems, 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(lastShoppingUrl));
                Response.Redirect("~/BuyWithAgreement.aspx?Items=" + guidKey + "&AcceptUrl=" + acceptUrl + "&DeclineUrl=" + declineUrl);
            }
            else
            {
                //REDIRECT TO BASKET PAGE
                Response.Redirect("~/Basket.aspx");
            }
        }
Beispiel #13
0
        private void SaveWishlist()
        {
            Wishlist wishlist = AbleContext.Current.User.PrimaryWishlist;
            int      rowIndex = 0;

            foreach (GridViewRow saverow in WishlistGrid.Rows)
            {
                int wishlistItemId = (int)WishlistGrid.DataKeys[rowIndex].Value;
                int itemIndex      = wishlist.WishlistItems.IndexOf(wishlistItemId);
                if (itemIndex > -1)
                {
                    WishlistItem item    = wishlist.WishlistItems[itemIndex];
                    TextBox      desired = saverow.FindControl("Desired") as TextBox;
                    if (desired != null)
                    {
                        item.Desired = AlwaysConvert.ToInt16(desired.Text, item.Desired);
                        if (item.Desired <= 0)
                        {
                            item.Delete();
                        }
                    }
                    DropDownList priority = saverow.FindControl("Priority") as DropDownList;
                    if (priority != null)
                    {
                        item.Priority = AlwaysConvert.ToByte(priority.SelectedValue);
                        if (item.Priority < 0)
                        {
                            item.Priority = 0;
                        }
                        if (item.Priority > 4)
                        {
                            item.Priority = 4;
                        }
                    }
                    TextBox comment = saverow.FindControl("Comment") as TextBox;
                    if (comment != null)
                    {
                        item.Comment = StringHelper.StripHtml(comment.Text);
                    }
                    rowIndex++;
                }
            }
            wishlist.Save();
        }
        protected IList <OrderItem> GetOrderItems()
        {
            //GET THE PRODUCT ID
            int     productId = AlwaysConvert.ToInt(HiddenProductId.Value);
            Product product   = ProductDataSource.Load(productId);

            if (product == null)
            {
                return(null);
            }
            //GET THE QUANTITY
            short tempQuantity = AlwaysConvert.ToInt16(Quantity.Text);

            if (tempQuantity < 1)
            {
                return(null);
            }
            if (tempQuantity > System.Int16.MaxValue)
            {
                tempQuantity = System.Int16.MaxValue;
            }

            //RECALCULATE SELECTED KIT OPTIONS
            GetSelectedKitOptions(product);
            // DETERMINE THE OPTION LIST
            string optionList = ProductVariantDataSource.GetOptionList(productId, _SelectedOptions, false);
            //CREATE THE BASKET ITEM WITH GIVEN OPTIONS

            IList <OrderItem> orderItems = OrderItemDataSource.CreateForProduct(productId, tempQuantity, optionList, AlwaysConvert.ToList(",", _SelectedKitProducts));

            if (orderItems.Count > 0)
            {
                // COLLECT ANY ADDITIONAL INPUTS FOR BASE ITEM
                AbleCommerce.Code.ProductHelper.CollectProductTemplateInput(orderItems[0], phOptions);

                // UPADATE THE PRICE OF BASE ITEM IF NEEDED ( KIT PRICE WILL NOT BE MODIFIED)
                if (orderItems[0].Price != AlwaysConvert.ToDecimal(Price.Text) && (product.KitStatus != KitStatus.Master))
                {
                    orderItems[0].Price = AlwaysConvert.ToDecimal(Price.Text);
                }
            }
            return(orderItems);
        }
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            AbleContext.Current.Database.BeginTransaction();
            Payment payment = new Payment();

            payment.OrderId             = OrderId;
            payment.PaymentMethodId     = AlwaysConvert.ToInt(SelectedPaymentMethod.SelectedValue);
            payment.ReferenceNumber     = ReferenceNumber.Text;
            payment.Amount              = AlwaysConvert.ToDecimal(Amount.Text);
            payment.CurrencyCode        = "USD";
            payment.PaymentStatusId     = AlwaysConvert.ToInt16(selPaymentStatus.SelectedValue);
            payment.PaymentStatusReason = PaymentStatusReason.Text;
            Order.Payments.Add(payment);
            string addNote = string.Format("A payment of type {0} and amount {1:c} is recorded as {2}.", payment.PaymentMethodName, payment.Amount, payment.PaymentStatus);

            Order.Notes.Add(new OrderNote(Order.Id, AbleContext.Current.UserId, LocaleHelper.LocalNow, addNote, NoteType.SystemPrivate));
            Order.Save(true, true);
            AbleContext.Current.Database.CommitTransaction();
            Response.Redirect(CancelLink.NavigateUrl);
        }
Beispiel #16
0
        private void Save()
        {
            _Subscription.Name = SubscriptionName.Text;
            int selectedGroupId = AlwaysConvert.ToInt(SubscriptionGroup.SelectedValue);

            _Subscription.GroupId  = selectedGroupId;
            _Subscription.IsActive = Active.Checked;
            short frequency = AlwaysConvert.ToInt16(Frequency.Text);

            // IF PAYMENT FREQUENCY IS CHANGED BY MERCHANT
            if (trFrequency.Visible && frequency > 0 && _Subscription.PaymentFrequency != frequency)
            {
                _Subscription.PaymentFrequency = frequency;

                // RECALCULATE NEXT ORDER DATE ACCORDING TO NEW FREQUENCY VALUE
                _Subscription.RecalculateNextOrderDueDate();

                // RECALCULATE EXPIRATION ACCORDING TO NEW FREQUENCY VALUE
                _Subscription.RecalculateExpiration();
            }

            short numberOfPayments = AlwaysConvert.ToInt16(NumberOfPayments.Text);

            if (numberOfPayments != _Subscription.NumberOfPayments)
            {
                _Subscription.NumberOfPayments = numberOfPayments;
                _Subscription.RecalculateExpiration();
            }

            try
            {
                EmailProcessor.NotifySubscriptionUpdated(_Subscription);
            }
            catch (Exception ex)
            {
                Logger.Error("Error sending subscription updated email.", ex);
            }

            _Subscription.Save();
            InitFormValues();
        }
        protected void SaveEditButton_Click(object sender, EventArgs e)
        {
            int itemId = AlwaysConvert.ToInt(EditItemId.Value);
            int index  = _Order.Items.IndexOf(itemId);

            if (index > -1)
            {
                OrderItem orderItem = _Order.Items[index];
                orderItem.Price    = AlwaysConvert.ToDecimal(EditItemPrice.Text);
                orderItem.Quantity = AlwaysConvert.ToInt16(EditItemQuantity.Text);

                // Do not allow positive values for Discount/Credit or negative values for charge
                switch (orderItem.OrderItemTypeId)
                {
                case ((short)OrderItemType.Discount):
                case ((short)OrderItemType.Credit):
                    if (orderItem.Price > 0)
                    {
                        orderItem.Price = Decimal.Negate((Decimal)orderItem.Price);
                    }
                    break;

                case ((short)OrderItemType.Charge):
                    if (orderItem.Price < 0)
                    {
                        orderItem.Price = Decimal.Negate((Decimal)orderItem.Price);
                    }
                    break;

                default:
                    break;
                }

                // UPDATE THE CALCULATED SUMMARY VALUES OF ORDER
                _Order.Save(true, false);
                BindGrids();
            }
            EditItemPopup.Hide();
        }
        protected void AddButton_Click(object sender, System.EventArgs e)
        {
            PaymentMethod method = new PaymentMethod();

            method.Name = Name.Text;
            method.PaymentInstrumentType = (PaymentInstrumentType)AlwaysConvert.ToInt16(PaymentInstrumentList.SelectedValue);
            method.PaymentGateway        = PaymentGatewayDataSource.Load(AlwaysConvert.ToInt(GatewayList.SelectedValue));
            method.AllowSubscriptions    = AllowSubscriptionPayments.Checked;
            //GROUP RESTRICTION
            if (UseGroupRestriction.SelectedIndex > 0)
            {
                foreach (ListItem item in GroupList.Items)
                {
                    Group group = GroupDataSource.Load(AlwaysConvert.ToInt(item.Value));
                    if (item.Selected)
                    {
                        method.Groups.Add(group);
                    }
                }
            }
            method.OrderBy = (short)PaymentMethodDataSource.GetNextOrderBy();
            method.Save();
            //UPDATE THE ADD MESSAGE
            AddedMessage.Text    = string.Format(AddedMessage.Text, method.Name);
            AddedMessage.Visible = true;
            //RESET THE ADD FORM
            PaymentInstrumentList.SelectedIndex = -1;
            Name.Text = string.Empty;
            GatewayList.SelectedIndex         = -1;
            AllowSubscriptionPayments.Checked = false;
            UseGroupRestriction.SelectedIndex = 0;
            BindGroups();
            //TRIGER ANY EVENT ATTACHED TO THE UPDATE
            if (ItemAdded != null)
            {
                ItemAdded(this, new PersistentItemEventArgs(method.Id, method.Name));
            }
        }
 private int CreateInput()
 {
     if (Page.IsValid)
     {
         InputField input = new InputField();
         input.ProductTemplateId = _ProductTemplateId;
         input.Name            = Name.Text;
         input.UserPrompt      = UserPrompt.Text;
         input.InputTypeId     = AlwaysConvert.ToInt16(InputTypeId.SelectedValue);
         input.Columns         = AlwaysConvert.ToByte(Columns.Text);
         input.Rows            = AlwaysConvert.ToByte(Rows.Text);
         input.MaxLength       = AlwaysConvert.ToInt16(MaxLength.Text);
         input.IsMerchantField = (bool)ViewState["IsMerchantField"];
         if (!input.IsMerchantField)
         {
             input.IsRequired = Required.Checked;
         }
         input.UseShopBy = trUseShopBy.Visible ? UseShopBy.Checked : false;
         input.Save();
         return(input.Id);
     }
     return(0);
 }
        private void SaveBasket()
        {
            int rowIndex = 0;

            foreach (GridViewRow saverow in BasketGrid.Rows)
            {
                int basketItemId = (int)BasketGrid.DataKeys[rowIndex].Value;
                int itemIndex    = _Basket.Items.IndexOf(basketItemId);
                if ((itemIndex > -1))
                {
                    BasketItem item = _Basket.Items[itemIndex];
                    if ((item.OrderItemType == OrderItemType.Product))
                    {
                        TextBox quantity = (TextBox)saverow.FindControl("Quantity");
                        if (quantity != null)
                        {
                            item.Quantity = AlwaysConvert.ToInt16(quantity.Text);
                            // Update for Minimum Maximum quantity of product
                            if (item.Quantity < item.Product.MinQuantity)
                            {
                                item.Quantity = item.Product.MinQuantity;
                                quantity.Text = item.Quantity.ToString();
                            }
                            else if ((item.Product.MaxQuantity > 0) && (item.Quantity > item.Product.MaxQuantity))
                            {
                                item.Quantity = item.Product.MaxQuantity;
                                quantity.Text = item.Quantity.ToString();
                            }
                        }
                    }
                    rowIndex++;
                }
            }
            // SAVE THE WHOLE BASKET
            _Basket.Save();
        }
Beispiel #21
0
        private void SaveSettings()
        {
            Store store = AbleContext.Current.Store;
            StoreSettingsManager settings = store.Settings;

            store.Name = StoreName.Text;
            store.VolumeDiscountMode       = (VolumeDiscountMode)DiscountMode.SelectedIndex;
            store.WeightUnit               = (WeightUnit)AlwaysConvert.ToInt(WeightUnit.SelectedValue);
            store.MeasurementUnit          = (MeasurementUnit)AlwaysConvert.ToInt(MeasurementUnit.SelectedValue);
            settings.TimeZoneCode          = TimeZoneOffset.SelectedValue;
            settings.TimeZoneOffset        = GetTimeZoneOffset(TimeZoneOffset.SelectedValue);
            settings.PostalCodeCountries   = PostalCodeCountries.Text.Replace(" ", string.Empty);
            settings.SiteDisclaimerMessage = SiteDisclaimerMessage.Text.Trim();

            // INVENTORY
            store.Settings.EnableInventory                       = EnableInventory.Checked;
            settings.InventoryDisplayDetails                     = CurrentInventoryDisplayMode.SelectedIndex == 1;
            settings.InventoryInStockMessage                     = InStockMessage.Text;
            settings.InventoryOutOfStockMessage                  = OutOfStockMessage.Text;
            settings.InventoryAvailabilityMessage                = InventoryAvailabilityMessage.Text;
            settings.InventoryRestockNotificationLink            = RestockNotificationLink.Text;
            settings.InventoryRestockNotificationEmailTemplateId = AlwaysConvert.ToInt(RestockNotificationEmail.SelectedValue);

            // ORDERS
            short increment = AlwaysConvert.ToInt16(OrderIdIncrement.Text);

            if (increment >= 1)
            {
                store.OrderIdIncrement = increment;
            }
            settings.CheckoutTermsAndConditions     = CheckoutTerms.Text.Trim();
            settings.OrderMinimumAmount             = AlwaysConvert.ToDecimal(OrderMinAmount.Text);
            settings.OrderMaximumAmount             = AlwaysConvert.ToDecimal(OrderMaxAmount.Text);
            settings.AcceptOrdersWithInvalidPayment = IgnoreFailedPayments.Checked;
            settings.EnablePartialPaymentCheckouts  = AllowPartialPaymnets.Checked;

            settings.EnableOnePageCheckout  = EnableOnePageCheckout.Checked;
            settings.AllowAnonymousCheckout = AllowGuestCheckout.Checked || LimitedGuestCheckout.Checked;
            settings.AllowAnonymousCheckoutForDigitalGoods = !LimitedGuestCheckout.Checked;
            settings.EnableCustomerOrderNotes      = EnableOrderNotes.Checked;
            settings.EnableShipMessage             = EnableShipMessage.Checked;
            settings.EnableShipToMultipleAddresses = EnableShipToMultipleAddresses.Checked;

            // PRODUCTS PURCHASING
            settings.ProductPurchasingDisabled = ProductPurchasingDisabled.Checked;

            // WISHLISTS ENABLED
            settings.WishlistsEnabled = WishlistsEnabled.Checked;

            // RESTRICT STORE ACCESS
            settings.RestrictStoreAccess = (AccessRestrictionType)Enum.Parse(typeof(AccessRestrictionType), RestrictStoreAccessOptions.SelectedValue);
            if (settings.RestrictStoreAccess == AccessRestrictionType.AuthorizedGroupsOnly)
            {
                IList <Group> allGroups      = GroupDataSource.LoadForStore(AbleContext.Current.StoreId, "Name ASC");
                IList <Group> nonAdminGroups = allGroups.FindAll(grp => !grp.IsInRole(Role.AllAdminRoles)) as IList <Group>;

                // remove permissions for all non-admin groups
                Role authorizedUserRole = RoleDataSource.LoadForRolename(Role.CustomerRoles[0]);
                foreach (Group group in nonAdminGroups)
                {
                    group.Roles.Remove(authorizedUserRole);
                }
                foreach (ListItem item in AuthorizedGroups.Items)
                {
                    if (item.Selected)
                    {
                        int groupId = AlwaysConvert.ToInt(item.Value);
                        foreach (Group group in nonAdminGroups)
                        {
                            // add permissions for selected groups
                            if (groupId == group.Id)
                            {
                                group.Roles.Add(authorizedUserRole);
                            }
                        }
                    }
                }
                nonAdminGroups.Save();
            }

            // SEARCH SETTINGS
            settings.WishlistSearchEnabled        = EnableWishlistSearch.Checked;
            settings.MinimumSearchLength          = AlwaysConvert.ToInt(MinimumSearchLength.Text);
            settings.PopularSearchThreshold       = AlwaysConvert.ToInt(PopularSearchThreshold.Text);
            settings.CategorySearchDisplayLimit   = AlwaysConvert.ToInt(CategorySearchDisplayLimit.Text);
            settings.EnablePaymentProfilesStorage = PaymentStorage.Checked;

            // HTML EDITOR SETTING
            settings.EnableWysiwygEditor = EnableHtmlEditor.Checked;

            store.Save();

            // CHECK NEXT ORDER NUMBER
            if (OrigNextOrderNumber.Value != NextOrderId.Text)
            {
                // NEXT ORDER NUMBER WAS UPDATED
                store.NextOrderId         = StoreDataSource.SetNextOrderNumber(AlwaysConvert.ToInt(NextOrderId.Text));
                OrigNextOrderNumber.Value = store.NextOrderId.ToString();
            }
            else
            {
                // DETERMINE CORRECT VALUE FOR NEXT ORDER NUMBER
                OrigNextOrderNumber.Value = StoreDataSource.GetNextOrderNumber(false).ToString();
            }
            OrderIdIncrement.Text = store.OrderIdIncrement.ToString();
            UpdateNextOrderNumber(store);
            store.Save();

            if (SearchProvider.SelectedValue != ApplicationSettings.Instance.SearchProvider)
            {
                ApplicationSettings.Instance.SearchProvider = SearchProvider.SelectedValue;
                ApplicationSettings.Instance.Save();

                if (SearchProvider.SelectedValue == "SqlFtsSearchProvider")
                {
                    bool fullTextSearch = false;
                    // FTS IS TURNED ON, MAKE SURE THE CATALOG IS AVAILABLE
                    if (KeywordSearchHelper.EnsureCatalog())
                    {
                        // CATALOG IS FOUND, MAKE SURE INDEXES ARE AVAILABLE
                        if (KeywordSearchHelper.EnsureIndexes())
                        {
                            // FTS CAN BE SAFELY ENABLED
                            fullTextSearch = true;
                        }
                    }

                    if (!fullTextSearch)
                    {
                        KeywordSearchHelper.RemoveCatalog();
                    }
                }

                if (SearchProvider.SelectedValue == "LuceneSearchProvider")
                {
                    AbleContext.Resolve <IFullTextSearchService>().AsyncReindex();
                }
            }
        }
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                // DUPLICATE TAX RULE NAMES SHOULD NOT BE ALLOWED
                int taxRuleId = TaxRuleDataSource.GetTaxRuleIdByName(Name.Text);
                if (taxRuleId > 0)
                {
                    // TAX RULE(S) WITH SAME NAME ALREADY EXIST
                    CustomValidator customNameValidator = new CustomValidator();
                    customNameValidator.ControlToValidate = "Name";
                    customNameValidator.Text         = "*";
                    customNameValidator.ErrorMessage = "A Tax Rule with the same name already exists.";
                    customNameValidator.IsValid      = false;
                    phNameValidator.Controls.Add(customNameValidator);
                    return;
                }
                //SAVE TAX RULE
                TaxRule taxRule = new TaxRule();
                taxRule.Name              = Name.Text;
                taxRule.TaxRate           = AlwaysConvert.ToDecimal(TaxRate.Text);
                taxRule.UseBillingAddress = AlwaysConvert.ToBool(UseBillingAddress.SelectedValue.Equals("1"), false);
                taxRule.TaxCodeId         = AlwaysConvert.ToInt(TaxCode.SelectedValue);
                taxRule.Priority          = AlwaysConvert.ToInt16(Priority.Text);
                taxRule.UsePerItemTax     = PerUnitCalculation.Checked;
                taxRule.Save();
                //UPDATE TAX CODES
                taxRule.TaxCodes.Clear();
                taxRule.Save();
                foreach (ListItem listItem in TaxCodes.Items)
                {
                    if (listItem.Selected)
                    {
                        TaxCode taxCode = TaxCodeDataSource.Load(AlwaysConvert.ToInt(listItem.Value));
                        taxRule.TaxCodes.Add(taxCode);
                        listItem.Selected = false;
                    }
                }
                //UPDATE ZONES
                taxRule.ShipZones.Clear();
                if (ZoneRule.SelectedIndex > 0)
                {
                    foreach (ListItem item in ZoneList.Items)
                    {
                        ShipZone shipZone = ShipZoneDataSource.Load(AlwaysConvert.ToInt(item.Value));
                        if (item.Selected)
                        {
                            taxRule.ShipZones.Add(shipZone);
                        }
                    }
                }
                //UPDATE GROUP FILTER
                taxRule.Groups.Clear();
                taxRule.GroupRule = (FilterRule)GroupRule.SelectedIndex;
                if (taxRule.GroupRule != FilterRule.All)
                {
                    foreach (ListItem item in GroupList.Items)
                    {
                        Group group = GroupDataSource.Load(AlwaysConvert.ToInt(item.Value));
                        if (item.Selected)
                        {
                            taxRule.Groups.Add(group);
                        }
                    }
                }
                //IF NO GROUPS ARE SELECTED, APPLY TO ALL GROUPS
                if (taxRule.Groups.Count == 0)
                {
                    taxRule.GroupRule = FilterRule.All;
                }

                // UPDATE ROUNDING RULE
                taxRule.RoundingRuleId = AlwaysConvert.ToByte(RoundingRule.SelectedValue);

                taxRule.Save();
                //UPDATE THE ADD MESSAGE
                Response.Redirect("TaxRules.aspx");
            }
        }
        protected void AddProductPrice_PreRender(object sender, EventArgs e)
        {
            int     productId = AlwaysConvert.ToInt(AddProductId.Value);
            Product product   = ProductDataSource.Load(productId);

            if (product != null)
            {
                //GET THE SELECTED KIT OPTIONS
                GetSelectedKitOptions(product);
                //SET THE CURRENT CALCULATED PRICE
                string            optionList            = ProductVariantDataSource.GetOptionList(productId, _SelectedOptions, true);
                bool              calculateOneTimePrice = AlwaysConvert.ToBool(OptionalSubscription.SelectedValue, false);
                ProductCalculator pcalc = ProductCalculator.LoadForProduct(productId, 1, optionList, AlwaysConvert.ToList(",", _SelectedKitProducts), _UserId, false, calculateOneTimePrice);
                AddProductPrice.Text = string.Format("{0:F2}", pcalc.Price);

                if (product.IsSubscription)
                {
                    if (product.SubscriptionPlan.IsRecurring)
                    {
                        if (!calculateOneTimePrice)
                        {
                            short frequency = product.SubscriptionPlan.PaymentFrequencyType == PaymentFrequencyType.Optional ? AlwaysConvert.ToInt16(AutoDeliveryInterval.SelectedValue) : product.SubscriptionPlan.PaymentFrequency;
                            SubscriptionMessage.Text    = ProductHelper.GetRecurringPaymentMessage(product.Price, 0, product.SubscriptionPlan, frequency);
                            SubscriptionMessage.Visible = true;
                        }
                        else
                        {
                            SubscriptionMessage.Visible = false;
                        }
                    }
                    else
                    {
                        trSubscriptionRow.Visible = product.SubscriptionPlan.IsOptional;
                    }
                }
                else
                {
                    trSubscriptionRow.Visible = false;
                }

                if (product.UseVariablePrice && !product.IsSubscription && !product.IsKit)
                {
                    AddProductVariablePrice.Text    = string.Format("{0:F2}", pcalc.Price);
                    AddProductVariablePrice.Visible = true;
                    string varPriceText = string.Empty;
                    if (product.MinimumPrice > 0)
                    {
                        if (product.MaximumPrice > 0)
                        {
                            varPriceText = string.Format("(between {0} and {1})", product.MinimumPrice.LSCurrencyFormat("lcf"), product.MaximumPrice.LSCurrencyFormat("lcf"));
                        }
                        else
                        {
                            varPriceText = string.Format("(at least {0})", product.MinimumPrice.LSCurrencyFormat("lcf"));
                        }
                    }
                    else if (product.MaximumPrice > 0)
                    {
                        varPriceText = string.Format("({0} maximum)", product.MaximumPrice.LSCurrencyFormat("lcf"));
                    }
                    phVariablePrice.Controls.Add(new LiteralControl(varPriceText));
                }
                AddProductPrice.Visible = !AddProductVariablePrice.Visible;
                if ((AddProductPrice.Visible && _Basket.UserId == AbleContext.Current.UserId) || (product.IsKit))
                {
                    AddProductPrice.Enabled = false;
                }
            }
        }
Beispiel #24
0
        private void Save(SubscriptionPlan sp)
        {
            sp.Id   = _Product.Id;
            sp.Name = Name.Text;
            switch (BillingOption.SelectedIndex)
            {
            case 0:
                // ONE TIME CHARGE
                sp.NumberOfPayments         = 1;
                sp.RecurringCharge          = 0;
                sp.RecurringChargeSpecified = false;
                sp.RecurringTaxCodeId       = 0;
                sp.PaymentFrequency         = AlwaysConvert.ToInt16(Expiration.Text);
                if (ExpirationUnit.SelectedIndex == 0)
                {
                    sp.PaymentFrequencyUnit = PaymentFrequencyUnit.Day;
                }
                else
                {
                    sp.PaymentFrequencyUnit = PaymentFrequencyUnit.Month;
                }
                break;

            case 1:
                // RECURRING CHARGE
                sp.NumberOfPayments         = AlwaysConvert.ToInt16(NumberOfPayments.Text);
                sp.RecurringCharge          = 0;
                sp.RecurringChargeSpecified = false;
                sp.RecurringTaxCodeId       = 0;
                break;

            case 2:
                // INITIAL CHARGE WITH DIFFERENT RECURRING CHARGE
                sp.NumberOfPayments         = AlwaysConvert.ToInt16(NumberOfPayments.Text);
                sp.RecurringCharge          = AlwaysConvert.ToDecimal(RecurringCharge.Text);;
                sp.RecurringChargeSpecified = true;
                sp.RecurringChargeMode      = (InheritanceMode)Enum.Parse(typeof(InheritanceMode), RecurringChargeMode.SelectedValue);
                sp.RecurringTaxCodeId       = AlwaysConvert.ToInt(RecurringTaxCode.SelectedValue);
                break;
            }

            if (BillingOption.SelectedIndex != 0)
            {
                if (FixedFrequencyCheck.Checked)
                {
                    sp.PaymentFrequency           = AlwaysConvert.ToInt16(FixedPaymentFrequency.Text);
                    sp.OptionalPaymentFrequencies = string.Empty;
                    sp.PaymentFrequencyType       = CommerceBuilder.Products.PaymentFrequencyType.Fixed;
                    if (FixedPaymentFrequencyUnits.SelectedIndex == 0)
                    {
                        sp.PaymentFrequencyUnit = PaymentFrequencyUnit.Day;
                    }
                    else
                    {
                        sp.PaymentFrequencyUnit = PaymentFrequencyUnit.Month;
                    }
                }
                else
                if (CustomFrequencyCheck.Checked)
                {
                    sp.OptionalPaymentFrequencies = CustomPaymentFrequency.Text;
                    sp.PaymentFrequency           = 0;
                    sp.PaymentFrequencyType       = CommerceBuilder.Products.PaymentFrequencyType.Optional;
                    if (CustomPaymentFrequencyUnit.SelectedIndex == 0)
                    {
                        sp.PaymentFrequencyUnit = PaymentFrequencyUnit.Day;
                    }
                    else
                    {
                        sp.PaymentFrequencyUnit = PaymentFrequencyUnit.Month;
                    }
                }
                else
                {
                    sp.PaymentFrequencyType = CommerceBuilder.Products.PaymentFrequencyType.Fixed;
                }
            }

            sp.GroupId                = AlwaysConvert.ToInt(SubscriptionGroup.SelectedValue);
            sp.IsOptional             = AllowOneTimePurchase.Checked;
            sp.OneTimeCharge          = AlwaysConvert.ToDecimal(OneTimePrice.Text);
            sp.OneTimeChargeMode      = (InheritanceMode)Enum.Parse(typeof(InheritanceMode), OneTimePriceMode.SelectedValue);
            sp.Description            = SalePitch.Text;
            sp.OneTimeChargeTaxCodeId = AlwaysConvert.ToInt(OneTimePriceTaxCode.SelectedValue);
            sp.Save();
            SavedMessage.Text    = string.Format(SavedMessage.Text, LocaleHelper.LocalNow);
            SavedMessage.Visible = true;
        }
        private void SaveProduct()
        {
            // get a reference to the loaded product
            // this assists in file comparions between add/edit page
            Product product = _Product;

            // basic product information pane
            product.Name           = Name.Text;
            product.ManufacturerId = AlwaysConvert.ToInt(ManufacturerList.SelectedValue);
            product.Price          = AlwaysConvert.ToDecimal(Price.Text);
            product.ModelNumber    = ModelNumber.Text;
            product.MSRP           = AlwaysConvert.ToDecimal(Msrp.Text);
            product.Weight         = AlwaysConvert.ToDecimal(Weight.Text);
            product.CostOfGoods    = AlwaysConvert.ToDecimal(CostOfGoods.Text);
            product.GTIN           = Gtin.Text;
            product.Sku            = Sku.Text;
            product.IsFeatured     = IsFeatured.Checked;

            // descriptions
            product.Summary             = Summary.Text;
            product.Description         = Description.Text;
            product.ExtendedDescription = ExtendedDescription.Text;

            // shipping, tax, and inventory
            product.WarehouseId = AlwaysConvert.ToInt(Warehouse.SelectedValue);
            product.VendorId    = AlwaysConvert.ToInt(Vendor.SelectedValue);
            product.ShippableId = (byte)AlwaysConvert.ToInt(IsShippable.SelectedValue);
            product.Length      = AlwaysConvert.ToDecimal(Length.Text);
            product.Width       = AlwaysConvert.ToDecimal(Width.Text);
            product.Height      = AlwaysConvert.ToDecimal(Height.Text);
            product.TaxCodeId   = AlwaysConvert.ToInt(TaxCode.SelectedValue);
            if (CurrentInventoryMode.Visible)
            {
                product.InventoryModeId = AlwaysConvert.ToByte(CurrentInventoryMode.SelectedIndex);
                if (product.InventoryMode == InventoryMode.Product)
                {
                    product.InStock             = AlwaysConvert.ToInt(InStock.Text);
                    product.AvailabilityDate    = AvailabilityDate.SelectedDate;
                    product.InStockWarningLevel = AlwaysConvert.ToInt(LowStock.Text);
                    product.AllowBackorder      = BackOrder.Checked;
                }
                else if (product.InventoryMode == InventoryMode.Variant)
                {
                    product.AllowBackorder = BackOrder.Checked;
                }

                product.EnableRestockNotifications = EnableRestockNotifications.Checked;
            }

            // advanced settings
            product.WrapGroupId       = AlwaysConvert.ToInt(WrapGroup.SelectedValue);
            product.AllowReviews      = AllowReviewsPanel.Visible ? AllowReviews.Checked : true;
            product.Visibility        = (CatalogVisibility)Visibility.SelectedIndex;
            product.HidePrice         = HidePrice.Checked;
            product.Webpage           = WebpageDataSource.Load(AlwaysConvert.ToInt(DisplayPage.SelectedValue));
            product.IsProhibited      = IsProhibited.Checked;
            product.IsGiftCertificate = GiftCertificate.Checked;
            product.DisablePurchase   = DisablePurchase.Checked;
            product.UseVariablePrice  = UseVariablePrice.Checked;
            product.MinimumPrice      = AlwaysConvert.ToDecimal(MinPrice.Text);
            product.MaximumPrice      = AlwaysConvert.ToDecimal(MaxPrice.Text);
            product.HandlingCharges   = AlwaysConvert.ToDecimal(HandlingCharges.Text);
            product.MinQuantity       = AlwaysConvert.ToInt16(MinQuantity.Text);
            product.MaxQuantity       = AlwaysConvert.ToInt16(MaxQuantity.Text);
            product.HtmlHead          = HtmlHead.Text.Trim();
            product.SearchKeywords    = SearchKeywords.Text.Trim();
            _Product.EnableGroups     = AlwaysConvert.ToBool(EnableGroups.SelectedValue, false);
            _Product.ProductGroups.DeleteAll();
            foreach (ListItem item in ProductGroups.Items)
            {
                if (item.Selected)
                {
                    int          groupId = AlwaysConvert.ToInt(item.Value);
                    ProductGroup pg      = new ProductGroup(_Product, GroupDataSource.Load(groupId));
                    _Product.ProductGroups.Add(pg);
                }
            }

            // search engines and feeds
            product.CustomUrl = CustomUrl.Text;
            CustomUrlValidator.OriginalValue = _Product.CustomUrl;
            product.ExcludeFromFeed          = !IncludeInFeed.Checked;
            product.Title                 = ProductTitle.Text.Trim();
            product.MetaDescription       = MetaDescriptionValue.Text.Trim();
            product.MetaKeywords          = MetaKeywordsValue.Text.Trim();
            product.GoogleCategory        = GoogleCategory.Text;
            product.Condition             = Condition.SelectedValue;
            product.Gender                = Gender.SelectedValue;
            product.AgeGroup              = AgeGroup.SelectedValue;
            product.Color                 = Color.Text;
            product.Size                  = Size.Text;
            product.AdwordsGrouping       = AdwordsGrouping.Text;
            product.AdwordsLabels         = AdwordsLabels.Text;
            product.ExcludedDestination   = ExcludedDestination.SelectedValue;
            product.AdwordsRedirect       = AdwordsRedirect.Text;
            product.PublishFeedAsVariants = PublishAsVariants.Checked;

            // TAX CLOUD PRODUCT TIC
            if (trTIC.Visible && !string.IsNullOrEmpty(HiddenTIC.Value))
            {
                product.TIC = AlwaysConvert.ToInt(HiddenTIC.Value);
            }
            else
            {
                product.TIC = null;
            }

            // save product
            product.Save();
            ModalPopupExtender.Hide();
        }
Beispiel #26
0
        protected void UpdateButton_Click(object sender, EventArgs e)
        {
            bool          itemFound    = false;
            OrderShipment newShipment  = null;
            OrderShipment moveShipment = null;

            foreach (GridViewRow row in ShipmentItems.Rows)
            {
                HiddenField hf          = (HiddenField)row.FindControl("Id");
                int         orderItemId = AlwaysConvert.ToInt(hf.Value);
                int         index       = _OrderShipment.OrderItems.IndexOf(orderItemId);
                if (index > -1)
                {
                    TextBox      tb  = (TextBox)row.FindControl("MoveQty");
                    short        qty = AlwaysConvert.ToInt16(tb.Text);
                    DropDownList ddl = (DropDownList)row.FindControl("Shipment");
                    string       selectedShipment = Request.Form[ddl.UniqueID];
                    if ((qty > 0) && (!string.IsNullOrEmpty(selectedShipment)))
                    {
                        OrderItem orderItem = _OrderShipment.OrderItems[index];
                        itemFound = true;
                        int shipmentId = AlwaysConvert.ToInt(selectedShipment);
                        moveShipment = OrderShipmentDataSource.Load(shipmentId);
                        if (moveShipment == null)
                        {
                            if (newShipment == null)
                            {
                                newShipment = _OrderShipment.Copy();
                                newShipment.Save();
                            }
                            moveShipment = newShipment;
                        }
                        if (qty < orderItem.Quantity)
                        {
                            //SPLIT PART OF THIS ITEM TO ANOTHER SHIPMENT
                            OrderItem splitItem = OrderItem.Copy(orderItem.Id, false);
                            splitItem.Quantity        = qty;
                            splitItem.OrderShipmentId = moveShipment.Id;
                            splitItem.Save();
                            if (orderItem.ParentItemId == orderItem.Id)
                            {
                                splitItem.ParentItemId = splitItem.Id;
                                splitItem.Save();
                            }
                            moveShipment.OrderItems.Add(splitItem);
                            orderItem.Quantity -= qty;
                            orderItem.Save();
                        }
                        else
                        {
                            //MOVE WHOLE ITEM TO ANOTHER SHIPMENT
                            orderItem.OrderShipmentId = moveShipment.Id;
                            orderItem.Save();
                            _OrderShipment.OrderItems.RemoveAt(index);
                        }
                    }
                }
            }

            if (itemFound)
            {
                Response.Redirect(CancelLink.NavigateUrl);
            }
            else
            {
                CustomValidator quantityError = new CustomValidator();
                quantityError.ErrorMessage = "You must pick at least one item to move.";
                quantityError.Text         = "&nbsp;";
                quantityError.IsValid      = false;
                phQuantityValidation.Controls.Add(quantityError);
            }
        }
        protected BasketItem CreateBasketItem()
        {
            //GET THE PRODUCT ID
            int     productId = AlwaysConvert.ToInt(AddProductId.Value);
            Product product   = ProductDataSource.Load(productId);

            if (product == null)
            {
                return(null);
            }
            //GET THE QUANTITY
            short tempQuantity = AlwaysConvert.ToInt16(AddProductQuantity.Text);

            if (tempQuantity < 1)
            {
                return(null);
            }
            //RECALCULATE SELECTED KIT OPTIONS
            GetSelectedKitOptions(product);
            // DETERMINE THE OPTION LIST
            string optionList = ProductVariantDataSource.GetOptionList(productId, _SelectedOptions, false);

            //CREATE THE BASKET ITEM WITH GIVEN OPTIONS
            bool       calculateOneTimePrice = AlwaysConvert.ToBool(OptionalSubscription.SelectedValue, false);
            BasketItem basketItem            = BasketItemDataSource.CreateForProduct(productId, tempQuantity, optionList, AlwaysConvert.ToList(",", _SelectedKitProducts), _UserId, calculateOneTimePrice);

            if (basketItem != null)
            {
                //BASKET ID
                basketItem.BasketId = _Basket.Id;

                // PRODUCT PRICE FOR VARIABLE PRICE PRODUCT
                if (product.UseVariablePrice && !product.IsSubscription && !product.IsKit)
                {
                    basketItem.Price = AlwaysConvert.ToDecimal(AddProductVariablePrice.Text);
                }
                else
                {
                    basketItem.Price = AlwaysConvert.ToDecimal(AddProductPrice.Text);
                }

                if (product.IsSubscription)
                {
                    if (product.SubscriptionPlan.IsOptional)
                    {
                        basketItem.IsSubscription = !calculateOneTimePrice;
                    }
                    else
                    {
                        basketItem.IsSubscription = true;
                    }

                    if (basketItem.IsSubscription && product.SubscriptionPlan.IsRecurring)
                    {
                        basketItem.Frequency     = product.SubscriptionPlan.PaymentFrequencyType == PaymentFrequencyType.Optional ? AlwaysConvert.ToInt16(AutoDeliveryInterval.SelectedValue) : product.SubscriptionPlan.PaymentFrequency;
                        basketItem.FrequencyUnit = product.SubscriptionPlan.PaymentFrequencyUnit;
                    }
                    else if (basketItem.IsSubscription)
                    {
                        basketItem.Frequency     = product.SubscriptionPlan.PaymentFrequency;
                        basketItem.FrequencyUnit = product.SubscriptionPlan.PaymentFrequencyUnit;
                    }
                }


                // COLLECT ANY ADDITIONAL INPUTS
                AbleCommerce.Code.ProductHelper.CollectProductTemplateInput(basketItem, this);
            }
            return(basketItem);
        }
Beispiel #28
0
        protected int SaveCoupon()
        {
            if (Page.IsValid)
            {
                // VALIDATE IF A PROPER END DATE IS SELECTED
                if (EndDate.SelectedEndDate != DateTime.MinValue && DateTime.Compare(EndDate.SelectedEndDate, StartDate.SelectedEndDate) < 0)
                {
                    CustomValidator dateValidator = new CustomValidator();
                    dateValidator.ControlToValidate = "Name"; // THIS SHOULD BE "EndDate" CONTROL, BUT THAT CANNOT BE VALIDATED
                    dateValidator.Text         = "*";
                    dateValidator.ErrorMessage = "End date can not be earlier than start date.";
                    dateValidator.IsValid      = false;
                    phEndDateValidator.Controls.Add(dateValidator);
                    return(0);
                }

                Coupon existingCoupon = CouponDataSource.LoadForCouponCode(CouponCode.Text);
                if (existingCoupon != null)
                {
                    CustomValidator codeValidator = new CustomValidator();
                    codeValidator.ControlToValidate = "CouponCode";
                    codeValidator.Text         = "*";
                    codeValidator.ErrorMessage = "The coupon code " + CouponCode.Text + " is already in use.";
                    codeValidator.IsValid      = false;
                    phCouponCodeValidator.Controls.Add(codeValidator);
                    return(0);
                }

                Coupon _Coupon = new Coupon();
                _Coupon.CouponType     = this.CouponType;
                _Coupon.Name           = Name.Text;
                _Coupon.CouponCode     = CouponCode.Text;
                _Coupon.DiscountAmount = AlwaysConvert.ToDecimal(DiscountAmount.Text);
                _Coupon.IsPercent      = (DiscountType.SelectedIndex == 0);
                //QUANTITY SETTINGS (PRODUCT COUPON)
                if (_Coupon.CouponType == CouponType.Product)
                {
                    _Coupon.MinQuantity = AlwaysConvert.ToInt16(Quantity.Text);
                    if (RepeatCoupon.Checked)
                    {
                        _Coupon.MaxQuantity      = 0;
                        _Coupon.QuantityInterval = _Coupon.MinQuantity;
                    }
                    else
                    {
                        _Coupon.MaxQuantity      = _Coupon.MinQuantity;
                        _Coupon.QuantityInterval = 0;
                    }
                    _Coupon.MaxValue    = 0;
                    _Coupon.MinPurchase = 0;
                }
                //PURCHASE RESTRICTIONS (ORDER AND SHIPPING COUPONS)
                else
                {
                    _Coupon.MaxValue         = AlwaysConvert.ToDecimal(MaxValue.Text);
                    _Coupon.MinPurchase      = AlwaysConvert.ToDecimal(MinPurchase.Text);
                    _Coupon.MinQuantity      = 0;
                    _Coupon.MaxQuantity      = 0;
                    _Coupon.QuantityInterval = 0;
                }
                //SET START DATE
                _Coupon.StartDate = StartDate.SelectedDate;
                //SET END DATE
                _Coupon.EndDate = EndDate.SelectedEndDate;
                //MAX USES
                _Coupon.MaxUsesPerCustomer = AlwaysConvert.ToInt16(MaximumUsesPerCustomer.Text);
                _Coupon.MaxUses            = AlwaysConvert.ToInt16(MaximumUses.Text);
                //COMBINE RULE
                _Coupon.AllowCombine = AllowCombine.Checked;
                //PRODUCT (OR SHIPPING) RULE
                if (_Coupon.CouponType != CouponType.Shipping)
                {
                    _Coupon.ProductRule = (CouponRule)ProductRule.SelectedIndex;
                }
                else
                {
                    _Coupon.ProductRule = (CouponRule)ShipMethodRule.SelectedIndex;
                    _Coupon.ShipMethods.Clear();
                    _Coupon.Save();
                    if (_Coupon.ProductRule != CouponRule.All)
                    {
                        foreach (ListItem item in ShipMethodList.Items)
                        {
                            ShipMethod shipMethod = ShipMethodDataSource.Load(AlwaysConvert.ToInt(item.Value));
                            if (item.Selected)
                            {
                                _Coupon.ShipMethods.Add(shipMethod);
                            }
                        }
                    }
                }
                //GROUP RESTRICTION
                if (UseGroupRestriction.SelectedIndex > 0)
                {
                    _Coupon.Groups.Clear();
                    _Coupon.Save();
                    foreach (ListItem item in GroupList.Items)
                    {
                        Group group = GroupDataSource.Load(AlwaysConvert.ToInt(item.Value));
                        if (item.Selected)
                        {
                            _Coupon.Groups.Add(group);
                        }
                    }
                }
                _Coupon.Save();
                return(_Coupon.Id);
            }
            return(0);
        }
        private void Ship(bool requestTracking)
        {
            //WE HAVE TO LOOK FOR ANY ITEMS NOT BEING SHIPPED
            //BUILD A DICTIONARY OF QUANTITY TO SHIP
            bool itemFound        = false;
            bool isPartial        = false;
            bool quantityExceeded = false;
            Dictionary <int, short> quantities = new Dictionary <int, short>();

            foreach (GridViewRow row in ShipmentItems.Rows)
            {
                HiddenField hf          = (HiddenField)row.FindControl("Id");
                int         orderItemId = AlwaysConvert.ToInt(hf.Value);
                int         index       = _OrderShipment.OrderItems.IndexOf(orderItemId);
                if (index > -1)
                {
                    TextBox tb  = (TextBox)row.FindControl("Quantity");
                    short   qty = AlwaysConvert.ToInt16(tb.Text);
                    itemFound        = itemFound || (qty > 0);
                    isPartial        = isPartial || (qty < _OrderShipment.OrderItems[index].Quantity);
                    quantityExceeded = quantityExceeded || (qty > _OrderShipment.OrderItems[index].Quantity);
                    quantities.Add(orderItemId, qty);
                }
            }

            if ((itemFound) && (!quantityExceeded))
            {
                try
                {
                    // start transation to do it in single step
                    AbleContext.Current.Database.BeginTransaction();

                    //CHECK IF WE ARE NOT SHIPPING ALL OF THE ITEMS
                    if (isPartial)
                    {
                        //AT LEAST ONE ITEM MUST BE MOVED TO A NEW SHIPMENT
                        //CREATE A COPY OF THIS SHIPMENT
                        OrderShipment newShipment = _OrderShipment.Copy();
                        newShipment.Save();
                        _Order.Shipments.Add(newShipment);
                        //KEEP TRACK OF ITEMS TO REMOVE FROM THE CURRENT SHIPMENT
                        List <int> removeItems = new List <int>();
                        //LOOP THE ITEMS AND DECIDE WHICH TO PUT IN THE NEW SHIPMENT
                        foreach (OrderItem item in _OrderShipment.OrderItems)
                        {
                            int searchItemId = (AlwaysConvert.ToInt(item.ParentItemId) == 0) ? item.Id : AlwaysConvert.ToInt(item.ParentItemId);
                            if (quantities.ContainsKey(searchItemId))
                            {
                                short shipQty = quantities[searchItemId];
                                if (shipQty != item.Quantity)
                                {
                                    if (shipQty > 0)
                                    {
                                        //WE HAVE TO SPLIT THIS ITEM
                                        OrderItem newItem = OrderItem.Copy(item.Id, true);
                                        newItem.Quantity        = (short)(item.Quantity - shipQty);
                                        newItem.OrderShipmentId = newShipment.Id;
                                        newItem.Save();
                                        newShipment.OrderItems.Add(newItem);
                                        //UPDATE THE CURRENT ITEM
                                        item.Quantity = shipQty;
                                        item.Save();
                                    }
                                    else
                                    {
                                        //THIS ITEM JUST NEEDS TO BE MOVED
                                        item.OrderShipmentId = newShipment.Id;
                                        item.Save();
                                        newShipment.OrderItems.Add(item);
                                        removeItems.Add(item.Id);
                                    }
                                }
                            }
                        }
                        //REMOVE ANY ITEMS THAT WERE MOVED TO ANOTHER SHIPMENT
                        foreach (int id in removeItems)
                        {
                            int delIndex = _OrderShipment.OrderItems.IndexOf(id);
                            if (delIndex > -1)
                            {
                                _OrderShipment.OrderItems.RemoveAt(delIndex);
                            }
                        }
                    }

                    //Add the Tracking Number
                    int    shipgwId     = AlwaysConvert.ToInt(ShipGateway.SelectedValue);
                    string trackingData = AddTrackingNumber.Text.Trim();
                    if (!string.IsNullOrEmpty(trackingData))
                    {
                        TrackingNumber tnum = new TrackingNumber();
                        tnum.TrackingNumberData = trackingData;
                        tnum.ShipGatewayId      = shipgwId;
                        tnum.OrderShipmentId    = _OrderShipment.Id;
                        _OrderShipment.TrackingNumbers.Add(tnum);
                    }

                    //SHIP THE CURRENT SHIPMENT
                    _OrderShipment.Ship(requestTracking, LocaleHelper.LocalNow);

                    // end transaction
                    AbleContext.Current.Database.CommitTransaction();

                    //RETURN TO SHIPMENTS PAGE
                    Response.Redirect(CancelButton.NavigateUrl, false);
                }
                catch (Exception ex)
                {
                    AbleContext.Current.Database.RollbackTransaction();
                    Logger.Error(string.Format("An error occurred while trying to confirm shipment to provider: {0}", ex.Message), ex);

                    CustomValidator shipError = new CustomValidator();
                    shipError.Text         = "*";
                    shipError.ErrorMessage = ex.Message;
                    shipError.IsValid      = false;
                    phValidation.Controls.Add(shipError);
                }
            }
            else
            {
                CustomValidator quantityError = new CustomValidator();
                if (quantityExceeded)
                {
                    quantityError.ErrorMessage = "You cannot move more than the existing quantity.";
                }
                else
                {
                    quantityError.ErrorMessage = "You must pick at least one item to move.";
                }
                quantityError.Text    = "&nbsp;";
                quantityError.IsValid = false;
                phValidation.Controls.Add(quantityError);
            }
        }
Beispiel #30
0
        /// <summary>
        /// Updates the parent of the given category
        /// </summary>
        /// <param name="categoryId">Id of the category for which to update the parent</param>
        /// <param name="parentId">Parent Id to set</param>
        public static void UpdateParent(int categoryId, int parentId)
        {
            //GET DATABSAE REFERENCES
            Database  database = Token.Instance.Database;
            DbCommand selectCommand;

            //VERIFY THE SPECIFIED CATEGORY IS VALID
            if (parentId != 0)
            {
                selectCommand = database.GetSqlStringCommand("SELECT CategoryId FROM ac_Categories WHERE CategoryId = @categoryId");
                database.AddInParameter(selectCommand, "@categoryId", DbType.Int32, categoryId);
                object scalarResult = database.ExecuteScalar(selectCommand);
                if (scalarResult == null)
                {
                    throw new ArgumentException("This category instance has not been saved to the database.", "CategoryId");
                }
            }

            //VERIFY THE SELECTED PARENT IS VALID
            if (parentId != 0)
            {
                selectCommand = database.GetSqlStringCommand("SELECT CategoryId FROM ac_Categories WHERE CategoryId = @categoryId");
                database.AddInParameter(selectCommand, "@categoryId", DbType.Int32, parentId);
                object scalarResult = database.ExecuteScalar(selectCommand);
                if (scalarResult == null)
                {
                    throw new ArgumentException("Invalid parent category specified.", "parentId");
                }
            }

            //CHECK FOR CIRCULAR REFRENCES
            if (categoryId.Equals(parentId))
            {
                throw new ArgumentException("Specified parent category would result in a circular reference.", "parentId");
            }
            selectCommand = database.GetSqlStringCommand("SELECT COUNT(*) As ChildReferences FROM ac_CategoryParents WHERE ParentId = @categoryId AND CategoryId = @parentId");
            database.AddInParameter(selectCommand, "@categoryId", DbType.Int32, categoryId);
            database.AddInParameter(selectCommand, "@parentId", DbType.Int32, parentId);
            int childReferences = (int)database.ExecuteScalar(selectCommand);

            if (childReferences > 0)
            {
                throw new ArgumentException("Specified parent category would result in a circular reference.", "parentId");
            }

            //UPDATE CATEGORY PARENT
            DbCommand updateCommand = database.GetSqlStringCommand("UPDATE ac_Categories SET ParentId = @parentId WHERE CategoryId = @categoryId");

            database.AddInParameter(updateCommand, "@categoryId", DbType.Int32, categoryId);
            database.AddInParameter(updateCommand, "@parentId", DbType.Int32, parentId);
            database.ExecuteNonQuery(updateCommand);

            //DELETE ANY EXISTING PARENT ASSOCIATIONS
            DbCommand deleteCommand = database.GetSqlStringCommand("DELETE FROM ac_CategoryParents WHERE CategoryId = @categoryId");

            database.AddInParameter(deleteCommand, "@categoryId", DbType.Int32, categoryId);
            database.ExecuteNonQuery(deleteCommand);
            deleteCommand = database.GetSqlStringCommand("DELETE FROM ac_CatalogNodes WHERE CatalogNodeTypeId = 0 AND CatalogNodeId = @categoryId");
            database.AddInParameter(deleteCommand, "@categoryId", DbType.Int32, categoryId);
            database.ExecuteNonQuery(deleteCommand);

            //NOW INSERT MODIFIED PARENT PATH
            StringBuilder insertQuery;
            DbCommand     insertCommand;
            int           level;

            if (parentId != 0)
            {
                insertQuery = new StringBuilder();
                insertQuery.Append("INSERT INTO ac_CategoryParents (CategoryId, ParentId, ParentLevel, ParentNumber)");
                insertQuery.Append(" SELECT @categoryId, ParentId, ParentLevel, (ParentNumber + 1)");
                insertQuery.Append(" FROM ac_CategoryParents");
                insertQuery.Append(" WHERE CategoryId = @parentCategoryId;");
                insertCommand = database.GetSqlStringCommand(insertQuery.ToString());
                database.AddInParameter(insertCommand, "@categoryId", DbType.Int32, categoryId);
                database.AddInParameter(insertCommand, "@parentCategoryId", DbType.Int32, parentId);
                database.ExecuteNonQuery(insertCommand);
                //GET LEVEL OF NEW CATEGORY
                selectCommand = database.GetSqlStringCommand("SELECT (ParentLevel + 1) FROM ac_CategoryParents WHERE CategoryId = @parentCategoryId AND ParentNumber=0");
                database.AddInParameter(selectCommand, "@parentCategoryId", DbType.Int32, parentId);
                level = AlwaysConvert.ToInt(database.ExecuteScalar(selectCommand));
            }
            else
            {
                insertQuery = new StringBuilder();
                insertQuery.Append("INSERT INTO ac_CategoryParents (CategoryId, ParentId, ParentLevel, ParentNumber)");
                insertQuery.Append(" VALUES (@categoryId, 0, 0, 1)");
                insertCommand = database.GetSqlStringCommand(insertQuery.ToString());
                database.AddInParameter(insertCommand, "@categoryId", DbType.Int32, categoryId);
                database.ExecuteNonQuery(insertCommand);
                level = 1;
            }

            // NOW INSERT SELF-REFERENCING PATH
            insertQuery = new StringBuilder();
            insertQuery.Append("INSERT INTO ac_CategoryParents (CategoryId, ParentId, ParentLevel, ParentNumber)");
            insertQuery.Append(" VALUES (@categoryId, @categoryId, @level, 0);");
            insertCommand = database.GetSqlStringCommand(insertQuery.ToString());
            database.AddInParameter(insertCommand, "@categoryId", DbType.Int32, categoryId);
            database.AddInParameter(insertCommand, "@level", DbType.Int32, level);
            database.ExecuteNonQuery(insertCommand);

            //GET ORDER OF NEW CATEGORY
            selectCommand = database.GetSqlStringCommand("SELECT (MAX(OrderBy) + 1) FROM ac_CatalogNodes WHERE CategoryId = @parentCategoryId");
            database.AddInParameter(selectCommand, "@parentCategoryId", DbType.Int32, parentId);
            Int16 order = AlwaysConvert.ToInt16(database.ExecuteScalar(selectCommand));

            //ADD IN CATALOG NODE
            insertQuery = new StringBuilder();
            insertQuery.Append("INSERT INTO ac_CatalogNodes (CategoryId, CatalogNodeId, CatalogNodeTypeId, OrderBy)");
            insertQuery.Append(" VALUES (@parentCategoryId, @categoryId, 0, @order)");
            insertCommand = database.GetSqlStringCommand(insertQuery.ToString());
            database.AddInParameter(insertCommand, "@parentCategoryId", DbType.Int32, parentId);
            database.AddInParameter(insertCommand, "@categoryId", DbType.Int32, categoryId);
            database.AddInParameter(insertCommand, "@order", DbType.Int16, order);
            database.ExecuteNonQuery(insertCommand);

            // GET ANY CHILD CATEGORIES OF CURRENT CATEGORY
            List <int> catalogNodeIds = new List <int>();

            selectCommand = database.GetSqlStringCommand("SELECT CategoryId FROM ac_Categories WHERE ParentId = @categoryId");
            database.AddInParameter(selectCommand, "@categoryId", DbType.Int32, categoryId);
            using (IDataReader reader = database.ExecuteReader(selectCommand))
            {
                while (reader.Read())
                {
                    catalogNodeIds.Add(reader.GetInt32(0));
                }
                reader.Close();
            }
            foreach (int catalogNodeId in catalogNodeIds)
            {
                Category.UpdateParent(catalogNodeId, categoryId);
            }
        }