Ejemplo n.º 1
0
        /// <summary>
        /// Used to Save the data to the database
        /// </summary>
        /// <returns>True if Successful</returns>
        public override bool Submit(ChangeSet changeSet)
        {
            try
            {
                using (esTransactionScope scope = new esTransactionScope())
                {
                    bool success = base.Submit(changeSet);

                    if (success)
                    {
                        scope.Complete();
                    }

                    return(success);
                }
            }
            catch (Exception ex)
            {
                if (!HandleError(ex))
                {
                    throw;
                }

                return(true);
            }
        }
Ejemplo n.º 2
0
        private void UpdateTaxRates(List <TaxRateInfo> taxRateInfos)
        {
            using (esTransactionScope transaction = new esTransactionScope())
            {
                int storeId = StoreContext.CurrentStore.Id.Value;

                //---- delete all tax regions for this store
                TaxRegionQuery q = new TaxRegionQuery();
                q.Where(q.StoreId == storeId);
                TaxRegionCollection taxRegions = new TaxRegionCollection();
                taxRegions.Load(q);
                taxRegions.MarkAllAsDeleted();
                taxRegions.Save();

                //---- and re-insert them
                // remove duplicate entries
                taxRateInfos.RemoveDuplicates((left, right) => (left.CountryCode == right.CountryCode && left.Region == right.Region) ? 1 : -1);
                foreach (TaxRateInfo taxRate in taxRateInfos)
                {
                    TaxRegion newTaxRegion = taxRegions.AddNew();
                    newTaxRegion.StoreId     = storeId;
                    newTaxRegion.CountryCode = taxRate.CountryCode;
                    newTaxRegion.Region      = taxRate.Region;
                    newTaxRegion.TaxRate     = taxRate.TaxRate;
                }
                taxRegions.Save();

                transaction.Complete();
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// This will DELETE and then INSERT each setting
        /// </summary>
        /// <param name="shippingServiceId"></param>
        /// <param name="settings"></param>
        public void UpdateSettingsDictionary(Dictionary <string, string> settings)
        {
            using (esTransactionScope transaction = new esTransactionScope())
            {
                // DELETE all existing settings for this service
                ShippingServiceSettingQuery qDelete = new ShippingServiceSettingQuery();
                qDelete.Where(qDelete.ShippingServiceId == this.Id.Value);
                ShippingServiceSettingCollection oldSettings = new ShippingServiceSettingCollection();
                oldSettings.Load(qDelete);
                oldSettings.MarkAllAsDeleted();
                oldSettings.Save();

                // INSERT new settings for this service
                if (settings.Keys.Count > 0)
                {
                    ShippingServiceSettingCollection newSettings = new ShippingServiceSettingCollection();
                    foreach (KeyValuePair <string, string> setting in settings)
                    {
                        ShippingServiceSetting newSetting = newSettings.AddNew();
                        newSetting.ShippingServiceId = this.Id.Value;
                        newSetting.Name  = setting.Key;
                        newSetting.Value = setting.Value;
                    }
                    newSettings.Save();
                }

                transaction.Complete();
            }
        }
        public static void UpdateSettingsDictionary(int storeId, short paymentProviderId, Dictionary <string, string> settings)
        {
            using (esTransactionScope transaction = new esTransactionScope())
            {
                // DELETE all existing settings for this store/provider
                StorePaymentProviderSettingQuery qDelete = new StorePaymentProviderSettingQuery();
                qDelete.Where(qDelete.StoreId == storeId, qDelete.PaymentProviderId == paymentProviderId);
                StorePaymentProviderSettingCollection oldSettings = new StorePaymentProviderSettingCollection();
                oldSettings.Load(qDelete);
                oldSettings.MarkAllAsDeleted();
                oldSettings.Save();

                // INSERT new settings for this store/provider
                if (settings.Keys.Count > 0)
                {
                    StorePaymentProviderSettingCollection newSettings = new StorePaymentProviderSettingCollection();
                    foreach (KeyValuePair <string, string> setting in settings)
                    {
                        StorePaymentProviderSetting newSetting = newSettings.AddNew();
                        newSetting.StoreId           = storeId;
                        newSetting.PaymentProviderId = paymentProviderId;
                        newSetting.Name  = setting.Key;
                        newSetting.Value = setting.Value;
                    }
                    newSettings.Save();
                }

                transaction.Complete();
            }
        }
Ejemplo n.º 5
0
        protected void lnkSaveIssue_Click(object sender, EventArgs e)
        {
            using (esTransactionScope scope = new esTransactionScope())
            {
                OMAMFundManager objFundManager = new OMAMFundManager();

                if (fundManager == null)
                {
                    //This is an add
                    objFundManager.FullName    = txtFMName.Text.ToString();
                    objFundManager.Profile     = Editor1.Text.ToString();
                    objFundManager.CreatedBy   = UserId;
                    objFundManager.CreatedDate = DateTime.Now;
                    //MTW objFundManager.FMImage = ddlFundManager.SelectedValue.ToString();

                    objFundManager.Save();
                }
                else
                {
                    //This is an update
                    objFundManager.Query.Where(objFundManager.Query.Id == Convert.ToInt32(fundManager.Id));
                    objFundManager.Query.Load();

                    objFundManager.FullName = txtFMName.Text.ToString();
                    objFundManager.Profile  = Editor1.Text.ToString();
                    //MTW objFundManager.FMImage = ddlFundManager.SelectedValue.ToString();

                    objFundManager.Save();
                }

                //Remove all the assigned funds first
                OMAMLNKManagerFundsCollection objManagerFunds = new OMAMLNKManagerFundsCollection();

                objManagerFunds.Query
                .Where(objManagerFunds.Query.ManagerId == objFundManager.Id);

                objManagerFunds.Query.Load();
                objManagerFunds.MarkAllAsDeleted();
                objManagerFunds.Save();

                //OK, Now add the newly assigned funds
                for (int i = 0; i < cblFundsAssigned.Items.Count; i++)
                {
                    OMAMLNKManagerFunds assignedFunds = new OMAMLNKManagerFunds();
                    assignedFunds.ManagerId = objFundManager.Id;
                    assignedFunds.FundId    = Convert.ToInt16(cblFundsAssigned.Items[i].Value);
                    assignedFunds.Save();
                }

                scope.Complete();

                divAddActivity.Visible = false;
                divFMGrid.Visible      = true;
                LoadFMs();
            }
        }
Ejemplo n.º 6
0
        public void AddProductToCart(int productId, int productQty, string jsonProductFieldData)
        {
            //UpdateCartItemInCart(null, productId, productQty, true, jsonProductFieldData);

            DataModel.Cart cart = null;

            using (esTransactionScope transaction = new esTransactionScope())
            {
                cart = GetCartFromDatabase(true);

                CartItemCollection cartItemCollection = cart.CartItemCollectionByCartId;
                List <CartItem>    cartItems          = cartItemCollection.ToList();
                int index = cartItems.FindIndex(ci => (ci.ProductId.Value == productId) && (ci.ProductFieldData == jsonProductFieldData));
                if (index >= 0)
                {
                    // product is in the cart
                    if (productQty <= 0)
                    {
                        // remove from cart
                        cartItemCollection[index].MarkAsDeleted();
                    }
                    else
                    {
                        // add/update quantity
                        cartItemCollection[index].Quantity += productQty;

                        // update ProductFieldData
                        if (!string.IsNullOrEmpty(jsonProductFieldData))
                        {
                            cartItemCollection[index].ProductFieldData = jsonProductFieldData;
                        }
                    }
                }
                else if (productQty > 0)
                {
                    // add to cart
                    CartItem newItem = cartItemCollection.AddNew();
                    newItem.ProductId        = productId;
                    newItem.Quantity         = productQty;
                    newItem.ProductFieldData = jsonProductFieldData;
                }

                //---- update some cart fields too...
                if (storeContext.UserId.HasValue)
                {
                    cart.UserId = storeContext.UserId.Value;
                }

                cart.Save();

                transaction.Complete();
            }

            //return cart;
        }
        static private DataTable SaveDynamicCollection_Deletes(esDataRequest request)
        {
            VistaDBCommand cmd = null;

            DataTable dataTable = CreateDataTable(request);

            using (esTransactionScope scope = new esTransactionScope())
            {
                using (VistaDBDataAdapter da = new VistaDBDataAdapter())
                {
                    da.AcceptChangesDuringUpdate = false;
                    da.ContinueUpdateOnError     = request.ContinueUpdateOnError;

                    try
                    {
                        cmd = da.DeleteCommand = Shared.BuildDynamicDeleteCommand(request, request.CollectionSavePacket[0].ModifiedColumns);
                        esTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate);

                        DataRow[] singleRow = new DataRow[1];

                        // Delete each record
                        foreach (esEntitySavePacket packet in request.CollectionSavePacket)
                        {
                            DataRow row = dataTable.NewRow();
                            dataTable.Rows.Add(row);

                            SetOriginalValues(request, packet, row, true);
                            row.AcceptChanges();
                            row.Delete();

                            singleRow[0] = row;
                            da.Update(singleRow);

                            if (row.HasErrors)
                            {
                                request.FireOnError(packet, row.RowError);
                            }

                            dataTable.Rows.Clear(); // ADO.NET won't let us reuse the same DataRow
                        }
                    }
                    finally
                    {
                        esTransactionScope.DeEnlist(cmd);
                        cmd.Dispose();
                    }
                }

                scope.Complete();
            }

            return(request.Table);
        }
Ejemplo n.º 8
0
        static private void SaveEntity()
        {
            // The transaction isn't necessary here but demonstrates it's usage
            using (esTransactionScope scope = new esTransactionScope())
            {
                Employees employee = new Employees();
                employee.FirstName = "Mike";
                employee.LastName  = "Griffin";
                employee.Save();

                scope.Complete(); // last line of using statement
            }
        }
Ejemplo n.º 9
0
        public void TestFailedTransaction()
        {
            switch (aggTest.es.Connection.Name)
            {
            case "SQLStoredProcEnterprise":
            case "SQLDynamicEnterprise":
            case "ORACLEStoredProcEnterprise":
            case "ORACLEDynamicEnterprise":
            case "VistaDBDynamic":
                Assert.Ignore("Using esTransactionScope only");
                break;

            default:
                try
                {
                    aggTest = new AggregateTest();
                    AggregateTest aggTest2  = new AggregateTest();
                    int           tempId1   = -1;
                    int           tempId2   = -1;
                    aggTest2.str().HireDate = "1/1/1";

                    using (esTransactionScope scope = new esTransactionScope())
                    {
                        try
                        {
                            aggTest.Save();
                            tempId1 = aggTest.Id.Value;
                            aggTest2.Save();
                            tempId2 = aggTest2.Id.Value;

                            throw new Exception();

                            scope.Complete();
                        }
                        catch
                        {
                        }
                    }
                    aggTest = new AggregateTest();
                    Assert.IsFalse(aggTest.LoadByPrimaryKey(tempId1));

                    aggTest = new AggregateTest();
                    Assert.IsFalse(aggTest.LoadByPrimaryKey(tempId2));
                }
                catch (Exception ex)
                {
                    Assert.Fail(ex.ToString());
                }
                break;
            }
        }
Ejemplo n.º 10
0
 protected override void UpdateSingleTest()
 {
     using (var ts = new esTransactionScope())
     {
         var simplests = new SimplestsCollection();
         simplests.LoadAll();
         foreach (var o in simplests)
         {
             o.Value++;
             o.Save();
         }
         ts.Complete();
     }
 }
Ejemplo n.º 11
0
 protected override void DeleteSingleTest()
 {
     using (var ts = new esTransactionScope())
     {
         var simplests = new SimplestsCollection();
         simplests.LoadAll();
         for (int i = simplests.Count - 1; i >= 0; i--)
         {
             var o = simplests[0];
             o.MarkAsDeleted();
             o.Save();
         }
         ts.Complete();
     }
 }
Ejemplo n.º 12
0
 protected override void InsertSingleTest(int count)
 {
     using (var ts = new esTransactionScope())
     {
         for (int i = 0; i < count; i++)
         {
             var simplest = new Simplests
             {
                 Id    = i,
                 Value = i
             };
             simplest.Save();
         }
         ts.Complete();
     }
     InstanceCount = count;
 }
Ejemplo n.º 13
0
 protected override void CompiledLinqQueryTest(int count)
 {
     using (var ts = new esTransactionScope())
     {
         for (int i = 0; i < count; i++)
         {
             var id    = i % InstanceCount;
             var query = new SimplestsCollection();
             query.Load(_db, _compiledQuery(_db, id));
             foreach (var simplest in query)
             {
                 // Doing nothing, just enumerate
             }
         }
         ts.Complete();
     }
 }
Ejemplo n.º 14
0
        protected override void LinqQueryPageTest(int count, int pageSize)
        {
            using (var ts = new esTransactionScope())
            {
                for (var i = 0; i < count; i++)
                {
                    var id        = (i * pageSize) % InstanceCount;
                    var simplests = new SimplestsCollection();
                    simplests.Load(_db, _pageQuery(_db, id, pageSize));
                    foreach (var o in simplests)
                    {
                        // Doing nothing, just enumerate
                    }
                }

                ts.Complete();
            }
        }
Ejemplo n.º 15
0
        public void TestTransactions()
        {
            switch (aggTest.es.Connection.Name)
            {
            case "SQLStoredProcEnterprise":
            case "SQLDynamicEnterprise":
            case "ORACLEStoredProcEnterprise":
            case "ORACLEDynamicEnterprise":
            case "VistaDBDynamic":
                Assert.Ignore("Using esTransactionScope only");
                break;

            default:
                int tempId1 = 0;
                int tempId2 = 0;

                aggTest = new AggregateTest();
                AggregateTest aggTest2 = new AggregateTest();

                using (esTransactionScope scope = new esTransactionScope())
                {
                    aggTest.Save();
                    tempId1 = aggTest.Id.Value;
                    aggTest2.Save();
                    tempId2 = aggTest2.Id.Value;

                    scope.Complete();
                }

                aggTest = new AggregateTest();
                Assert.IsTrue(aggTest.LoadByPrimaryKey(tempId1));
                aggTest.MarkAsDeleted();
                aggTest.Save();

                aggTest = new AggregateTest();
                Assert.IsTrue(aggTest.LoadByPrimaryKey(tempId2));
                aggTest.MarkAsDeleted();
                aggTest.Save();

                break;
            }
        }
Ejemplo n.º 16
0
 protected override void NativeMaterializeTest(int count)
 {
     using (var ts = new esTransactionScope())
     {
         var simplests = new SimplestsCollection();
         int i         = 0;
         while (i < count)
         {
             simplests.LoadAll();
             foreach (var o in simplests)
             {
                 if (++i >= count)
                 {
                     break;
                 }
             }
         }
         ts.Complete();
     }
 }
Ejemplo n.º 17
0
 protected override void LinqMaterializeTest(int count)
 {
     using (var ts = new esTransactionScope())
     {
         var simplests = new SimplestsCollection();
         int i         = 0;
         while (i < count)
         {
             simplests.Load(_db, _db.GetTable <Simplests>().Where(o => o.Id > 0));
             foreach (var o in simplests)
             {
                 if (++i >= count)
                 {
                     break;
                 }
             }
         }
         ts.Complete();
     }
 }
Ejemplo n.º 18
0
 protected override void NativeQueryTest(int count)
 {
     using (var ts = new esTransactionScope())
     {
         for (int i = 0; i < count; i++)
         {
             var simplests = new SimplestsCollection();
             var id        = i % InstanceCount;
             simplests.Query.Where(simplests.Query.Id == id);
             if (simplests.Query.Load())
             {
                 foreach (var simplest in simplests)
                 {
                     // Doing nothing, just enumerate
                 }
             }
         }
         ts.Complete();
     }
 }
Ejemplo n.º 19
0
        protected override void FetchTest(int count)
        {
            long sum = (long)count * (count - 1) / 2;

            using (var ts = new esTransactionScope())
            {
                for (int i = 0; i < count; i++)
                {
                    var id       = (long)i % InstanceCount;
                    var simplest = new Simplests();
                    simplest.LoadByPrimaryKey(id);
                    sum -= simplest.Id.Value;
                }
                ts.Complete();
            }
            if (count <= InstanceCount)
            {
                Assert.AreEqual(0, sum);
            }
        }
Ejemplo n.º 20
0
        public static void SetCategories(int productId, List <int> categoryIds)
        {
            Product p = new Product();

            if (p.LoadByPrimaryKey(productId))
            {
                using (esTransactionScope transaction = new esTransactionScope())
                {
                    p.ProductCategoryCollectionByProductId.MarkAllAsDeleted();
                    p.ProductCategoryCollectionByProductId.Save();

                    foreach (int catId in categoryIds)
                    {
                        ProductCategory pc = p.ProductCategoryCollectionByProductId.AddNew();
                        pc.CategoryId = catId;
                    }
                    p.ProductCategoryCollectionByProductId.Save();

                    transaction.Complete();
                }
            }
        }
Ejemplo n.º 21
0
        public void UpdateCartItemQuantity(int cartItemId, int quantity)
        {
            //UpdateCartItemInCart(cartItemId, null, quantity, false, string.Empty);

            using (esTransactionScope transaction = new esTransactionScope())
            {
                DataModel.Cart cart = GetCartFromDatabase(false);

                CartItemCollection cartItems = cart.CartItemCollectionByCartId;
                cartItems.Filter = cartItems.AsQueryable().Where(x => x.Id == cartItemId);
                //cartItems.Filter = CartItemMetadata.ColumnNames.Id + " = " + cartItemId;

                if (cartItems.Count > 0)
                {
                    // item is in the cart
                    if (quantity <= 0)
                    {
                        // remove from cart
                        cartItems[0].MarkAsDeleted();
                    }
                    else
                    {
                        cartItems[0].Quantity = quantity;
                    }
                }
                //cartItems.Filter = "";
                cartItems.Filter = null;

                //---- update some cart fields too...
                if (storeContext.UserId.HasValue)
                {
                    cart.UserId = storeContext.UserId.Value;
                }

                cart.Save();

                transaction.Complete();
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Create a "PendingOffsite" Order by copying the CheckoutOrderInfo into an actual Order in the database.
        /// </summary>
        /// <param name="checkoutOrderInfo"></param>
        /// <returns></returns>
        public Order CreateOrder(CheckoutOrderInfo checkoutOrderInfo, OrderStatusName orderStatus)
        {
            using (esTransactionScope transaction = new esTransactionScope())
            {
                Order pendingOrder = new Order();

                if (checkoutOrderInfo.PaymentProvider != PaymentProviderName.CardCaptureOnly)
                {
                    //--- check if we have an existing pending order for this Cart....
                    Order existingOrderByCartId = Order.GetOrderByCartId(checkoutOrderInfo.Cart.Id.Value);
                    if (existingOrderByCartId != null)
                    {
                        //existingOrderByCartId.MarkAsDeleted();
                        existingOrderByCartId.OrderStatus = OrderStatusName.Failed;
                        existingOrderByCartId.Save();
                    }
                }

                //pendingOrder.OrderStatus = OrderStatusName.PendingOffsite;
                pendingOrder.OrderStatus   = orderStatus;
                pendingOrder.PaymentStatus = PaymentStatusName.Pending;

                //---- copy the Checkout Order Info into our Order database object
                pendingOrder.StoreId           = storeContext.CurrentStore.Id.Value;
                pendingOrder.UserId            = storeContext.UserId;
                pendingOrder.CreatedFromCartId = checkoutOrderInfo.Cart.Id;
                pendingOrder.CreatedByIP       = HttpContext.Current.Request.UserHostAddress;
                pendingOrder.OrderNumber       = ""; // we'll update it later

                pendingOrder.CustomerFirstName = checkoutOrderInfo.BillingAddress.FirstName;
                pendingOrder.CustomerLastName  = checkoutOrderInfo.BillingAddress.LastName;
                pendingOrder.CustomerEmail     = checkoutOrderInfo.BillingAddress.Email;

                pendingOrder.BillAddress1    = checkoutOrderInfo.BillingAddress.Address1;
                pendingOrder.BillAddress2    = !string.IsNullOrEmpty(checkoutOrderInfo.BillingAddress.Address2) ? checkoutOrderInfo.BillingAddress.Address2 : String.Empty;
                pendingOrder.BillCity        = checkoutOrderInfo.BillingAddress.City;
                pendingOrder.BillRegion      = checkoutOrderInfo.BillingAddress.Region;
                pendingOrder.BillPostalCode  = checkoutOrderInfo.BillingAddress.PostalCode;
                pendingOrder.BillCountryCode = checkoutOrderInfo.BillingAddress.Country;
                pendingOrder.BillTelephone   = checkoutOrderInfo.BillingAddress.Telephone;

                pendingOrder.ShipRecipientName         = string.Format("{0} {1}", checkoutOrderInfo.ShippingAddress.FirstName, checkoutOrderInfo.ShippingAddress.LastName);
                pendingOrder.ShipRecipientBusinessName = checkoutOrderInfo.ShippingAddress.BusinessName ?? "";
                pendingOrder.ShipAddress1    = checkoutOrderInfo.ShippingAddress.Address1;
                pendingOrder.ShipAddress2    = checkoutOrderInfo.ShippingAddress.Address2;
                pendingOrder.ShipCity        = checkoutOrderInfo.ShippingAddress.City;
                pendingOrder.ShipRegion      = checkoutOrderInfo.ShippingAddress.Region;
                pendingOrder.ShipPostalCode  = checkoutOrderInfo.ShippingAddress.PostalCode;
                pendingOrder.ShipCountryCode = checkoutOrderInfo.ShippingAddress.Country;
                pendingOrder.ShipTelephone   = checkoutOrderInfo.ShippingAddress.Telephone;

                //--- Shipping Provider Stuff
                pendingOrder.ShippingServiceProvider = checkoutOrderInfo.ShippingProvider.ToString();
                pendingOrder.ShippingServiceOption   = checkoutOrderInfo.ShippingRate.ServiceTypeDescription ?? "";
                pendingOrder.ShippingServiceType     = checkoutOrderInfo.ShippingRate.ServiceType ?? "";
                pendingOrder.ShippingServicePrice    = checkoutOrderInfo.ShippingRate.Rate;

                //--- Order Notes
                pendingOrder.OrderNotes = checkoutOrderInfo.OrderNotes ?? "";

                //---- Cart Items
                List <vCartItemProductInfo> cartItems = checkoutOrderInfo.Cart.GetCartItemsWithProductInfo();
                foreach (vCartItemProductInfo cartItem in cartItems)
                {
                    Product product = cartItem.GetProduct();

                    OrderItem newItem = pendingOrder.OrderItemCollectionByOrderId.AddNew();
                    newItem.ProductId = product.Id;
                    newItem.Name      = product.Name;
                    newItem.Sku       = product.Sku;
                    if (product.DeliveryMethodId == 2)
                    {
                        newItem.DigitalFilename        = product.DigitalFilename;
                        newItem.DigitalFileDisplayName = product.DigitalFileDisplayName;
                    }
                    newItem.ProductFieldData = cartItem.ProductFieldData;
                    newItem.Quantity         = cartItem.Quantity;
                    newItem.WeightTotal      = cartItem.GetWeightForQuantity();
                    newItem.PriceTotal       = cartItem.GetPriceForQuantity();
                }

                pendingOrder.SubTotal       = checkoutOrderInfo.SubTotal;
                pendingOrder.ShippingAmount = checkoutOrderInfo.ShippingRate.Rate;
                pendingOrder.DiscountAmount = checkoutOrderInfo.DiscountAmount;
                pendingOrder.TaxAmount      = checkoutOrderInfo.TaxAmount;
                pendingOrder.Total          = checkoutOrderInfo.Total;

                //--- Coupons
                foreach (CheckoutCouponInfo checkoutCoupon in checkoutOrderInfo.GetAppliedCoupons())
                {
                    OrderCoupon orderCoupon = pendingOrder.OrderCouponCollectionByOrderId.AddNew();
                    orderCoupon.CouponCode     = checkoutCoupon.CouponCode;
                    orderCoupon.DiscountAmount = checkoutCoupon.DiscountAmount;
                }

                //--- Save limited Credit Card info to order
                pendingOrder.CreditCardType = checkoutOrderInfo.CreditCard.CardType.ToString();
                // the full card number is not saved here for security
                pendingOrder.CreditCardNumberLast4 = checkoutOrderInfo.CreditCard.CardNumber.Right(4);
                pendingOrder.CreditCardExpiration  = string.Format("{0} / {1}", checkoutOrderInfo.CreditCard.ExpireMonth2Digits, checkoutOrderInfo.CreditCard.ExpireYear);
                // Credit Card CVV not saved here for security
                pendingOrder.CreditCardNameOnCard = checkoutOrderInfo.CreditCard.NameOnCard;

                pendingOrder.Save();

                // update the order number
                pendingOrder.OrderNumber = storeContext.CurrentStore.GetSetting(StoreSettingNames.OrderNumberPrefix) + pendingOrder.Id;
                pendingOrder.Save();

                transaction.Complete();

                int orderId = pendingOrder.Id.Value;
                pendingOrder.LoadByPrimaryKey(orderId);

                return(pendingOrder);
            }
        }
Ejemplo n.º 23
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            bool isNew = false;

            Product toSave = new Product();

            if (!toSave.LoadByPrimaryKey(ParamId.GetValueOrDefault(-1)))
            {
                isNew          = true;
                toSave.Name    = txtName.Text;
                toSave.StoreId = StoreContext.CurrentStore.Id;
            }

            string slug = txtSlug.Text.CreateSlug();

            if (toSave.Slug != slug)
            {
                if (!SlugFactory.IsSlugAvailable(StoreContext.CurrentStore.Id.Value, slug))
                {
                    ShowFlash(string.Format(@"The URL name ""{0}"" is already in use for this store, please choose another.", slug));
                    return;
                }
            }

            if (toSave.Name.Trim() != txtName.Text.Trim())
            {
                var existingProductByName = Product.GetByName(StoreContext.CurrentStore.Id.Value, txtName.Text.Trim());
                if (existingProductByName != null)
                {
                    ShowFlash(string.Format(@"The product name ""{0}"" already exists in this store, please chose another product name", existingProductByName.Name));
                    return;
                }
            }

            string sku = txtSku.Text;

            if (!string.IsNullOrEmpty(sku))
            {
                if (!RegexPatterns.IsValidSku.IsMatch(sku))
                {
                    ShowFlash(string.Format(@"The Sku '{0}' is invalid, it must match the pattern '{1}'", sku, RegexPatterns.IsValidSku));
                    return;
                }
                sku = sku.Trim();
            }

            toSave.Name                   = txtName.Text.Trim();
            toSave.Slug                   = slug;
            toSave.IsActive               = chkIsActive.Checked;
            toSave.Price                  = Convert.ToDecimal(txtPrice.Text, CultureInfo.CreateSpecificCulture("en-US"));
            toSave.Sku                    = sku;
            toSave.SpecialNotes           = txtSpecialNotes.Text.NewlineToBr();
            toSave.IsTaxable              = chkIsTaxable.Checked;
            toSave.IsPriceDisplayed       = chkIsPriceDisplayed.Checked;
            toSave.IsAvailableForPurchase = chkIsAvailableForPurchase.Checked;
            toSave.DeliveryMethodId       = WA.Parser.ToShort(rdoDeliveryMethod.SelectedValue);
            if (toSave.DeliveryMethodId.Value == (short)ProductDeliveryMethod.Shipped)
            {
                toSave.ShippingAdditionalFeePerItem = string.IsNullOrEmpty(txtAdditionalShippingFeePerItem.Text) ? 0 : Convert.ToDecimal(txtAdditionalShippingFeePerItem.Text, CultureInfo.CreateSpecificCulture("en-US"));

                toSave.Weight = String.IsNullOrEmpty(txtWeight.Text) ? 0 : Convert.ToDecimal(txtWeight.Text, CultureInfo.CreateSpecificCulture("en-US"));
                toSave.Length = String.IsNullOrEmpty(txtLength.Text) ? 0 : Convert.ToDecimal(txtLength.Text, CultureInfo.CreateSpecificCulture("en-US"));
                toSave.Width  = String.IsNullOrEmpty(txtWidth.Text) ? 0 : Convert.ToDecimal(txtWidth.Text, CultureInfo.CreateSpecificCulture("en-US"));
                toSave.Height = String.IsNullOrEmpty(txtHeight.Text) ? 0 : Convert.ToDecimal(txtHeight.Text, CultureInfo.CreateSpecificCulture("en-US"));
            }
            else if (toSave.DeliveryMethodId.Value == (short)ProductDeliveryMethod.Downloaded)
            {
                toSave.Weight = 0;
                toSave.Length = null;
                toSave.Width  = null;
                toSave.Height = null;
                toSave.ShippingAdditionalFeePerItem = 0;
            }

            toSave.QuantityWidget  = rdoQuantityWidget.SelectedValue;
            toSave.QuantityOptions = txtQuantityOptions.Text;

            toSave.InventoryIsEnabled = chkInventoryIsEnabled.Checked;
            toSave.InventoryAllowNegativeStockLevel = chkInventoryAllowNegativeStockLevel.Checked;
            toSave.InventoryQtyInStock      = WA.Parser.ToInt(txtInventoryQtyInStock.Text);
            toSave.InventoryQtyLowThreshold = WA.Parser.ToInt(txtInventoryQtyLowThreshold.Text);

            toSave.SeoTitle       = txtSeoTitle.Text;
            toSave.SeoDescription = txtSeoDescription.Text;
            toSave.SeoKeywords    = txtSeoKeywords.Text;

            toSave.CheckoutAssignRoleInfoJson = ParseCheckoutRoleInfoFromPost();
            toSave.ViewPermissions            = ParseViewPermissionInfoFromPost();
            toSave.CheckoutPermissions        = ParseCheckoutPermissionInfoFromPost();


            toSave.Save();

            //---- Product Categories
            List <string> productCategoryIdStrings = new List <string>(Request.Form.GetValues("productCategory") ?? new string[] { });
            List <int?>   productCategoryIds       = productCategoryIdStrings.ConvertAll(s => WA.Parser.ToInt(s));

            productCategoryIds.RemoveAll(i => !i.HasValue);
            Product.SetCategories(toSave.Id.Value, productCategoryIds.ConvertAll(i => i.Value));

            //---- Related Products
            DeletePreviousRelatedProducts(toSave);

            var relatedlatedProducts = new RelatedProductCollection();

            foreach (ListItem p in cblRelatedProducts.Items)
            {
                if (!p.Selected)
                {
                    continue;
                }
                RelatedProduct relatedProduct = relatedlatedProducts.AddNew();
                relatedProduct.ProductId        = toSave.Id;
                relatedProduct.RelatedProductId = Convert.ToInt32(p.Value);
            }

            relatedlatedProducts.Save();


            //---- Digital File upload);
            if (fupDigitalFile.HasFile)
            {
                string fileUploadDirectory = StoreUrls.ProductFileFolderFileRoot;
                string fileExt             = Path.GetExtension(fupDigitalFile.PostedFile.FileName);
                string filenameWithExt     = string.Format("{0}_{1}{2}", toSave.Id.Value, Guid.NewGuid(), fileExt);
                string filePath            = fileUploadDirectory + filenameWithExt;
                //Debug.WriteFormat(@"fileUploadDirectory = ""{0}""", fileUploadDirectory);
                if (!Directory.Exists(fileUploadDirectory))
                {
                    //Debug.WriteFormat(@"creating fileUploadDirectory = ""{0}""", fileUploadDirectory);
                    Directory.CreateDirectory(fileUploadDirectory);
                }
                fupDigitalFile.PostedFile.SaveAs(filePath);

                toSave.DigitalFilename        = filenameWithExt;
                toSave.DigitalFileDisplayName = Path.GetFileNameWithoutExtension(fupDigitalFile.PostedFile.FileName).Left(250);

                toSave.Save();
            }

            //---- Photos are saved via ajax (uploaded via ajax, separately, no need to save here)

            //---- Descriptor Fields
            using (esTransactionScope transaction = new esTransactionScope())
            {
                toSave.ProductDescriptorCollectionByProductId.MarkAllAsDeleted();
                toSave.Save();

                AddDescriptor(txtDescriptorName1.Text, (txtDescriptorText1 as DotNetNuke.UI.UserControls.TextEditor).Text, 1, toSave);
                AddDescriptor(txtDescriptorName2.Text, (txtDescriptorText2 as DotNetNuke.UI.UserControls.TextEditor).Text, 2, toSave);
                AddDescriptor(txtDescriptorName3.Text, (txtDescriptorText3 as DotNetNuke.UI.UserControls.TextEditor).Text, 3, toSave);
                AddDescriptor(txtDescriptorName4.Text, (txtDescriptorText4 as DotNetNuke.UI.UserControls.TextEditor).Text, 4, toSave);
                AddDescriptor(txtDescriptorName5.Text, (txtDescriptorText5 as DotNetNuke.UI.UserControls.TextEditor).Text, 5, toSave);

                toSave.Save();

                transaction.Complete();
            }

            Response.Redirect(StoreUrls.AdminEditProduct(toSave.Id.Value, "Product Saved" + (isNew ? ", you can now add Photos, Descriptions, and Custom Attributes" : "")));
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Replaces/overwrites fields on an existing Product.
        /// ALL matching fields are replaced/overwritten with the values from the CSV file (including empty fields).
        /// Existing Product Categories are first DELETED, and then re-added from the CSV file.
        /// Existing Product Photos are DELETED, and then re-added from the CSV.
        /// </summary>
        /// <param name="p"></param>
        /// <param name="csvProduct"></param>
        private void ReplaceProduct(Product p, CsvProductInfo csvProduct)
        {
            p.Name                             = csvProduct.Name;
            p.Sku                              = csvProduct.Sku;
            p.Slug                             = csvProduct.UrlName.IsValidSlug() ? csvProduct.UrlName : csvProduct.UrlName.CreateSlug();
            p.Price                            = csvProduct.Price;
            p.Weight                           = csvProduct.Weight;
            p.SeoTitle                         = csvProduct.SeoTitle;
            p.SeoDescription                   = csvProduct.SeoDescription;
            p.SeoKeywords                      = csvProduct.SeoKeywords;
            p.IsActive                         = csvProduct.IsActive.GetValueOrDefault(true);
            p.IsTaxable                        = csvProduct.TaxableItem.GetValueOrDefault(true);
            p.IsPriceDisplayed                 = csvProduct.ShowPrice.GetValueOrDefault(true);
            p.IsAvailableForPurchase           = csvProduct.AvailableForPurchase.GetValueOrDefault(true);
            p.InventoryIsEnabled               = csvProduct.EnableInventoryManagement.GetValueOrDefault(false);
            p.InventoryQtyInStock              = csvProduct.StockLevel;
            p.InventoryAllowNegativeStockLevel = csvProduct.AllowNegativeStock.GetValueOrDefault(false);

            if (!p.Slug.IsValidSlug())
            {
                csvLine.Status     = ProductImportStatus.Error;
                csvLine.StatusMsg += string.Format(@"Invalid Slug '{0}' must match the pattern '{1}'", p.Slug, RegexPatterns.IsValidSlug);
                return;
            }
            if (!string.IsNullOrEmpty(p.Sku) && !p.Sku.IsValidSku())
            {
                csvLine.Status     = ProductImportStatus.Error;
                csvLine.StatusMsg += string.Format(@"Invalid Sku '{0}' must match the pattern '{1}'", p.Sku, RegexPatterns.IsValidSku);
                return;
            }

            // save now so we can get an ID for new products
            p.Save();

            //--- Digital File
            if (NotEmpty(p.DigitalFilename))
            {
                File.Delete(Path.Combine(productFilesFolderFileRoot, p.DigitalFilename));
                p.DigitalFilename        = "";
                p.DigitalFileDisplayName = "";
                p.DeliveryMethodId       = (short)ProductDeliveryMethod.Shipped;
            }
            ImportDigitalFile(p, csvProduct.DigitalFilename);

            //--- Descriptors (delete and re-add)
            using (esTransactionScope transaction = new esTransactionScope())
            {
                p.ProductDescriptorCollectionByProductId.MarkAllAsDeleted();
                AddProductDescriptor(p, 1, csvProduct.Desc1Name, csvProduct.Desc1Html); // always add the 1st tab
                if (!string.IsNullOrEmpty(csvProduct.Desc2Name))
                {
                    AddProductDescriptor(p, 2, csvProduct.Desc2Name, csvProduct.Desc2Html);
                }
                if (!string.IsNullOrEmpty(csvProduct.Desc3Name))
                {
                    AddProductDescriptor(p, 3, csvProduct.Desc3Name, csvProduct.Desc3Html);
                }
                if (!string.IsNullOrEmpty(csvProduct.Desc4Name))
                {
                    AddProductDescriptor(p, 4, csvProduct.Desc4Name, csvProduct.Desc4Html);
                }
                if (!string.IsNullOrEmpty(csvProduct.Desc5Name))
                {
                    AddProductDescriptor(p, 5, csvProduct.Desc5Name, csvProduct.Desc5Html);
                }

                transaction.Complete();
            }

            //--- Categories (delete and then re-associate/add)
            p.ProductCategoryCollectionByProductId.MarkAllAsDeleted(); // remove existing product categories
            //p.ProductCategoryCollectionByProductId.Save();
            List <string> newCategoryNames = csvProduct.CategoryNames.ToList(",", true);

            foreach (string newCat in newCategoryNames)
            {
                var c = Category.GetByName(storeId, newCat) ?? CreateCategory(newCat);
                p.AddCategory(c);
            }

            //--- Photos (delete and then re-add)
            p.DeleteAllPhotos(productPhotoFolderFileRoot);
            IEnumerable <string> importPhotoFiles = GetPhotoFilePathsForImport(p, csvProduct);

            foreach (string filepath in importPhotoFiles)
            {
                AddPhoto(p, filepath);
            }

            p.Save();
        }
Ejemplo n.º 25
0
        private void CopyAnnotationData(int fromAnnotationId, int toAnnotationId)
        {
            Annotation ann = new Annotation();

            if (!ann.LoadByPrimaryKey(toAnnotationId))
            {
                MessageBox.Show("To Annotation Not found");
                return;
            }

            ann = new Annotation();
            if (!ann.LoadByPrimaryKey(fromAnnotationId))
            {
                MessageBox.Show("From Annotation Not found");
                return;
            }

            Dictionary <int, int> axisKeys   = new Dictionary <int, int>();
            Dictionary <int, int> seriesKeys = new Dictionary <int, int>();

            using (esTransactionScope scope = new esTransactionScope())
            {
                foreach (AnnotationPlot annPlot in ann.AnnotationPlotCollectionByAnnotationId)
                {
                    AnnotationPlot annPlotClone = new AnnotationPlot();
                    annPlotClone.AnnotationId   = toAnnotationId;
                    annPlotClone.RegionId       = annPlot.RegionId;
                    annPlotClone.Description    = annPlot.Description;
                    annPlotClone.Title          = annPlot.Title;
                    annPlotClone.Type           = annPlot.Type;
                    annPlotClone.DimensionCount = annPlot.DimensionCount;
                    annPlotClone.Save();

                    foreach (AnnotationPlotAxis annPlotAxis in annPlot.AnnotationPlotAxisCollectionByPlotId)
                    {
                        AnnotationPlotAxis annPlotAxisClone = new AnnotationPlotAxis();
                        annPlotAxisClone.PlotId    = annPlotClone.Id;
                        annPlotAxisClone.Label     = annPlotAxis.Label;
                        annPlotAxisClone.MinValue  = annPlotAxis.MinValue;
                        annPlotAxisClone.MaxValue  = annPlotAxis.MaxValue;
                        annPlotAxisClone.Scale     = annPlotAxis.Scale;
                        annPlotAxisClone.Type      = annPlotAxis.Type;
                        annPlotAxisClone.Dimension = annPlotAxis.Dimension;
                        annPlotAxisClone.Save();
                        axisKeys.Add(annPlotAxis.Id.Value, annPlotAxisClone.Id.Value);
                    }

                    foreach (AnnotationPlotSeries annPlotSeries in annPlot.AnnotationPlotSeriesCollectionByPlotId)
                    {
                        AnnotationPlotSeries annPlotSeriesClone = new AnnotationPlotSeries();
                        annPlotSeriesClone.PlotId      = annPlotClone.Id;
                        annPlotSeriesClone.Description = annPlotSeries.Description;
                        annPlotSeriesClone.ColorRGB    = annPlotSeries.ColorRGB;
                        annPlotSeriesClone.Save();
                        seriesKeys.Add(annPlotSeries.Id.Value, annPlotSeriesClone.Id.Value);
                    }
                }

                foreach (AnnotationPlot annPlot in ann.AnnotationPlotCollectionByAnnotationId)
                {
                    foreach (AnnotationPlotAxis annPlotAxis in annPlot.AnnotationPlotAxisCollectionByPlotId)
                    {
                        foreach (AnnotationPlotAxisData annPlotAxisData in annPlotAxis.AnnotationPlotAxisDataCollectionByAxisId)
                        {
                            AnnotationPlotAxisData annPlotAxisDataClone = new AnnotationPlotAxisData();
                            annPlotAxisDataClone.AxisId   = axisKeys[annPlotAxisData.AxisId.Value];
                            annPlotAxisDataClone.SeriesId = seriesKeys[annPlotAxisData.SeriesId.Value];
                            annPlotAxisDataClone.DataBin  = annPlotAxisData.DataBin;
                            annPlotAxisDataClone.Save();
                        }
                    }

                    foreach (AnnotationPlotSeries annPlotSeries in annPlot.AnnotationPlotSeriesCollectionByPlotId)
                    {
                        foreach (AnnotationPlotAxisData annPlotAxisData in annPlotSeries.AnnotationPlotAxisDataCollectionBySeriesId)
                        {
                            AnnotationPlotAxisData annPlotAxisDataClone = new AnnotationPlotAxisData();
                            annPlotAxisDataClone.Query.Where(
                                annPlotAxisDataClone.Query.AxisId == axisKeys[annPlotAxisData.AxisId.Value] &&
                                annPlotAxisDataClone.Query.SeriesId == seriesKeys[annPlotAxisData.SeriesId.Value]);

                            if (!annPlotAxisDataClone.Query.Load())
                            {
                                annPlotAxisDataClone          = new AnnotationPlotAxisData();
                                annPlotAxisDataClone.AxisId   = axisKeys[annPlotAxisData.AxisId.Value];
                                annPlotAxisDataClone.SeriesId = seriesKeys[annPlotAxisData.SeriesId.Value];
                                annPlotAxisDataClone.DataBin  = annPlotAxisData.DataBin;
                                annPlotAxisDataClone.Save();
                            }
                        }
                    }
                }
                scope.Complete();
            }
        }
        static private DataTable SaveDynamicCollection_InsertsUpdates(esDataRequest request)
        {
            DataTable dataTable = CreateDataTable(request);

            using (esTransactionScope scope = new esTransactionScope())
            {
                using (VistaDBDataAdapter da = new VistaDBDataAdapter())
                {
                    da.AcceptChangesDuringUpdate = false;
                    da.ContinueUpdateOnError     = request.ContinueUpdateOnError;

                    VistaDBCommand cmd = null;

                    if (!request.IgnoreComputedColumns)
                    {
                        da.RowUpdated += new VistaDBRowUpdatedEventHandler(OnRowUpdated);
                    }

                    foreach (esEntitySavePacket packet in request.CollectionSavePacket)
                    {
                        if (packet.RowState != esDataRowState.Added && packet.RowState != esDataRowState.Modified)
                        {
                            continue;
                        }

                        DataRow row = dataTable.NewRow();
                        dataTable.Rows.Add(row);

                        switch (packet.RowState)
                        {
                        case esDataRowState.Added:
                            cmd = da.InsertCommand = Shared.BuildDynamicInsertCommand(request, packet.ModifiedColumns);
                            SetModifiedValues(request, packet, row);
                            break;

                        case esDataRowState.Modified:
                            cmd = da.UpdateCommand = Shared.BuildDynamicUpdateCommand(request, packet.ModifiedColumns);
                            SetOriginalValues(request, packet, row, false);
                            SetModifiedValues(request, packet, row);
                            row.AcceptChanges();
                            row.SetModified();
                            break;
                        }

                        request.Properties["esDataRequest"]   = request;
                        request.Properties["esEntityData"]    = packet;
                        dataTable.ExtendedProperties["props"] = request.Properties;

                        DataRow[] singleRow = new DataRow[1];
                        singleRow[0] = row;

                        try
                        {
                            esTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate);
                            da.Update(singleRow);

                            if (row.HasErrors)
                            {
                                request.FireOnError(packet, row.RowError);
                            }
                        }
                        finally
                        {
                            esTransactionScope.DeEnlist(cmd);
                            dataTable.Rows.Clear();
                        }

                        if (!row.HasErrors && cmd.Parameters != null)
                        {
                            foreach (VistaDBParameter param in cmd.Parameters)
                            {
                                switch (param.Direction)
                                {
                                case ParameterDirection.Output:
                                case ParameterDirection.InputOutput:

                                    packet.CurrentValues[param.SourceColumn] = param.Value;
                                    break;
                                }
                            }
                        }

                        cmd.Dispose();
                    }
                }

                scope.Complete();
            }

            return(dataTable);
        }
        static private DataTable SaveStoredProcCollection(esDataRequest request)
        {
            bool needToInsert = false;
            bool needToUpdate = false;
            bool needToDelete = false;

            Dictionary <DataRow, esEntitySavePacket> rowMapping = null;

            if (request.ContinueUpdateOnError)
            {
                rowMapping = new Dictionary <DataRow, esEntitySavePacket>();
            }

            //================================================
            // Create the DataTable ...
            //================================================
            DataTable dataTable = CreateDataTable(request);

            foreach (esEntitySavePacket packet in request.CollectionSavePacket)
            {
                DataRow row = dataTable.NewRow();

                switch (request.EntitySavePacket.RowState)
                {
                case esDataRowState.Added:
                    SetModifiedValues(request, packet, row);
                    dataTable.Rows.Add(row);
                    if (request.ContinueUpdateOnError)
                    {
                        rowMapping[row] = packet;
                    }
                    break;

                case esDataRowState.Modified:
                    SetOriginalValues(request, packet, row, false);
                    SetModifiedValues(request, packet, row);
                    dataTable.Rows.Add(row);
                    row.AcceptChanges();
                    row.SetModified();
                    if (request.ContinueUpdateOnError)
                    {
                        rowMapping[row] = packet;
                    }
                    break;

                case esDataRowState.Deleted:
                    SetOriginalValues(request, packet, row, true);
                    dataTable.Rows.Add(row);
                    row.AcceptChanges();
                    row.Delete();
                    if (request.ContinueUpdateOnError)
                    {
                        rowMapping[row] = packet;
                    }
                    break;
                }
            }

            if (Shared.HasUpdates(dataTable.Rows, out needToInsert, out needToUpdate, out needToDelete))
            {
                using (SADataAdapter da = new SADataAdapter())
                {
                    da.AcceptChangesDuringUpdate = false;
                    da.ContinueUpdateOnError     = request.ContinueUpdateOnError;

                    SACommand cmd = null;

                    if (needToInsert)
                    {
                        da.InsertCommand = cmd = Shared.BuildStoredProcInsertCommand(request);
                    }
                    if (needToUpdate)
                    {
                        da.UpdateCommand = cmd = Shared.BuildStoredProcUpdateCommand(request);
                    }
                    if (needToDelete)
                    {
                        da.DeleteCommand = cmd = Shared.BuildStoredProcDeleteCommand(request);
                    }

                    using (esTransactionScope scope = new esTransactionScope())
                    {
                        if (needToInsert)
                        {
                            esTransactionScope.Enlist(da.InsertCommand, request.ConnectionString, CreateIDbConnectionDelegate);
                        }
                        if (needToUpdate)
                        {
                            esTransactionScope.Enlist(da.UpdateCommand, request.ConnectionString, CreateIDbConnectionDelegate);
                        }
                        if (needToDelete)
                        {
                            esTransactionScope.Enlist(da.DeleteCommand, request.ConnectionString, CreateIDbConnectionDelegate);
                        }

                        try
                        {
                            da.Update(dataTable);
                        }
                        finally
                        {
                            if (needToInsert)
                            {
                                esTransactionScope.DeEnlist(da.InsertCommand);
                            }
                            if (needToUpdate)
                            {
                                esTransactionScope.DeEnlist(da.UpdateCommand);
                            }
                            if (needToDelete)
                            {
                                esTransactionScope.DeEnlist(da.DeleteCommand);
                            }
                        }

                        scope.Complete();
                    }
                }

                if (request.ContinueUpdateOnError && dataTable.HasErrors)
                {
                    DataRow[] errors = dataTable.GetErrors();

                    foreach (DataRow rowWithError in errors)
                    {
                        request.FireOnError(rowMapping[rowWithError], rowWithError.RowError);
                    }
                }
            }

            return(request.Table);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Updates an existing product.
        /// A field is only updated if the CSV field is non-empty.
        /// Existing Product Categories are kept, and new Categories are added from the CSV file.
        /// Existing Product Photos are kept, and new Photos are added.
        /// </summary>
        /// <param name="p"></param>
        /// <param name="csvProduct"></param>
        private void UpdateProduct(Product p, CsvProductInfo csvProduct)
        {
            if (NotEmpty(csvProduct.Name))
            {
                p.Name = csvProduct.Name;
            }
            if (NotEmpty(csvProduct.Sku))
            {
                p.Sku = csvProduct.Sku;
            }
            if (NotEmpty(csvProduct.UrlName))
            {
                p.Slug = csvProduct.UrlName.IsValidSlug() ? csvProduct.UrlName : csvProduct.UrlName.CreateSlug();
            }
            if (csvProduct.Price.HasValue)
            {
                p.Price = csvProduct.Price;
            }
            if (csvProduct.Weight.HasValue)
            {
                p.Weight = csvProduct.Weight;
            }
            if (NotEmpty(csvProduct.SeoTitle))
            {
                p.SeoTitle = csvProduct.SeoTitle;
            }
            if (NotEmpty(csvProduct.SeoDescription))
            {
                p.SeoDescription = csvProduct.SeoDescription;
            }
            if (NotEmpty(csvProduct.SeoKeywords))
            {
                p.SeoKeywords = csvProduct.SeoKeywords;
            }
            if (csvProduct.IsActive.HasValue)
            {
                p.IsActive = csvProduct.IsActive;
            }
            if (csvProduct.TaxableItem.HasValue)
            {
                p.IsTaxable = csvProduct.TaxableItem;
            }
            if (csvProduct.ShowPrice.HasValue)
            {
                p.IsPriceDisplayed = csvProduct.ShowPrice;
            }
            if (csvProduct.AvailableForPurchase.HasValue)
            {
                p.IsAvailableForPurchase = csvProduct.AvailableForPurchase;
            }
            if (csvProduct.EnableInventoryManagement.HasValue)
            {
                p.InventoryIsEnabled = csvProduct.EnableInventoryManagement;
            }
            p.InventoryQtyInStock = csvProduct.StockLevel.HasValue ? csvProduct.StockLevel : null;

            if (csvProduct.AllowNegativeStock.HasValue)
            {
                p.InventoryAllowNegativeStockLevel = csvProduct.AllowNegativeStock;
            }

            if (!p.Slug.IsValidSlug())
            {
                csvLine.Status     = ProductImportStatus.Error;
                csvLine.StatusMsg += string.Format(@"Invalid Slug '{0}' must match the pattern '{1}'", p.Slug, RegexPatterns.IsValidSlug);
                return;
            }
            if (!string.IsNullOrEmpty(p.Sku) && !p.Sku.IsValidSku())
            {
                csvLine.Status     = ProductImportStatus.Error;
                csvLine.StatusMsg += string.Format(@"Invalid Sku '{0}' must match the pattern '{1}'", p.Sku, RegexPatterns.IsValidSku);
                return;
            }

            //--- Digital File
            if (NotEmpty(csvProduct.DigitalFilename))
            {
                if (NotEmpty(p.DigitalFilename))
                {
                    File.Delete(Path.Combine(productFilesFolderFileRoot, p.DigitalFilename));
                }
                ImportDigitalFile(p, csvProduct.DigitalFilename);
            }

            //--- Descriptors (update/add if different, but preserve existing)
            using (esTransactionScope transaction = new esTransactionScope())
            {
                var existingDescriptors = p.GetProductDescriptors();
                var newDescriptors      = new Dictionary <int, DescriptorInfo>();
                for (short i = 0; i < 5; i++)
                {
                    //var descriptor = (i < existingDescriptors.Count) ? existingDescriptors[i] : new ProductDescriptor();
                    //descriptor.SortOrder = i;
                    //newDescriptors[i] = descriptor;

                    if (i < existingDescriptors.Count)
                    {
                        newDescriptors[i] = new DescriptorInfo()
                        {
                            Name = existingDescriptors[i].Name, Text = existingDescriptors[i].Text
                        };
                    }
                    else
                    {
                        newDescriptors[i] = new DescriptorInfo();
                    }
                }
                if (NotEmpty(csvProduct.Desc1Name))
                {
                    newDescriptors[0].Name = csvProduct.Desc1Name;
                }
                if (NotEmpty(csvProduct.Desc2Name))
                {
                    newDescriptors[1].Name = csvProduct.Desc2Name;
                }
                if (NotEmpty(csvProduct.Desc3Name))
                {
                    newDescriptors[2].Name = csvProduct.Desc3Name;
                }
                if (NotEmpty(csvProduct.Desc4Name))
                {
                    newDescriptors[3].Name = csvProduct.Desc4Name;
                }
                if (NotEmpty(csvProduct.Desc5Name))
                {
                    newDescriptors[4].Name = csvProduct.Desc5Name;
                }
                if (NotEmpty(csvProduct.Desc1Html))
                {
                    newDescriptors[0].Text = csvProduct.Desc1Html;
                }
                if (NotEmpty(csvProduct.Desc2Html))
                {
                    newDescriptors[1].Text = csvProduct.Desc2Html;
                }
                if (NotEmpty(csvProduct.Desc3Html))
                {
                    newDescriptors[2].Text = csvProduct.Desc3Html;
                }
                if (NotEmpty(csvProduct.Desc4Html))
                {
                    newDescriptors[3].Text = csvProduct.Desc4Html;
                }
                if (NotEmpty(csvProduct.Desc5Html))
                {
                    newDescriptors[4].Text = csvProduct.Desc5Html;
                }

                p.ProductDescriptorCollectionByProductId.MarkAllAsDeleted();
                for (short i = 0; i < newDescriptors.Count; i++)
                {
                    var descr = newDescriptors[i];
                    if (NotEmpty(descr.Name) || NotEmpty(descr.Text))
                    {
                        AddProductDescriptor(p, i, descr.Name, descr.Text);
                    }
                }

                transaction.Complete();
            }

            //--- Categories (add new, but don't delete existing)
            List <Category> existingProductCategories = p.GetCategories(true);
            List <string>   newCategoryNames          = csvProduct.CategoryNames.ToList(",", true);

            newCategoryNames.RemoveAll(x => existingProductCategories.Exists(c => c.Name == x));
            foreach (string newCat in newCategoryNames)
            {
                var c = Category.GetByName(storeId, newCat) ?? CreateCategory(newCat);
                p.AddCategory(c);
            }

            //--- Photos (add new, but don't delete existing)
            IEnumerable <string> importPhotoFiles = GetPhotoFilePathsForImport(p, csvProduct);

            foreach (string filepath in importPhotoFiles)
            {
                AddPhoto(p, filepath);
            }

            p.Save();
        }
Ejemplo n.º 29
0
        protected void cmdSave_Click(object sender, EventArgs e)
        {
            //Add the news item
            using (esTransactionScope scope = new esTransactionScope())
            {
                if (fundId == -1)
                {
                    //New Item
                    OMAMFund fundDetail = new OMAMFund();
                    fundDetail.FundCode            = txtFundCode.Text.ToString();
                    fundDetail.FundName            = txtFundName.Text.ToString();
                    fundDetail.FundSnippet         = edtShortDesc.Text.ToString();
                    fundDetail.RiskWarning         = edtRiskWarning.Text.ToString();
                    fundDetail.FundAims            = edtFundAims.Text.ToString();
                    fundDetail.CreatedBy           = UserId;
                    fundDetail.CreatedDate         = DateTime.Now;
                    fundDetail.SPRatingURL         = ddlSPRating.SelectedValue.ToString();
                    fundDetail.OBSRRatingURL       = ddlOBSRRating.SelectedValue.ToString();
                    fundDetail.CityWireRatingURL   = ddlCitywireRating.SelectedValue.ToString();
                    fundDetail.CityWitreRatingCopy = edtCityWireRating.Text.ToString();
                    fundDetail.OBSRRatingCopy      = edtOBSRRating.Text.ToString();
                    fundDetail.SPRatingCopy        = edtSPRating.Text.ToString();

                    if (ddlAnnual.SelectedIndex > 0)
                    {
                        fundDetail.AnnualReportFile = ddlAnnual.SelectedValue.ToString();
                        fundDetail.AnnualReportURL  = Settings["AnnualReportFolder"].ToString();
                    }

                    if (ddlFactsheet.SelectedIndex > 0)
                    {
                        fundDetail.FactsheetFile = ddlFactsheet.SelectedValue.ToString();
                        fundDetail.FactsheetURL  = Settings["FactsheetFolder"].ToString();
                    }

                    if (ddlInterim.SelectedIndex > 0)
                    {
                        fundDetail.InterimReportFile = ddlInterim.SelectedValue.ToString();
                        fundDetail.InterimReportURL  = Settings["InterimFolder"].ToString();
                    }

                    if (ddlOBSRReport.SelectedIndex > 0)
                    {
                        fundDetail.OBSRReportFile = ddlOBSRReport.SelectedValue.ToString();
                        fundDetail.OBSRReportURL  = Settings["OBSRReportFolder"].ToString();
                    }

                    if (ddlReasons.SelectedIndex > 0)
                    {
                        fundDetail.ReasonsWhyFile = ddlReasons.SelectedValue.ToString();
                        fundDetail.ReasonsWhyURL  = Settings["ReasonFolder"].ToString();
                    }

                    if (ddlSalesAid.SelectedIndex > 0)
                    {
                        fundDetail.SalesAidFile = ddlSalesAid.SelectedValue.ToString();
                        fundDetail.SalesAidURL  = Settings["SalesAidFolder"].ToString();
                    }

                    if (ddlSPReport.SelectedIndex > 0)
                    {
                        fundDetail.SPReportFile = ddlSPReport.SelectedValue.ToString();
                        fundDetail.SPReportURL  = Settings["SPReportFolder"].ToString();
                    }

                    if (ddlTermsheet.SelectedIndex > 0)
                    {
                        fundDetail.TermsheetFile = ddlTermsheet.SelectedValue.ToString();
                        fundDetail.TermsheetURL  = Settings["TermsheetFolder"].ToString();
                    }

                    fundDetail.Save();

                    fundId = fundDetail.Id;
                }
                else
                {
                    Fund.FundCode            = txtFundCode.Text.ToString();
                    Fund.FundName            = txtFundName.Text.ToString();
                    Fund.FundSnippet         = edtShortDesc.Text.ToString();
                    Fund.RiskWarning         = edtRiskWarning.Text.ToString();
                    Fund.FundAims            = edtFundAims.Text.ToString();
                    Fund.SPRatingURL         = ddlSPRating.SelectedValue.ToString();
                    Fund.OBSRRatingURL       = ddlOBSRRating.SelectedValue.ToString();
                    Fund.CityWireRatingURL   = ddlCitywireRating.SelectedValue.ToString();
                    Fund.CityWitreRatingCopy = edtCityWireRating.Text.ToString();
                    Fund.OBSRRatingCopy      = edtOBSRRating.Text.ToString();
                    Fund.SPRatingCopy        = edtSPRating.Text.ToString();

                    if (ddlAnnual.SelectedIndex > 0)
                    {
                        Fund.AnnualReportFile = ddlAnnual.SelectedValue.ToString();
                        Fund.AnnualReportURL  = Settings["AnnualReportFolder"].ToString();
                    }

                    if (ddlFactsheet.SelectedIndex > 0)
                    {
                        Fund.FactsheetFile = ddlFactsheet.SelectedValue.ToString();
                        Fund.FactsheetURL  = Settings["FactsheetFolder"].ToString();
                    }

                    if (ddlInterim.SelectedIndex > 0)
                    {
                        Fund.InterimReportFile = ddlInterim.SelectedValue.ToString();
                        Fund.InterimReportURL  = Settings["InterimFolder"].ToString();
                    }

                    if (ddlOBSRReport.SelectedIndex > 0)
                    {
                        Fund.OBSRReportFile = ddlOBSRReport.SelectedValue.ToString();
                        Fund.OBSRReportURL  = Settings["OBSRReportFolder"].ToString();
                    }

                    if (ddlReasons.SelectedIndex > 0)
                    {
                        Fund.ReasonsWhyFile = ddlReasons.SelectedValue.ToString();
                        Fund.ReasonsWhyURL  = Settings["ReasonFolder"].ToString();
                    }

                    if (ddlSalesAid.SelectedIndex > 0)
                    {
                        Fund.SalesAidFile = ddlSalesAid.SelectedValue.ToString();
                        Fund.SalesAidURL  = Settings["SalesAidFolder"].ToString();
                    }

                    if (ddlSPReport.SelectedIndex > 0)
                    {
                        Fund.SPReportFile = ddlSPReport.SelectedValue.ToString();
                        Fund.SPReportURL  = Settings["SPReportFolder"].ToString();
                    }

                    if (ddlTermsheet.SelectedIndex > 0)
                    {
                        Fund.TermsheetFile = ddlTermsheet.SelectedValue.ToString();
                        Fund.TermsheetURL  = Settings["TermsheetFolder"].ToString();
                    }

                    Fund.Save();
                }

                //Remove all the assigned categories first
                OMAMLNKFundCategoriesCollection fundCategories = new OMAMLNKFundCategoriesCollection();

                fundCategories.Query
                .Where(fundCategories.Query.FundId == fundId);

                fundCategories.Query.Load();
                fundCategories.MarkAllAsDeleted();
                fundCategories.Save();

                //OK, Now add the newly assigned funds
                for (int i = 0; i < cblCategoriesAssigned.Items.Count; i++)
                {
                    OMAMLNKFundCategories assignedCategory = new OMAMLNKFundCategories();
                    assignedCategory.CategoryId = Convert.ToInt16(cblCategoriesAssigned.Items[i].Value);
                    assignedCategory.FundId     = fundId;
                    assignedCategory.Save();
                }

                scope.Complete();

                Response.Redirect(Globals.NavigateURL(), true);
            }
        }