Beispiel #1
0
 public static void SetDefaultsForNew(this ProductBundle productBundle, StoreFront storeFront)
 {
     if (storeFront == null)
     {
         throw new ArgumentNullException("storeFront");
     }
     productBundle.ClientId     = storeFront.ClientId;
     productBundle.Client       = storeFront.Client;
     productBundle.StoreFrontId = storeFront.StoreFrontId;
     productBundle.StoreFront   = storeFront;
     if (storeFront.ProductBundles == null || storeFront.ProductBundles.Count == 0)
     {
         productBundle.Name  = "New Product Bundle";
         productBundle.Order = 100;
     }
     else
     {
         productBundle.Order = (storeFront.ProductBundles.Max(nb => nb.Order) + 10);
         productBundle.Name  = "New Product Bundle " + productBundle.Order;
     }
     productBundle.UrlName              = productBundle.Name.Replace(' ', '_');
     productBundle.ImageName            = null;
     productBundle.MaxQuantityPerOrder  = 0;
     productBundle.AvailableForPurchase = true;
     productBundle.MetaDescription      = productBundle.Name;
     productBundle.MetaKeywords         = productBundle.Name;
     productBundle.IsPending            = false;
     productBundle.EndDateTimeUtc       = DateTime.UtcNow.AddYears(100);
     productBundle.StartDateTimeUtc     = DateTime.UtcNow.AddMinutes(-1);
 }
Beispiel #2
0
        protected void SetMetaTags(ProductBundle bundle)
        {
            StoreFrontConfiguration config = CurrentStoreFrontConfigOrThrow;

            _metaDescriptionOverride = bundle.MetaDescriptionOrSystemDefault(config);
            _metaKeywordsOverride    = bundle.MetaKeywordsOrSystemDefault(config);
        }
 public async Task CreateProductBundle(ProductBundle productBundle)
 {
     /*
      * await _productBundleRepository.InsertAsync(productBundle);
      */
     throw new NotImplementedException();
 }
Beispiel #4
0
        public void AggregateRoot_repository_with_TPrimaryKey()
        {
            Guid         aggregateId = Guid.NewGuid();
            const string bundleName  = "SampleBundle";

            string eventLog  = string.Empty;
            string headerLog = string.Empty;

            The <IEventBus>().RegisterPublishingBehaviour((@event, headers) =>
            {
                eventLog  = @event.ToJsonString(true, true);
                headerLog = headers.ToString();
            });

            The <IEventBus>().Register <ProductBundleCreated>((@event, headers) =>
            {
                @event.Name.ShouldBe(bundleName);
                @event.Id.ShouldBe(aggregateId);
                headers.GetAggregateId().ShouldBe(aggregateId.ToString());
            });

            using (IUnitOfWorkCompleteHandle uow = The <IUnitOfWorkManager>().Begin())
            {
                The <IRepository <ProductBundle, Guid> >().Insert(ProductBundle.Create(aggregateId, bundleName));
                uow.Complete();
            }

            eventLog.ShouldNotBeEmpty();
            headerLog.ShouldNotBeEmpty();
        }
        public HttpResponseMessage add(ProductBundle post)
        {
            // Check for errors
            if (post == null)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null");
            }
            else if (Product.MasterPostExists(post.bundle_product_id) == false)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The bundle product does not exist");
            }
            else if (Product.MasterPostExists(post.product_id) == false)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The product does not exist");
            }
            else if (ProductBundle.GetOneById(post.bundle_product_id, post.product_id) != null)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The product bundle already exists");
            }

            // Make sure that the data is valid
            post.quantity = AnnytabDataValidation.TruncateDecimal(post.quantity, 0, 999999.99M);

            // Add the post
            ProductBundle.Add(post);

            // Return the success response
            return Request.CreateResponse<string>(HttpStatusCode.OK, "The post has been added");

        } // End of the add method
Beispiel #6
0
        protected void RemoveItem(ProductBundle bundle, int productId)
        {
            if (bundle == null)
            {
                throw new ArgumentNullException("bundle");
            }

            ProductBundleItem bundleItem = bundle.ProductBundleItems.SingleOrDefault(pbi => pbi.ProductId == productId);

            if (bundleItem == null)
            {
                AddUserMessage("Bundle Item not found", "The item you are trying to remove (Product Id: " + productId + ") is no longer in bundle '" + bundle.Name.ToHtml() + "' [" + bundle.ProductBundleId + "]", UserMessageType.Info);
                return;
            }
            else
            {
                string itemToRemoveName    = bundleItem.Product.Name;
                int    productBundleItemId = bundleItem.ProductBundleItemId;
                bool   result = GStoreDb.ProductBundleItems.DeleteById(productBundleItemId);
                if (result)
                {
                    GStoreDb.SaveChanges();
                    AddUserMessage("Bundle Item Removed", "Bundle item '" + itemToRemoveName.ToHtml() + "' [" + productBundleItemId + "] was removed from bundle '" + bundle.Name.ToHtml() + "' [" + bundle.ProductBundleId + "]", UserMessageType.Success);
                }
                else
                {
                    AddUserMessage("Bundle Item Delete Error", "The item you are trying to remove '" + itemToRemoveName.ToHtml() + "' [" + productBundleItemId + "] could not be deleted from bundle '" + bundle.Name.ToHtml() + "' [" + bundle.ProductBundleId + "]", UserMessageType.Info);
                }
            }
        }
Beispiel #7
0
        public ActionResult Delete(int?id, string Tab, bool returnToFrontEnd = false)
        {
            if (!id.HasValue)
            {
                return(HttpBadRequest("ProductBundleId = null"));
            }

            StoreFront    storeFront    = CurrentStoreFrontOrThrow;
            ProductBundle productBundle = storeFront.ProductBundles.Where(p => p.ProductBundleId == id.Value).SingleOrDefault();

            if (productBundle == null)
            {
                AddUserMessage("Product Bundle not found", "Sorry, the Product Bundle you are trying to Delete cannot be found. Product Bundle id: [" + id.Value + "] for Store Front '" + storeFront.CurrentConfig().Name.ToHtml() + "' [" + storeFront.StoreFrontId + "]", UserMessageType.Danger);
                if (returnToFrontEnd)
                {
                    return(RedirectToAction("Index", "Catalog", new { area = "" }));
                }
                if (storeFront.Authorization_IsAuthorized(CurrentUserProfileOrThrow, GStoreAction.Bundles_Manager))
                {
                    return(RedirectToAction("Manager", new { ProductCategoryId = productBundle.ProductCategoryId }));
                }
                return(RedirectToAction("Index", "CatalogAdmin"));
            }

            ProductBundleEditAdminViewModel viewModel = new ProductBundleEditAdminViewModel(productBundle, CurrentUserProfileOrThrow, isDeletePage: true, activeTab: Tab);

            viewModel.ReturnToFrontEnd = returnToFrontEnd;
            ViewData.Add("ReturnToFrontEnd", returnToFrontEnd);
            return(View("Delete", viewModel));
        }
Beispiel #8
0
        public HttpResponseMessage update(ProductBundle post)
        {
            // Check for errors
            if (post == null)
            {
                return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The post is null"));
            }

            // Make sure that the data is valid
            post.quantity = AnnytabDataValidation.TruncateDecimal(post.quantity, 0, 999999.99M);

            // Get the saved post
            ProductBundle savedPost = ProductBundle.GetOneById(post.bundle_product_id, post.product_id);

            // Check if the post exists
            if (savedPost == null)
            {
                return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The record does not exist"));
            }

            // Update the post
            ProductBundle.Update(post);

            // Return the success response
            return(Request.CreateResponse <string>(HttpStatusCode.OK, "The update was successful"));
        } // End of the update method
Beispiel #9
0
        public HttpResponseMessage add(ProductBundle post)
        {
            // Check for errors
            if (post == null)
            {
                return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The post is null"));
            }
            else if (Product.MasterPostExists(post.bundle_product_id) == false)
            {
                return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The bundle product does not exist"));
            }
            else if (Product.MasterPostExists(post.product_id) == false)
            {
                return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The product does not exist"));
            }
            else if (ProductBundle.GetOneById(post.bundle_product_id, post.product_id) != null)
            {
                return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The product bundle already exists"));
            }

            // Make sure that the data is valid
            post.quantity = AnnytabDataValidation.TruncateDecimal(post.quantity, 0, 999999.99M);

            // Add the post
            ProductBundle.Add(post);

            // Return the success response
            return(Request.CreateResponse <string>(HttpStatusCode.OK, "The post has been added"));
        } // End of the add method
        public HttpResponseMessage update(ProductBundle post)
        {
            // Check for errors
            if (post == null)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null");
            }

            // Make sure that the data is valid
            post.quantity = AnnytabDataValidation.TruncateDecimal(post.quantity, 0, 999999.99M);

            // Get the saved post
            ProductBundle savedPost = ProductBundle.GetOneById(post.bundle_product_id, post.product_id);

            // Check if the post exists
            if (savedPost == null)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The record does not exist");
            }

            // Update the post
            ProductBundle.Update(post);

            // Return the success response
            return Request.CreateResponse<string>(HttpStatusCode.OK, "The update was successful");

        } // End of the update method
        protected void LoadValues(UserProfile userProfile, ProductBundle productBundle)
        {
            if (productBundle == null)
            {
                return;
            }
            this.IsActiveDirect = productBundle.IsActiveDirect();
            this.IsActiveBubble = productBundle.IsActiveBubble();

            this.ProductBundle           = productBundle;
            this.Client                  = productBundle.Client;
            this.ClientId                = (productBundle.Client == null ? 0 : productBundle.ClientId);
            this.CreateDateTimeUtc       = productBundle.CreateDateTimeUtc;
            this.CreatedBy               = productBundle.CreatedBy;
            this.CreatedBy_UserProfileId = productBundle.CreatedBy_UserProfileId;
            this.EndDateTimeUtc          = productBundle.EndDateTimeUtc;
            this.ForRegisteredOnly       = productBundle.ForRegisteredOnly;
            this.ForAnonymousOnly        = productBundle.ForAnonymousOnly;
            this.IsPending               = productBundle.IsPending;
            this.Name                    = productBundle.Name;
            this.UrlName                 = productBundle.UrlName;
            this.ImageName               = productBundle.ImageName;
            this.ProductBundleId         = productBundle.ProductBundleId;
            this.Order                   = productBundle.Order;
            this.Category                = productBundle.Category;
            this.ProductCategoryId       = productBundle.ProductCategoryId;
            this.StartDateTimeUtc        = productBundle.StartDateTimeUtc;
            this.StoreFront              = productBundle.StoreFront;
            this.StoreFrontId            = productBundle.StoreFrontId;
            this.UpdateDateTimeUtc       = productBundle.UpdateDateTimeUtc;
            this.UpdatedBy               = productBundle.UpdatedBy;
            this.UpdatedBy_UserProfileId = productBundle.UpdatedBy_UserProfileId;

            this.MaxQuantityPerOrder = productBundle.MaxQuantityPerOrder;
            this.MetaDescription     = productBundle.MetaDescription;
            this.MetaKeywords        = productBundle.MetaKeywords;

            this.AvailableForPurchase = productBundle.AvailableForPurchase;
            this.RequestAQuote_Show   = productBundle.RequestAQuote_Show;
            this.RequestAQuote_Label  = productBundle.RequestAQuote_Label;
            this.RequestAQuote_PageId = productBundle.RequestAQuote_PageId;
            this.RequestAQuote_Page   = productBundle.RequestAQuote_Page;
            this.Theme   = productBundle.Theme;
            this.ThemeId = productBundle.ThemeId;
            this.ProductBundleDetailTemplate = productBundle.ProductBundleDetailTemplate;
            this.SummaryCaption           = productBundle.SummaryCaption;
            this.SummaryHtml              = productBundle.SummaryHtml;
            this.TopDescriptionCaption    = productBundle.TopDescriptionCaption;
            this.TopDescriptionHtml       = productBundle.TopDescriptionHtml;
            this.TopLinkHref              = productBundle.TopLinkHref;
            this.TopLinkLabel             = productBundle.TopLinkLabel;
            this.BottomDescriptionCaption = productBundle.BottomDescriptionCaption;
            this.BottomDescriptionHtml    = productBundle.BottomDescriptionHtml;
            this.BottomLinkHref           = productBundle.BottomLinkHref;
            this.BottomLinkLabel          = productBundle.BottomLinkLabel;
            this.FooterHtml        = productBundle.FooterHtml;
            this.ProductTypeSingle = productBundle.ProductTypeSingle;
            this.ProductTypePlural = productBundle.ProductTypePlural;
        }
Beispiel #12
0
        public ProductBundle get_by_id(Int32 id = 0, Int32 productId = 0)
        {
            // Create the post to return
            ProductBundle post = ProductBundle.GetOneById(id, productId);

            // Return the post
            return(post);
        } // End of the get_by_id method
Beispiel #13
0
        /// <summary>
        /// Create a product
        /// </summary>
        /// <param name="productData">Product object to be created</param>
        /// <returns>Created product object</returns>
        public async Task <Product> Create(Product productData)
        {
            var bundle = new ProductBundle {
                Content = productData
            };

            return((await Post(apiEndpoint: "products", toSerialize: bundle)).Content);
        }
Beispiel #14
0
        public List <ProductBundle> get_all()
        {
            // Create the list to return
            List <ProductBundle> posts = ProductBundle.GetAll();

            // Return the list
            return(posts);
        } // End of the get_all method
Beispiel #15
0
        public List <ProductBundle> get_by_bundle_product_id(Int32 id = 0)
        {
            // Create the list to return
            List <ProductBundle> posts = ProductBundle.GetByBundleProductId(id);

            // Return the list
            return(posts);
        } // End of the get_by_bundle_product_id method
Beispiel #16
0
        /// <summary>
        /// Updated a Product
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="newData"></param>
        /// <returns></returns>
        public async Task <Product> Update(int productId, Product newData)
        {
            var endPoint = String.Format("products/{0}", productId);
            var bundle   = new ProductBundle {
                Content = newData
            };

            return((await Put(endPoint, toSerialize: bundle)).Content);
        }
Beispiel #17
0
    } // End of the Update method

    #endregion

    #region Get methods

    /// <summary>
    /// Get one product bundle on id
    /// </summary>
    /// <param name="bundleProductId">A bundle product id</param>
    /// <param name="productId">An product id</param>
    /// <returns>A reference to a product bundle post</returns>
    public static ProductBundle GetOneById(Int32 bundleProductId, Int32 productId)
    {
        // Create the post to return
        ProductBundle post = null;

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "SELECT * FROM dbo.product_bundles WHERE bundle_product_id = @bundle_product_id AND " 
            + "product_id = @product_id;";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@bundle_product_id", bundleProductId);
                cmd.Parameters.AddWithValue("@product_id", productId);

                // Create a reader
                SqlDataReader reader = null;

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Fill the reader with one row of data.
                    reader = cmd.ExecuteReader();

                    // Loop through the reader as long as there is something to read and add values
                    while (reader.Read())
                    {
                        post = new ProductBundle(reader);
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    // Call Close when done reading to avoid memory leakage.
                    if (reader != null)
                        reader.Close();
                }
            }
        }

        // Return the post
        return post;

    } // End of the GetOneById method
Beispiel #18
0
        public ActionResult Create(ProductBundleEditAdminViewModel viewModel, string createAndView)
        {
            StoreFront storeFront = CurrentStoreFrontOrThrow;
            bool       urlIsValid = GStoreDb.ValidateProductBundleUrlName(this, viewModel.UrlName, storeFront.StoreFrontId, storeFront.ClientId, null);

            if (urlIsValid && ModelState.IsValid)
            {
                try
                {
                    ProcessFileUploads(viewModel, storeFront);
                    ProductBundle productBundle = GStoreDb.CreateProductBundle(viewModel, storeFront, CurrentUserProfileOrThrow);
                    AddUserMessage("Product Bundle Created!", "Product Bundle '" + productBundle.Name.ToHtml() + "' [" + productBundle.ProductBundleId + "] was created successfully for Store Front '" + storeFront.CurrentConfig().Name.ToHtml() + "' [" + storeFront.StoreFrontId + "]", UserMessageType.Success);
                    if (!string.IsNullOrWhiteSpace(createAndView))
                    {
                        return(RedirectToAction("Details", new { id = productBundle.ProductBundleId, returnToFrontEnd = viewModel.ReturnToFrontEnd, tab = viewModel.ActiveTab }));
                    }
                    if (viewModel.ReturnToFrontEnd)
                    {
                        return(RedirectToAction("ViewBundleByName", "Catalog", new { area = "", urlName = viewModel.UrlName }));
                    }
                    if (storeFront.Authorization_IsAuthorized(CurrentUserProfileOrThrow, GStoreAction.Bundles_Manager))
                    {
                        return(RedirectToAction("Manager", new { ProductCategoryId = productBundle.ProductCategoryId }));
                    }
                    return(RedirectToAction("Index", "CatalogAdmin"));
                }
                catch (Exception ex)
                {
                    string errorMessage = "An error occurred while Creating Product Bundle '" + viewModel.Name + "' for Store Front '" + storeFront.CurrentConfig().Name.ToHtml() + "' [" + storeFront.StoreFrontId + "] \nError: " + ex.GetType().FullName;

                    if (CurrentUserProfileOrThrow.AspNetIdentityUserIsInRoleSystemAdmin())
                    {
                        errorMessage += " \nException.ToString(): " + ex.ToString();
                    }
                    AddUserMessage("Error Creating Product Bundle!", errorMessage.ToHtmlLines(), UserMessageType.Danger);
                    ModelState.AddModelError("Ajax", errorMessage);
                }
            }
            else
            {
                AddUserMessage("Create Product Bundle Error", "There was an error with your entry for new Product Bundle '" + viewModel.Name.ToHtml() + "' for Store Front '" + storeFront.CurrentConfig().Name.ToHtml() + "' [" + storeFront.StoreFrontId + "]. Please correct it below and save.", UserMessageType.Danger);
            }

            if (Request.HasFiles())
            {
                AddUserMessage("Files not uploaded", "You must correct the form values below and re-upload your files", UserMessageType.Danger);
            }

            viewModel.FillListsIfEmpty(storeFront.Client, storeFront);

            viewModel.IsCreatePage = true;
            ViewData.Add("ReturnToFrontEnd", viewModel.ReturnToFrontEnd);
            return(View("CreateOrEdit", viewModel));
        }
 public ProductBundleEditAdminViewModel(ProductBundle productBundle, UserProfile userProfile)
 {
     if (userProfile == null)
     {
         throw new ArgumentNullException("userProfile");
     }
     if (productBundle == null)
     {
         throw new ArgumentNullException("productBundle", "Product Bundle cannot be null");
     }
     LoadValues(userProfile, productBundle);
 }
Beispiel #20
0
        /// <summary>
        /// Renders a bundle partial to display the bundle in a list of bundles for the current category
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="bundle"></param>
        public static void RenderCatalogBundleForListPartial(this HtmlHelper <CatalogViewModel> htmlHelper, ProductBundle bundle)
        {
            CatalogViewModel viewModel = htmlHelper.ViewData.Model;

            ProductBundle oldValueProductBundle = htmlHelper.ViewData.Model.CurrentProductBundleOrNull;

            ViewDataDictionary <CatalogViewModel> newViewData = new ViewDataDictionary <CatalogViewModel>(htmlHelper.ViewData);

            newViewData.Model.CurrentProductBundleOrNull = bundle;

            string view = "_BundleForList_Partial";

            htmlHelper.RenderCatalogPartialHelper(view, newViewData);

            htmlHelper.ViewData.Model.CurrentProductBundleOrNull = oldValueProductBundle;
        }
Beispiel #21
0
        public HttpResponseMessage delete(Int32 id = 0, Int32 productId = 0)
        {
            // Create an error code variable
            Int32 errorCode = 0;

            // Delete the post
            errorCode = ProductBundle.DeleteOnId(id, productId);

            // Check if there is an error
            if (errorCode != 0)
            {
                return(Request.CreateResponse <string>(HttpStatusCode.Conflict, "Foreign key constraint"));
            }

            // Return the success response
            return(Request.CreateResponse <string>(HttpStatusCode.OK, "The delete was successful"));
        } // End of the delete method
 public ProductBundleEditAdminViewModel(ProductBundle productBundle, UserProfile userProfile, string activeTab, bool isCreatePage = false, bool isEditPage = false, bool isDetailsPage = false, bool isDeletePage = false)
 {
     if (userProfile == null)
     {
         throw new ArgumentNullException("userProfile");
     }
     if (productBundle == null)
     {
         throw new ArgumentNullException("productBundle", "Product Bundle cannot be null");
     }
     this.IsCreatePage  = isCreatePage;
     this.IsEditPage    = isEditPage;
     this.IsDetailsPage = isDetailsPage;
     this.IsDeletePage  = isDeletePage;
     this.ActiveTab     = activeTab;
     LoadValues(userProfile, productBundle);
 }
Beispiel #23
0
        public ActionResult DesktopGroupsAddEx()
        {
            using (log4net.NDC.Push(Guid.NewGuid().ToString()))
            {
                logger.Debug("Request for Create DesktopGroups page with billing");
                LoginViewModel clientId =
                    LoginViewModel.JsonDeserialize(((FormsIdentity)User.Identity).Ticket);
                ViewBag.Domain = clientId.DomainName;
                // ViewBag offers typeless mechanism of exposing objects to the view page
                ViewBag.Templates = new List <Template>();

                // Templates come from AJAX call
                //                ViewBag.Templates = Template.GetTemplates(CloudStackClient);
                ViewBag.DesktopTypes     = Catalog.DesktopTypeList;
                ViewBag.ComputeOfferings = XenDesktopInventoryItem.GetServiceOfferingList();
                ViewBag.AvailableUsers   = Catalog.GetActiveDirectoryUsers("*");

                // ProductBundle list comes from CPBM
                if (DT2.Properties.Settings.Default.TestDisableProductBundleGet)
                {
                    // Dev scaffolding:
                    dynamic response = JsonConvert.DeserializeObject(ProductBundle.SampleCatalogJson2);
                    ViewBag.Bundles = DT2.Models.ProductBundle.ParseJson(response);
                }
                else
                {
                    var bundles = ProductBundle.GetBundles();

                    // verify that each bundle has a monthly and one time charge.
                    foreach (var item in bundles)
                    {
                        if (item.RateCardCharges.Count < 2)
                        {
                            item.RateCardCharges.Add("0.00");
                        }
                        if (item.RateCardCharges.Count < 2)
                        {
                            item.RateCardCharges.Add("0.00");
                        }
                    }
                    ViewBag.Bundles = bundles;
                }
                return(View());
            }
        }
Beispiel #24
0
        public ActionResult RemoveBundle(string id)
        {
            if (!CheckAccess())
            {
                return(BounceToLogin());
            }

            StoreFront storeFront = CurrentStoreFrontOrThrow;
            Cart       cart       = storeFront.GetCart(Session.SessionID, CurrentUserProfileOrNull);

            if (string.IsNullOrWhiteSpace(id))
            {
                AddUserMessage("Remove from Cart Error", "Bundle not found. Please try again.", UserMessageType.Danger);
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Cart, UserActionActionEnum.Cart_RemoveFromCart, "Bad Url", false, cartId: (cart == null ? (int?)null : cart.CartId), productBundleUrlName: id);
                return(RedirectToAction("Index"));
            }

            ProductBundle productBundle = storeFront.ProductBundles.AsQueryable().CanAddToCart(storeFront).SingleOrDefault(b => b.UrlName.ToLower() == id.ToLower());

            if (productBundle == null)
            {
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Cart, UserActionActionEnum.Cart_RemoveFromCart, "Bundle not found in catalog", false, cartId: (cart == null ? (int?)null : cart.CartId), productBundleUrlName: id);
                AddUserMessage("Remove From Cart Error", "Bundle '" + id.ToHtml() + "' could not be found. Please try again.", UserMessageType.Danger);
                return(RedirectToAction("Index"));
            }


            CartBundle cartBundleExisting = cart.FindBundleInCart(productBundle);

            if (cartBundleExisting == null)
            {
                AddUserMessage("Bundle Not Found in Cart", "'" + id.ToHtml() + "' was already removed from your cart.", UserMessageType.Success);
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Cart, UserActionActionEnum.Cart_RemoveFromCart, "Bundle not found in cart.", false, cartId: (cart == null ? (int?)null : cart.CartId), productBundleUrlName: id);
                return(RedirectToAction("Index"));
            }

            bool result = cartBundleExisting.RemoveFromCart(GStoreDb);

            cart.CancelCheckout(GStoreDb);

            AddUserMessage("Bundle Removed from Cart", "'" + productBundle.Name.ToHtml() + "' was removed from your shopping cart.", UserMessageType.Success);
            GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Cart, UserActionActionEnum.Cart_RemoveFromCart, "Success", true, cartId: (cart == null ? (int?)null : cart.CartId), productBundleUrlName: id);

            return(RedirectToPreviousPageOrCartIndex());
        }
Beispiel #25
0
        /// <summary>
        /// Returns true if store front and client (parent record) are both active
        /// </summary>
        /// <param name="storeFront"></param>
        /// <returns></returns>
        public static bool IsActiveBubble(this ProductBundle productBundle)
        {
            if (productBundle == null || !productBundle.IsActiveDirect())
            {
                return(false);
            }

            if (productBundle.Client == null || !productBundle.Client.IsActiveDirect())
            {
                return(false);
            }

            if (productBundle.Category == null)
            {
                return(false);
            }
            return(productBundle.Category.IsActiveBubble());
        }
Beispiel #26
0
        protected ActionResult ViewBundle(ProductBundle bundle)
        {
            if (bundle == null)
            {
                throw new ApplicationException("Product Bundle is null, be sure bundle is set before calling ViewBundle");
            }
            /// get current catalog item
            CatalogViewModel model = new CatalogViewModel(CurrentStoreFrontOrThrow, CurrentStoreFrontOrThrow.CategoryTreeWhereActiveForCatalogByName(User.IsRegistered()), CurrentStoreFrontConfigOrThrow.CatalogPageInitialLevels, bundle.Category, null, bundle, null);

            if (bundle.Theme != null)
            {
                ViewData.Theme(bundle.Theme);
            }
            else if (bundle.Category.Theme != null)
            {
                ViewData.Theme(bundle.Category.Theme);
            }
            return(View("ViewBundle", this.LayoutNameForCatalog, model));
        }
Beispiel #27
0
        public ActionResult UpdateBundleQty(string id, int?quantity)
        {
            if (!CheckAccess())
            {
                return(BounceToLogin());
            }
            int newQuantity = 1;

            if (quantity.HasValue && quantity.Value > 0 && quantity.Value < 10000)
            {
                newQuantity = quantity.Value;
            }
            if (string.IsNullOrWhiteSpace(id))
            {
                AddUserMessage("Update Quantity Error", "Item '' not found. Please try again.", UserMessageType.Danger);
                return(RedirectToAction("Index"));
            }

            StoreFront storeFront = CurrentStoreFrontOrThrow;

            ProductBundle productBundle = storeFront.ProductBundles.AsQueryable().CanAddToCart(storeFront).SingleOrDefault(p => p.UrlName.ToLower() == id.ToLower());

            if (productBundle == null)
            {
                AddUserMessage("Update Quantity Error", "Bundle '" + id.ToHtml() + "' cannot be added to your cart. Please try again.", UserMessageType.Danger);
                return(RedirectToAction("Index"));
            }

            Cart cart = CurrentStoreFrontOrThrow.GetCart(Session.SessionID, CurrentUserProfileOrNull);

            CartBundle cartBundleExisting = cart.FindBundleInCart(productBundle);

            if (cartBundleExisting == null)
            {
                AddUserMessage("Update Quantity Error", "Bundle '" + id.ToHtml() + "' is not in your cart. Please try again.", UserMessageType.Success);
                return(RedirectToAction("Index"));
            }

            cartBundleExisting.UpdateQuantityAndSave(GStoreDb, newQuantity, this);
            cart.CancelCheckout(GStoreDb);

            return(RedirectToPreviousPageOrCartIndex());
        }
Beispiel #28
0
        public ActionResult Create(int?id, bool returnToFrontEnd = false, string Tab = "")
        {
            ProductBundle productBundle = GStoreDb.ProductBundles.Create();

            productBundle.SetDefaultsForNew(CurrentStoreFrontOrThrow);
            if (id.HasValue)
            {
                ProductCategory parentProductCategory = CurrentStoreFrontOrThrow.ProductCategories.SingleOrDefault(pc => pc.ProductCategoryId == id.Value);
                if (parentProductCategory != null)
                {
                    productBundle.Category          = parentProductCategory;
                    productBundle.ProductCategoryId = parentProductCategory.ProductCategoryId;
                }
            }

            ProductBundleEditAdminViewModel viewModel = new ProductBundleEditAdminViewModel(productBundle, CurrentUserProfileOrThrow, Tab, isCreatePage: true);

            viewModel.ReturnToFrontEnd = returnToFrontEnd;
            ViewData.Add("ReturnToFrontEnd", returnToFrontEnd);
            return(View("CreateOrEdit", viewModel));
        }
Beispiel #29
0
        public ActionResult ViewBundleByName(string urlName)
        {
            if (string.IsNullOrWhiteSpace(urlName))
            {
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Catalog, UserActionActionEnum.Catalog_ViewBundle, "Bad Url", false);
                return(Index());
            }

            ProductBundle bundle = CurrentStoreFrontOrThrow.ProductBundles.AsQueryable().Where(prod => prod.UrlName.ToLower() == urlName.ToLower()).WhereIsActive().SingleOrDefault();

            if (bundle == null)
            {
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Catalog, UserActionActionEnum.Catalog_ViewBundleNotFound, urlName, false, productBundleUrlName: urlName);
                return(BundleNotFound(urlName));
            }

            GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Catalog, UserActionActionEnum.Catalog_ViewBundle, urlName, true, productBundleUrlName: urlName);

            SetMetaTags(bundle);

            return(ViewBundle(bundle));
        }
Beispiel #30
0
    } // End of the constructor

    #endregion

    #region Insert methods

    /// <summary>
    /// Add one product bundle
    /// </summary>
    /// <param name="post">A reference to a product bundle post</param>
    public static void Add(ProductBundle post)
    {

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "INSERT INTO dbo.product_bundles (bundle_product_id, product_id, quantity) "
            + "VALUES (@bundle_product_id, @product_id, @quantity);";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@bundle_product_id", post.bundle_product_id);
                cmd.Parameters.AddWithValue("@product_id", post.product_id);
                cmd.Parameters.AddWithValue("@quantity", post.quantity);

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases
                try
                {
                    // Open the connection
                    cn.Open();

                    // Execute the insert
                    cmd.ExecuteNonQuery();

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

    } // End of the Add method
Beispiel #31
0
    } // End of the constructor

    #endregion

    #region Insert methods

    /// <summary>
    /// Add one product bundle
    /// </summary>
    /// <param name="post">A reference to a product bundle post</param>
    public static void Add(ProductBundle post)
    {

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "INSERT INTO dbo.product_bundles (bundle_product_id, product_id, quantity) "
            + "VALUES (@bundle_product_id, @product_id, @quantity);";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@bundle_product_id", post.bundle_product_id);
                cmd.Parameters.AddWithValue("@product_id", post.product_id);
                cmd.Parameters.AddWithValue("@quantity", post.quantity);

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases
                try
                {
                    // Open the connection
                    cn.Open();

                    // Execute the insert
                    cmd.ExecuteNonQuery();

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

    } // End of the Add method
Beispiel #32
0
    } // End of the Update method

    #endregion

    #region Get methods

    /// <summary>
    /// Get one product bundle on id
    /// </summary>
    /// <param name="bundleProductId">A bundle product id</param>
    /// <param name="productId">An product id</param>
    /// <returns>A reference to a product bundle post</returns>
    public static ProductBundle GetOneById(Int32 bundleProductId, Int32 productId)
    {
        // Create the post to return
        ProductBundle post = null;

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "SELECT * FROM dbo.product_bundles WHERE bundle_product_id = @bundle_product_id AND " 
            + "product_id = @product_id;";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@bundle_product_id", bundleProductId);
                cmd.Parameters.AddWithValue("@product_id", productId);

                // Create a reader
                SqlDataReader reader = null;

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Fill the reader with one row of data.
                    reader = cmd.ExecuteReader();

                    // Loop through the reader as long as there is something to read and add values
                    while (reader.Read())
                    {
                        post = new ProductBundle(reader);
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    // Call Close when done reading to avoid memory leakage.
                    if (reader != null)
                        reader.Close();
                }
            }
        }

        // Return the post
        return post;

    } // End of the GetOneById method
Beispiel #33
0
        public ActionResult AddBundle(string id, int?qty, bool?buyNow)
        {
            //remove old item and add new item
            if (!CheckAccess())
            {
                return(BounceToLogin());
            }

            int quantity = 1;

            if (qty.HasValue && qty.Value > 0 && qty.Value < 10000)
            {
                quantity = qty.Value;
            }

            StoreFront storeFront = CurrentStoreFrontOrThrow;
            Cart       cart       = storeFront.GetCart(Session.SessionID, CurrentUserProfileOrNull);

            if (string.IsNullOrWhiteSpace(id))
            {
                AddUserMessage("Add to Cart Error", "Item not found. Please try again.", UserMessageType.Danger);
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Cart, UserActionActionEnum.Cart_AddToCartFailure, "Bad Url", false, cartId: (cart == null ? (int?)null : cart.CartId), productBundleUrlName: id);
                return(RedirectToAction("Index"));
            }

            ProductBundle productBundle = storeFront.ProductBundles.AsQueryable().CanAddToCart(storeFront).SingleOrDefault(p => p.UrlName.ToLower() == id.ToLower());

            if (productBundle == null)
            {
                AddUserMessage("Add to Cart Error", "Item '" + id.ToHtml() + "' could not be found to add to your cart. Please try again.", UserMessageType.Danger);
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Cart, UserActionActionEnum.Cart_AddToCartFailure, "Item Not Found", false, cartId: (cart == null ? (int?)null : cart.CartId), productBundleUrlName: id);
                return(RedirectToPreviousPageOrCartIndex());
            }

            if (!productBundle.AvailableForPurchase)
            {
                AddUserMessage("Add to Cart Error", "Item '" + id.ToHtml() + "' is not available for purchase online. Please try again.", UserMessageType.Danger);
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Cart, UserActionActionEnum.Cart_AddToCartFailure, "Product not available for purchase", false, cartId: (cart == null ? (int?)null : cart.CartId), productBundleUrlName: id);
                return(RedirectToPreviousPageOrCartIndex());
            }

            //if item with same variant is already added, increment the quantity
            if (!CurrentStoreFrontConfigOrThrow.UseShoppingCart)
            {
                if (cart != null && cart.CartItems.Count > 0)
                {
                    //if storefront is not set to use a cart, dump previous items and start with a new cart.
                    CurrentStoreFrontOrThrow.DumpCartNoSave(GStoreDb, cart);
                    GStoreDb.SaveChanges();
                    cart = storeFront.GetCart(Session.SessionID, CurrentUserProfileOrNull);
                }
            }

            CartBundle cartBundleExisting = cart.FindBundleInCart(productBundle);

            if (cartBundleExisting != null)
            {
                int newQty = cartBundleExisting.Quantity + quantity;
                cartBundleExisting = cartBundleExisting.UpdateQuantityAndSave(GStoreDb, newQty, this);

                if (newQty <= cartBundleExisting.ProductBundle.MaxQuantityPerOrder)
                {
                    AddUserMessage("Bundle Added to Cart", "'" + cartBundleExisting.ProductBundle.Name.ToHtml() + "' was added to your cart. Now you have " + cartBundleExisting.Quantity + " of them in your cart.<br/><a href=" + Url.Action("Index", "Cart") + ">Click here to view your cart.</a>", UserMessageType.Success);
                    cart.CancelCheckout(GStoreDb);
                }
                else
                {
                    //quantity is over max, user messages are already set
                }
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Cart, UserActionActionEnum.Cart_AddToCartSuccess, "Added to Existing", true, cartId: cart.CartId, productBundleUrlName: id);

                if (buyNow ?? false)
                {
                    return(RedirectToAction("Index", "Checkout"));
                }
                return(RedirectToPreviousPageOrCartIndex());
            }

            CartBundle cartBundle = cart.AddBundleToCart(productBundle, quantity, this);

            AddUserMessage("Bundle Added to Cart", "'" + cartBundle.ProductBundle.Name.ToHtml() + "' is now in your shopping cart.<br/><a href=" + Url.Action("Index", "Cart") + ">Click here to view your cart.</a>", UserMessageType.Success);

            GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Cart, UserActionActionEnum.Cart_AddToCartSuccess, "Added", true, cartId: cartBundle.CartId, productBundleUrlName: id);

            cart.CancelCheckout(GStoreDb);

            if (buyNow.HasValue && buyNow.Value)
            {
                return(RedirectToAction("Index", "Checkout"));
            }

            return(RedirectToPreviousPageOrCartIndex());
        }
        public ActionResult add_bundle_item(FormCollection collection)
        {
            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();
            ViewBag.CurrentDomain = currentDomain;

            // Get query parameters
            string returnUrl = collection["returnUrl"];
            ViewBag.QueryParams = new QueryParams(returnUrl);

            // Check if the administrator is authorized
            if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true)
            {
                ViewBag.AdminSession = true;
            }
            else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true)
            {
                ViewBag.AdminSession = true;
                ViewBag.AdminErrorCode = 1;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }
            else
            {
                // Redirect the user to the start page
                return RedirectToAction("index", "admin_login");
            }

            // Get form data
            Int32 bundleProductId = Convert.ToInt32(collection["hiddenBundleProductId"]);
            Int32 productId = Convert.ToInt32(collection["hiddenProductId"]);
            decimal quantity = 0;
            decimal.TryParse(collection["quantity"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out quantity);
            quantity = AnnytabDataValidation.TruncateDecimal(quantity, 0M, 999999.99M);

            // Check if we can find a saved bundle post
            ProductBundle productBundle = ProductBundle.GetOneById(bundleProductId, productId);

            // Make sure that the product bundle does not exist already
            if (productBundle == null)
            {
                // Add a product bundle
                productBundle = new ProductBundle();
                productBundle.bundle_product_id = bundleProductId;
                productBundle.product_id = productId;
                productBundle.quantity = quantity;
                ProductBundle.Add(productBundle);
            }
            else
            {
                // Update a product bundle
                productBundle.quantity = quantity;
                ProductBundle.Update(productBundle);
            }

            // Return the bundle structure view
            return RedirectToAction("bundle_structure", new { id = bundleProductId, returnUrl = returnUrl });

        } // End of the add_bundle_item method
 public void UpdateProductBundle(ProductBundle productBundle)
 {
     this.ProductBundle = productBundle;
     this.Category      = productBundle.Category;
 }