/// <summary>
 /// Handles the Click event of the btn_ProdToPool control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
 /// Erstellt von Veit Berg, am 27.01.16
 private void btn_ProdToPool_Click(object sender, EventArgs e)
 {
     try{
     DataGridViewRow row = dataGridView_ProjProd.SelectedRows[0];
     int ProdId = (int)row.Cells[0].Value;
     int index = dataGridView_ProjProd.CurrentCell.RowIndex;
     ProjProds.RemoveAt(index);
     using (ProductController prodCont = new ProductController())
     {
         Product addProd = prodCont.GetProductById(ProdId);
         AllProds.Add(addProd);
         projProdCont.ChangeAllocationOfProjectProducstListInDb(ProjectId, ProjProds);
     }
     dataGridView_prodAvail .DataSource = null;
     dataGridView_prodAvail.DataSource = AllProds;
     dataGridView_ProjProd.DataSource = null;
     dataGridView_ProjProd.DataSource = ProjProds;
     dataGridView_ProjProd.Columns.Remove("Project_Id");
     dataGridView_ProjProd.Columns.Remove("Product");
     dataGridView_ProjProd.Columns.Remove("Project");
     dataGridView_ProjProd.Columns[1].Width = 200;
     }
     catch (Exception x)
     {
         MessageBox.Show(x.Message);
     }
 }
Example #2
0
        public IEnumerable<BasketItemModel> GetProductListByBasketID(int basketID)
        {
            UserOrderController userOrderController = new UserOrderController();
            OrderStatusController orderStatusController = new OrderStatusController();
            OrderStateController orderStateController = new OrderStateController();
            ProductController productController = new ProductController();

            List<BasketItemModel> basketDetails = new List<BasketItemModel>();

            foreach (UserOrder userOrder in userOrderController.GetAllUserOrders())
            {
                if (basketID == userOrder.OrderBasketID)
                {
                    basketDetails.Add(new BasketItemModel()
                    {
                        BasketID = userOrder.OrderBasketID,
                        CurierPassingDate = orderStatusController.GetById(userOrder.OrderStatusID).CourierPassingDate,
                        DeliveryDate = orderStatusController.GetById(userOrder.OrderStatusID).DeliveryDate,
                        OrderState = orderStateController.GetById(orderStatusController.GetById(userOrder.OrderStatusID).OrderStateID).Name,
                        OrderStatusID = orderStatusController.GetById(userOrder.OrderStatusID).ID,
                        ProductName = productController.GetById(userOrder.ProductID).Name,
                        ProductPrice = productController.GetById(userOrder.ProductID).Price,
                        OrderID = userOrder.ID
                    });
                }
            }

            return basketDetails;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ProjectExporter"/> class.
        /// </summary>
        /// <param name="projectIdToExport">The project identifier to export.</param>
        /// <param name="exportDirectoryPath">The export file path.</param>
        /// Erstellt von Joshua Frey, am 13.01.2016
        public ProjectExporter(int projectIdToExport, string exportDirectoryPath)
        {
            // initialize db controller
            ExportProjectController = new ProjectController();
            ExportCriterionController = new CriterionController();
            ExportProductController = new ProductController();
            ExportProjectCriterionController = new ProjectCriterionController();
            ExportProjectProductController = new ProjectProductController();
            ExportFulfillmentController = new FulfillmentController();

            this.ExportFilePaths = new List<string>();

            ProjectId = projectIdToExport;
            ProjectName = ExportProjectController.GetProjectById(projectIdToExport).Name;
            Timestamp = CommonMethods.GetTimestamp();

            ExportFilePath = exportDirectoryPath;

            FileBaseName = String.Format(@"{0}\{1}_Project_{2}", ExportFilePath, Timestamp, ProjectName);

            string logFilePath = this.FileBaseName + ".log";
            this.ExportFilePaths.Add(logFilePath);

            // Create Logfile
            this.ArchiveLogWriter = new LogWriter(logFilePath, "Archivierungslog");
        }
        public void Can_Filter_Products()
        {
            //Arrange
            //Mock Repository
            Mock<IProductsRepository> mockRepo = new Mock<IProductsRepository>();
            mockRepo.Setup(m => m.Products).Returns(new Product[]{
                new Product {ProductID = 1, Name = "P1", Category = "Cat1"},
                new Product {ProductID = 1, Name = "P2", Category = "Cat2"},
                new Product {ProductID = 1, Name = "P3", Category = "Cat1"},
                new Product {ProductID = 1, Name = "P4", Category = "Cat2"},
                new Product {ProductID = 1, Name = "P5", Category = "Cat3"},
            });

            //Arrange
            //Controller
            ProductController controller = new ProductController(mockRepo.Object);
            controller.PageSize = 3;

            //Action
            Product[] result = ((ProductListViewModel)controller.List("Cat2", 1).Model).Products.ToArray();

            //Assert
            Assert.AreEqual(result.Length, 2);
            Assert.IsTrue(result[0].Name == "P2" && result[0].Category == "Cat2");
            Assert.IsTrue(result[1].Name == "P4" && result[1].Category == "Cat2");
        }
 public void WhenICallApiLayerToGetProductById(int id)
 {
     var products = ScenarioContext.Current.Get<List<Product>>();
     var api = new ProductController(products);
     var product = api.Get(id);
     ScenarioContext.Current.Set(product, "Product");
 }
Example #6
0
    //    void Update() {
    //        Debug.Log(animation[animationName].time.ToString());
    //    }
    void Awake()
    {
        NGUIProductSceneViewer.OnProductViewChanged += OnProductViewChanged;
        NGUIProductSceneViewer.OnBackToLoginScene += OnBackToLoginScene;
        ProductController.OnCarPurchased += OnCarPurchased;
        ProductController.OnFailedToPurchase += OnFailedToPurchase;

        productController = GameObject.FindObjectOfType(typeof(ProductController)) as ProductController;
    }
Example #7
0
    void Awake()
    {
        NGUIProductSceneViewer.OnTalentInfoOpened += OnTalentInfoOpened;
        ProductController.OnTalentOpened += OnTalentOpened;
        ProductController.OnCarPurchased += OnCarPurchased;
        ProductController.OnFailedToPurchase += OnFailedToPurchase;

        productController = GameObject.FindObjectOfType(typeof(ProductController)) as ProductController;
    }
        public Product_Update_View(Produktverwaltung_View parentView, int productId)
        {
            this.parentView = parentView;
            using (ProductController ProdUpdView = new ProductController())
            {
                this.Product = ProdUpdView.GetProductById(productId);
            }

            InitializeComponent();
        }
 public async void GivenICallApiLayerToGetProductByIdAsynchronously(int id1, int id2)
 {
     var products = ScenarioContext.Current.Get<List<Product>>();
     var api = new ProductController(products);
     var tasks = new Task<Product>[]
     {
         api.GetAsync(id1),
         api.GetAsync(id2)
     };
     Task.WaitAll(tasks);
     ScenarioContext.Current.Set(tasks[0].Result, "Product1");
     ScenarioContext.Current.Set(tasks[1].Result, "Product2");
 }
        //Konstruktor - Werden ProjectId und ProductId als Parameter übergeben
        public FulfillmentForEachProductPrinter(int projectId, int productId)
        {
            this.ProjCritContr = new ProjectCriterionController();
             ProjectController projCont = new ProjectController();
             this.Project = projCont.GetProjectById(projectId);

             this.ProjProduct = new ProductController();
             ProductController projProdController = new ProductController();
             this.Product = projProdController.GetProductById(productId);

             this.FulFillContr = new FulfillmentController();
             FulfillmentController fulCont = new FulfillmentController();
             this.FulfillmentForEachProduct = fulCont.GetAllFulfillmentsForSingleProduct(projectId, productId);
        }
Example #11
0
        public void Should_add_the_product_list_to_view_data()
        {
            var products = new List<Product> {new Product {Name = "Wii"}};

            var repository = Fake<IProductRepository>();
            repository.Stub(rep => rep.FindAll()).Return(products);
            //stub out rep.FindAll() to return our products
            var controller = new ProductController(repository);

            var result = controller.Index();

            //result.ViewName.ShouldEqual(string.Empty);
            result.ViewData.Model.ShouldEqual(products);
        }
 public ProductControllerTests()
 {
     _documentService = A.Fake<IDocumentService>();
     _productService = A.Fake<IProductService>();
     _categoryService = A.Fake<ICategoryService>();
     _productOptionManager = A.Fake<IProductOptionManager>();
     _fileService = A.Fake<IFileAdminService>();
     _productOptionManagementService = A.Fake<IProductOptionManagementService>();
     _siteSettings = new SiteSettings {DefaultPageSize = 10};
     _uniquePageService = A.Fake<IUniquePageService>();
     _productSearch = new ProductSearch();
     _eTagAdminService = A.Fake<IETagAdminService>();
     A.CallTo(() => _uniquePageService.GetUniquePage<ProductSearch>()).Returns(_productSearch);
     _productController = new ProductController(_productService, _documentService, _categoryService,
         _productOptionManager,
         _fileService, _productOptionManagementService, _siteSettings, _uniquePageService, _eTagAdminService);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ProjectImporter"/> class.
        /// </summary>
        /// <param name="archiveFilePath">The archive file path.</param>
        /// Erstellt von Joshua Frey, am 13.01.2016
        public ProjectImporter(string archiveFilePath)
        {
            // initialize db controller
            ImportProjectController = new ProjectController();
            ImportCriterionController = new CriterionController();
            ImportProductController = new ProductController();
            ImportProjectCriterionController = new ProjectCriterionController();
            ImportProjectProductController = new ProjectProductController();
            ImportFulfillmentController = new FulfillmentController();
            this.ZipArchiveFilePath = archiveFilePath;

            this.ImportFilesDirectory = CreateImportDirectory();

            // Create Logfile
            string logFilePath = this.ImportFilesDirectory + @"\Import.log";
            this.ImportLogWriter = new LogWriter(logFilePath, "Import Log");
        }
 /// <summary>
 /// refreshs dropdown menue
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
 /// Erstellt von Veit Berg, am 27.01.16
 public void RefreshDropdown()
 {
     try
     {
         using (ProductController ProdRefr = new ProductController())
         {
             List<Product> ProdList = ProdRefr.GetAllProductsFromDb();
             var bindingList = new BindingList<Product>(ProdList);
             var source = new BindingSource(bindingList, null);
             comboBox_ProdChoose.DataSource = ProdList;
             comboBox_ProdChoose.DisplayMember = "Name";
             comboBox_ProdChoose.ValueMember = "Product_ID";
         }
     }
     catch (Exception x)
     {
         MessageBox.Show(x.Message);
     }
 }
        /// <summary>
        /// Handles the Click event of the btn_ProdUpdate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        /// Erstellt von Veit Berg, am 27.01.16
        private void btn_ProdUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                using (ProductController prodUpdate = new ProductController())
                {
                    Product prodNew = prodUpdate.GetProductById(Product.Product_Id);
                    prodNew.Product_Id = this.Product.Product_Id;
                    prodNew.Name = textBox_ProdNameUpdate.Text;
                    prodNew.Producer = textBox_ProdManuUpdate.Text;

                    double check;
                    if (CommonMethods.CheckIfForbiddenDelimiterInDb(prodNew.Name) ||
                        CommonMethods.CheckIfForbiddenDelimiterInDb(prodNew.Producer))
                    {
                        MessageBox.Show(CommonMethods.MessageForbiddenDelimiterWasFoundInText());
                    }
                    else
                    {
                        if (Double.TryParse(textBox_ProdPrizeUpdate.Text, out check))
                        {
                            prodNew.Price = Convert.ToDouble(textBox_ProdPrizeUpdate.Text);
                            prodUpdate.UpdateProductInDb(prodNew);
                            this.Close();
                        }
                        else
                        {
                            MessageBox.Show("Der Preis darf nur aus Zahlen bestehen!");
                        }
                    }
                }
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message);
            }
        }
        public void Can_Paginate()
        {
            //Arrange
            Mock<IProductsRepository> repo = new Mock<IProductsRepository>();
            repo.Setup(m => m.Products).Returns(new Product[]
                {
                    new Product {ProductID = 1, Name = "P1"},
                    new Product {ProductID = 2, Name = "P2"},
                    new Product {ProductID = 3, Name = "P3"},
                    new Product {ProductID = 4, Name = "P4"},
                    new Product {ProductID = 5, Name = "P5"}
                });

            ProductController controller = new ProductController(repo.Object);
            controller.PageSize = 3;

            //Act
            //IEnumerable<Product> result = (IEnumerable<Product>)controller.List(2).Model;
            ProductListViewModel result = (ProductListViewModel)controller.List(null, 2).Model;

            //Assert
            Product[] prodArray = result.Products.ToArray();
            Assert.IsTrue(prodArray.Length == 2);
            Assert.AreEqual(prodArray[0].Name, "P4");
            Assert.AreEqual(prodArray[1].Name, "P5");
        }
Example #17
0
        public void LoadData()
        {
            int ID = Request.QueryString["id"].ToInt(0);

            if (ID > 0)
            {
                string username = Request.Cookies["usernameLoginSystem"].Value;
                var    acc      = AccountController.GetByUsername(username);
                if (acc != null)
                {
                    int agentIDReceive = Convert.ToInt32(acc.AgentID);
                    var mp             = MoveProController.GetByIDAndAgentIDReceive(ID, agentIDReceive);
                    if (mp != null)
                    {
                        ViewState["ID"] = ID;
                        int    agentIDSend      = Convert.ToInt32(mp.AgentIDSend);
                        string agentSendname    = "";
                        string agentReceivename = "";

                        var agentSend = AgentController.GetByID(agentIDSend);
                        if (agentSend != null)
                        {
                            agentSendname = agentSend.AgentName;
                        }
                        var agentReceive = AgentController.GetByID(agentIDReceive);
                        if (agentReceive != null)
                        {
                            agentReceivename = agentReceive.AgentName;
                        }
                        ltrAgentReceive.Text = agentReceivename;
                        ltrAgentSend.Text    = agentSendname;



                        int mpStatus = Convert.ToInt32(mp.Status);
                        ltrNote.Text = mp.Note;

                        if (mpStatus < 3)
                        {
                            ltrbutton1.Text = "<a href=\"javascript:;\" class=\"btn primary-btn fw-btn not-fullwidth\" onclick=\"inProduct()\">Cập nhật</a>";
                            ltrbutton2.Text = "<div class=\"float-right\"><a href=\"javascript:;\" class=\"btn primary-btn fw-btn not-fullwidth\" onclick=\"inProduct()\">Cập nhật</a></div>";
                        }
                        #region LoadDDL
                        //Lấy trạng thái
                        StringBuilder htmlStatus = new StringBuilder();
                        htmlStatus.Append("<select id=\"moveProStatus\" class=\"form-control\" style=\"width: 20%; display: inline-block\">");
                        if (mpStatus == 2)
                        {
                            htmlStatus.Append("<option value=\"2\" selected>Đã chuyển</option>");
                            htmlStatus.Append("<option value=\"3\">Đã hoàn tất</option>");
                        }
                        else if (mpStatus == 3)
                        {
                            htmlStatus.Append("<option value=\"2\">Đã chuyển</option>");
                            htmlStatus.Append("<option value=\"3\" selected>Đã hoàn tất</option>");
                        }
                        htmlStatus.Append("</select>");
                        ltrMoProStatus.Text = htmlStatus.ToString();

                        //Lấy nhà cung cấp
                        //var supplier = SupplierController.GetAllWithIsHidden(false);
                        //StringBuilder htmlSupplier = new StringBuilder();
                        //htmlSupplier.Append("<select id=\"supplierList\" class=\"form-control\" style=\"width: 20%; float: left; margin-right: 10px\">");
                        //htmlSupplier.Append("<option value=\"0\">Tất cả nhà cung cấp</option>");
                        //if (supplier.Count > 0)
                        //{
                        //    foreach (var s in supplier)
                        //    {
                        //        htmlSupplier.Append("<option value=\"" + s.ID + "\">" + s.SupplierName + "</option>");
                        //    }
                        //}
                        //htmlSupplier.Append("</select>");
                        //ltrSupplier.Text = htmlSupplier.ToString();
                        #endregion
                        #region Lấy danh sách sản phẩm
                        var    mpDetail = MoveProDetailController.GetByMoveProID(ID);
                        string html     = "";
                        if (mpDetail.Count > 0)
                        {
                            string listSKU = "";
                            foreach (var item in mpDetail)
                            {
                                listSKU += item.SKU + "|";
                                int ProductType       = Convert.ToInt32(item.ProductType);
                                int ProductID         = Convert.ToInt32(item.ProductID);
                                int ProductVariableID = Convert.ToInt32(item.ProductVariableID);

                                string SKU                        = item.SKU;
                                double QuantityInstock            = 0;
                                string ProductImageOrigin         = "";
                                string ProductVariable            = "";
                                string ProductName                = "";
                                int    PID                        = 0;
                                string ProductVariableName        = "";
                                string ProductVariableValue       = "";
                                string ProductVariableSave        = "";
                                double QuantityMainInstock        = 0;
                                string ProductImage               = "";
                                string QuantityMainInstockString  = "";
                                string QuantityInstockString      = "";
                                string productVariableDescription = item.ProductVariableDescription;
                                string SupplierName               = item.SupplierName;
                                if (ProductType == 1)
                                {
                                    PID = ProductID;
                                    var product = ProductController.GetBySKU(SKU);
                                    if (product != null)
                                    {
                                        double total = PJUtils.TotalProductQuantityInstock(agentIDSend, SKU);

                                        string variablename  = "";
                                        string variablevalue = "";
                                        string variable      = "";

                                        double mainstock = PJUtils.TotalProductQuantityInstock(1, SKU);

                                        QuantityInstock       = total;
                                        QuantityInstockString = string.Format("{0:N0}", total);

                                        var img = ProductImageController.GetFirstByProductID(product.ID);
                                        if (img != null)
                                        {
                                            ProductImage       = "<img src=\"" + Thumbnail.getURL(img.ProductImage, Thumbnail.Size.Small) + "\" alt=\"\" style=\"width: 50px\"  />";
                                            ProductImageOrigin = Thumbnail.getURL(img.ProductImage, Thumbnail.Size.Small);
                                        }
                                        else
                                        {
                                            ProductImage       = "";
                                            ProductImageOrigin = "";
                                        }


                                        ProductVariable = variable;
                                        ProductName     = product.ProductTitle;

                                        QuantityMainInstock       = mainstock;
                                        QuantityMainInstockString = string.Format("{0:N0}", mainstock);
                                        ProductVariableSave       = item.ProductVariableDescription;

                                        ProductVariableName  = variablename;
                                        ProductVariableValue = variablevalue;
                                    }
                                }
                                else
                                {
                                    PID = ProductVariableID;
                                    var productvariable = ProductVariableController.GetBySKU(SKU);
                                    if (productvariable != null)
                                    {
                                        SKU = productvariable.SKU.Trim().ToUpper();
                                        double total = PJUtils.TotalProductQuantityInstock(agentIDSend, SKU);


                                        string variablename  = "";
                                        string variablevalue = "";
                                        string variable      = "";

                                        string[] vs = productVariableDescription.Split('|');
                                        if (vs.Length - 1 > 0)
                                        {
                                            for (int i = 0; i < vs.Length - 1; i++)
                                            {
                                                string[] items = vs[i].Split(':');
                                                variable      += items[0] + ":" + items[1] + "<br/>";
                                                variablename  += items[0] + "|";
                                                variablevalue += items[1] + "|";
                                            }
                                        }

                                        double mainstock = PJUtils.TotalProductQuantityInstock(1, SKU);

                                        QuantityInstock       = total;
                                        QuantityInstockString = string.Format("{0:N0}", total);
                                        ProductImage          = "<img src=\"" + Thumbnail.getURL(productvariable.Image, Thumbnail.Size.Small) + "\" alt=\"\" style=\"width:50px;\" />";
                                        ProductImageOrigin    = Thumbnail.getURL(productvariable.Image, Thumbnail.Size.Small);

                                        ProductVariable = variable;
                                        var product1 = ProductController.GetByID(Convert.ToInt32(productvariable.ProductID));
                                        if (product1 != null)
                                        {
                                            ProductName = product1.ProductTitle;
                                        }

                                        QuantityMainInstock       = mainstock;
                                        QuantityMainInstockString = string.Format("{0:N0}", mainstock);
                                        ProductVariableSave       = item.ProductVariableDescription;

                                        ProductVariableName  = variablename;
                                        ProductVariableValue = variablevalue;
                                    }
                                }
                                html += "<tr class=\"product-result\" data-mpdid=\"" + item.ID + "\" data-quantityinstock=\"" + QuantityInstock
                                        + "\" data-productimageorigin=\"" + ProductImageOrigin
                                        + "\" data-productvariable=\"" + ProductVariableSave
                                        + "\" data-productname=\"" + ProductName
                                        + "\" data-sku=\"" + SKU + "\" data-producttype=\"" + ProductType
                                        + "\" data-id=\"" + item.ID + "\" data-productnariablename=\"" + ProductVariableName
                                        + "\" data-productvariablevalue =\"" + ProductVariableValue + "\">";
                                html += "   <td>" + ProductImage + "";
                                html += "   <td>" + ProductName + "</td>";
                                html += "   <td>" + SKU + "</td>";
                                html += "   <td>" + SupplierName + "</td>";
                                html += "   <td>" + ProductVariable + "</td>";
                                html += "   <td>" + item.QuantiySend + "</td>";
                                html += "   <td style=\"width:20%;\"><input type=\"text\" min=\"0\" class=\"form-control in-quanlity\" style=\"width: 40%;margin: 0 auto;\" value=\"" + item.QuantityReceive + "\"  onkeyup=\"checkQuantiy($(this))\" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/></td>";
                                //html += "   <td><a href=\"javascript:;\" onclick=\"deleteRow($(this))\">Xóa</a></td>";
                                //html += "   <td></td>";
                                html += "</tr>";
                            }
                            ltrProducts.Text         = html;
                            hdfListProductSend.Value = listSKU;
                        }
                        #endregion
                    }
                }
            }
        }
Example #18
0
 public DeleteProductPartTest()
 {
     catalogService    = new Mock <ICatalogService>();
     warehouseService  = new Mock <IWarehouseService>();
     productController = new ProductController(catalogService.Object, warehouseService.Object);
 }
        public override List<UrlRule> GetRules(int PortalId)
        {
            List<UrlRule> Rules = new List<UrlRule>();
            Dictionary<string, Locale> dicLocales = LocaleController.Instance.GetLocales(PortalId);
            ProductController pc = new ProductController();
            CategoryController cc = new CategoryController();
            ModuleController mc = new ModuleController();
            ArrayList modules = mc.GetModulesByDefinition(PortalId, "NB_Store_ProductList");
            foreach (ModuleInfo module in modules.OfType<ModuleInfo>().Where(m=> m.IsDeleted == false))
            {
                Hashtable modSettings = mc.GetModuleSettings(module.ModuleID);

                int DetailTabId = Null.NullInteger;
                if (modSettings["lstProductTabs"] != null)
                {
                    string lstProductTabs = modSettings["lstProductTabs"].ToString();
                    int.TryParse(lstProductTabs, out DetailTabId);
                }
                bool RewriteProducts = module.TabID == DetailTabId;

                bool BrowseCategory = Null.NullBoolean;
                string chkBrowseCategory = modSettings["chkBrowseCategory"] == null ? "" :  modSettings["chkBrowseCategory"].ToString();
                Boolean.TryParse(chkBrowseCategory, out BrowseCategory);

                bool IndexProducts = true;
                if (modSettings["chkIndexProducts"] != null)
                {
                    Boolean.TryParse(modSettings["chkIndexProducts"].ToString(), out IndexProducts);
                }

                int CatID = Null.NullInteger;
                string ddlDefaultCategory = modSettings["ddlDefaultCategory"] == null ? "" : modSettings["ddlDefaultCategory"].ToString();
                int.TryParse(ddlDefaultCategory, out CatID);
                foreach (KeyValuePair<string, Locale> key in dicLocales)
                {
                    string CultureCode = key.Value.Code;
                    string RuleCultureCode = (dicLocales.Count > 1 ? CultureCode : null);
                    bool chkCascadeResults = false;
                    bool.TryParse(modSettings["chkCascadeResults"] == null ? "" : modSettings["chkCascadeResults"].ToString(), out chkCascadeResults);

                    if (RewriteProducts)
                    {
                        var prodLst = GetProductList(PortalId, pc, cc, CatID, CultureCode, chkCascadeResults);

                        //var prodLst = pc.GetProductList(PortalId, CatID, CultureCode, false);
                        foreach (ProductListInfo prod in prodLst)
                        {
                            var rule = new UrlRule
                            {
                                RuleType = UrlRuleType.Module,
                                CultureCode = RuleCultureCode,
                                TabId = module.TabID,
                                Parameters = "ProdID=" + prod.ProductID + (CatID == Null.NullInteger ? "" : "&" + "CatID=" + CatID),
                                Action = UrlRuleAction.Rewrite,
                                Url = CleanupUrl(prod.SEOName == "" ? prod.ProductName : prod.SEOName),
                                InSitemap = IndexProducts
                            };
                            Rules.Add(rule);
                        }
                    }
                    if (BrowseCategory)
                    {
                        var CatRules = GetRulesForCategory(PortalId, CultureCode, module.TabID, CatID, "", pc, cc, RuleCultureCode, chkCascadeResults, RewriteProducts, IndexProducts);
                        Rules.AddRange(CatRules);
                    }
                }
            }
            return Rules;
        }
Example #20
0
 public static void MyClassInitialize(TestContext testContext)
 {
     GenFormApplication.Initialize();
     _controller = GetNewController();
 }
Example #21
0
        private Control processToken(string tokenName)
        {
            ProductController productController = new ProductController();
            ArrayList productList = new ArrayList();

            Control parent = new Control();
            switch (tokenName)
            {
                case "MESSAGE":
                    if(bool.Parse(moduleSettings.General.ShowMessage) && categoryInfo != null)
                    {
                        // canadean changed: added category name
                        LiteralControl message = new LiteralControl(Server.HtmlDecode(categoryInfo.CategoryName));
                        parent.Controls.Add(message);
                        message = new LiteralControl(Server.HtmlDecode(categoryInfo.Message));
                        parent.Controls.Add(message);
                    }

                    if (catalogNav.CategoryID != Null.NullInteger)
                    {
                        //sub categories...
                        CategoryController controller = new CategoryController();
                        ArrayList subCategories = controller.GetCategories(PortalId, false, catalogNav.CategoryID);
                        if (subCategories.Count > 0)
                        {
                            LiteralControl BreakRow4 = new LiteralControl("<br /><div align=\"center\">");
                            parent.Controls.Add(BreakRow4);
                        }
                        //StoreController storeController = new StoreController();
                        //StoreInfo storeInfo = storeController.GetStoreInfo(PortalId);
                        foreach (CategoryInfo category in subCategories)
                        {
                            LiteralControl BreakRow = new LiteralControl("|&nbsp;");
                            parent.Controls.Add(BreakRow);
                            HyperLink link = new HyperLink();
                            link.Text = category.CategoryName;
                            StringDictionary replaceParams = new StringDictionary();
                            replaceParams["CategoryID"] = category.CategoryID.ToString();
                            replaceParams["ProductID"] = Null.NullString;
                            replaceParams["PageIndex"] = Null.NullString;
                            link.NavigateUrl = catalogNav.GetNavigationUrl(replaceParams, storeInfo.StorePageID);
                            parent.Controls.Add(link);
                            LiteralControl BreakRow2 = new LiteralControl("&nbsp;");
                            parent.Controls.Add(BreakRow2);
                        }
                        if (subCategories.Count > 0)
                        {
                            LiteralControl BreakRow3 = new LiteralControl("|</div><br/>");
                            parent.Controls.Add(BreakRow3);
                        }
                        else
                        {
                            LiteralControl BreakRow5 = new LiteralControl("<br/>");
                            parent.Controls.Add(BreakRow5);
                        }
                    }
                    return parent;

                // Canadean changed: added subcategory token
                case "SUBCATEGORY":
                    /*LiteralControl lc = new LiteralControl("pId: " + catalogNav.ProductID);
                    parent.Controls.Add(lc);*/
                    if ((catalogNav.CategoryID != Null.NullInteger) && (catalogNav.ProductID == Null.NullInteger))
                    {
                        //sub categories...
                        CategoryController controller = new CategoryController();
                        ArrayList subCategories = controller.GetCategories(PortalId, false, catalogNav.CategoryID);

                        if (subCategories.Count > 0)
                        {
                            /*
                            String htmlstr = "<br><table cellspacing='3' cellpadding='0' border='0'><tr><td class='subtitleShop'>select report category</td></tr><tr><td>" +
                                "<table cellspacing='0' cellpadding='0' border='0'> " +
                                "    <tbody>" +
                                "        <tr>" +
                                "            <td><a class='shopIntroText' href='/Shop/Reports/tabid/109/CategoryID/5/Default.aspx'>Soft Drinks</a></td>" +
                                "            <td><a href='/Shop/Reports/tabid/109/CategoryID/5/Default.aspx'><img alt='' border='0' src='/images/canadean/shop/shop_bullet.gif' /> </a></td>" +
                                "            <td>&nbsp;</td>" +
                                "            <td><a class='shopIntroText' href='/Shop/Reports/tabid/109/CategoryID/8/Default.aspx'>Beverage Packaging</a></td>" +
                                "            <td><a href='/Shop/Reports/tabid/109/CategoryID/8/Default.aspx'><img alt='' border='0' src='/images/canadean/shop/shop_bullet.gif' /> </a></td>" +
                                "            <td>&nbsp;</td>" +
                                "        </tr>" +
                                "        <tr>" +
                                "            <td><a class='shopIntroText' href='/Shop/Reports/tabid/109/CategoryID/6/Default.aspx'>Beer</a></td>" +
                                "            <td><a class='shopIntroText' href='/Shop/Reports/tabid/109/CategoryID/6/Default.aspx'><img alt='' border='0' src='/images/canadean/shop/shop_bullet.gif' /> </a></td>" +
                                "            <td>&nbsp;</td>" +
                                "            <td><a class='shopIntroText' href='/Shop/Reports/tabid/109/CategoryID/9/Default.aspx'>All Beverages</a></td>" +
                                "            <td><a class='shopIntroText' href='/Shop/Reports/tabid/109/CategoryID/9/Default.aspx'><img alt='' border='0' src='/images/canadean/shop/shop_bullet.gif' /> </a></td>" +
                                "            <td>&nbsp;</td>" +
                                "        </tr>" +
                                "        <tr>" +
                                "            <td><a class='shopIntroText' href='/Shop/Reports/tabid/109/CategoryID/7/Default.aspx'>Dairy</a></td>" +
                                "            <td><a class='shopIntroText' href='/Shop/Reports/tabid/109/CategoryID/7/Default.aspx'><img alt='' border='0' src='/images/canadean/shop/shop_bullet.gif' /> </a></td>" +
                                "            <td>&nbsp;</td>" +
                                "            <td>&nbsp;</td>" +
                                "            <td>&nbsp;</td>" +
                                "            <td>&nbsp;</td>" +
                                "        </tr>" +
                                "    </tbody>" +
                                "</table></td></tr></table><p>&nbsp;</p>";
                            */
                            // LiteralControl title = new LiteralControl(htmlstr);
                            //parent.Controls.Add(title);
                            phSubcategory.Visible = true;

                        }
                        /*
                        // Not used because of aesthetics questions
                        if (subCategories.Count > 0)
                        {
                            LiteralControl title = new LiteralControl("<br /><div class=subtitleShop>select report category</div>");
                            parent.Controls.Add(title);
                            LiteralControl BreakRow4 = new LiteralControl("<div class=categoryList><ul>");
                            parent.Controls.Add(BreakRow4);
                        }
                        //StoreController storeController = new StoreController();
                        //StoreInfo storeInfo = storeController.GetStoreInfo(PortalId);
                        foreach (CategoryInfo category in subCategories)
                        {
                            LiteralControl BreakRow = new LiteralControl("<li>");
                            parent.Controls.Add(BreakRow);
                            HyperLink link = new HyperLink();
                            link.Text = category.CategoryName;
                            link.CssClass = "newsMenuOn";
                            StringDictionary replaceParams = new StringDictionary();
                            replaceParams["CategoryID"] = category.CategoryID.ToString();
                            replaceParams["ProductID"] = Null.NullString;
                            replaceParams["PageIndex"] = Null.NullString;
                            link.NavigateUrl = catalogNav.GetNavigationUrl(replaceParams, storeInfo.StorePageID);
                            parent.Controls.Add(link);
                            LiteralControl BreakRow2 = new LiteralControl("</li>");
                            parent.Controls.Add(BreakRow2);
                        }
                        if (subCategories.Count > 0)
                        {
                            LiteralControl BreakRow3 = new LiteralControl("<ul></div>");
                            parent.Controls.Add(BreakRow3);
                        }
                        //else
                        //{
                        //    LiteralControl BreakRow5 = new LiteralControl("<br/>");
                        //    parent.Controls.Add(BreakRow5);
                        //}
                        */

                        return parent;
                    }
                    return null;

                // Canadean changed: added subsubcategory token
                case "SUBSUBCATEGORY":
                    if ((catalogNav.CategoryID3 == Null.NullInteger) && (catalogNav.CategoryID != Null.NullInteger) && (categoryInfo.ParentCategoryID == 4))    // Only show DD sub categories when we're on the Drink Type category
                    {
                        phSubSubcategory.Visible = true;
                        int categoryId1 = -1;
                        int categoryId2 = -1;
                        int returnCategory = 2;
                        categoryId1 = catalogNav.CategoryID;
                        CategoryController controller = new CategoryController();

                        if (catalogNav.CategoryID2 != Null.NullInteger)     // Type & Continent already selected, missing Country
                        {
                            labelSubSubcategoryNow.Text = "now select country";
                            categoryId2 = catalogNav.CategoryID2;
                            returnCategory = 3;
                            CategoryInfo categoryInfo2 = new CategoryInfo();
                            categoryInfo2 = controller.GetCategory(catalogNav.CategoryID2);
                            //labelCategoryName.Text = categoryInfo.CategoryName + " in " + categoryInfo2.CategoryName;
                            labelCategoryName.Text = "<u><a href='" + FixHyperlinkCatalog(catalogNav, 1) + "' class='demoHeadingLink'>" + categoryInfo.CategoryName + "</a></u> in " +
                                "<u><a href='" + FixHyperlinkCatalog(catalogNav, 2) + "' class='demoHeadingLink'>" + categoryInfo2.CategoryName + "</a></u>";

                        }
                        else
                        {
                            labelSubSubcategoryNow.Text = "now select continent";
                            //labelCategoryName.Text = categoryInfo.CategoryName;
                            labelCategoryName.Text = "<u><a href='" + FixHyperlinkCatalog(catalogNav, 1) + "' class='demoHeadingLink'>" + categoryInfo.CategoryName + "</a></u>";
                        }

                        /*String str = "<br>Getting data. Portal " + PortalId + " c1: " + categoryId1 + " c2: " + categoryId2 + " rc: " + returnCategory;
                        labelLog2.Text = str;
                        Response.Write(str);*/

                        ArrayList subCategories = controller.GetCategoriesFromProducts(PortalId, categoryId1, categoryId2, -1, returnCategory);
                        if (subCategories.Count > 0)
                        {
                            //labelSubSubCategory.Text = "<ul>";
                            bool two_columns = false;
                            int count = 0;
                            if(subCategories.Count > 24)
                                two_columns = true;

                            //Response.Write("lines: " + subCategories.Count);

                            labelSubSubCategory.Text = "<br /><table cellspacing='0' cellpadding='0' border='0'>";
                            CatalogNavigation currentCatalogNav = catalogNav;
                            foreach (CategoryInfo cur_category in subCategories)
                            {
                                String cat_name = cur_category.CategoryName;
                                int cat_id = cur_category.CategoryID;

                                StringDictionary replaceParams = new StringDictionary();
                                replaceParams["CategoryID"] = categoryId1.ToString();
                                if (catalogNav.CategoryID2 != Null.NullInteger)
                                {
                                    replaceParams["CategoryID2"] = catalogNav.CategoryID2.ToString();
                                    replaceParams["CategoryID3"] = cat_id.ToString();
                                }
                                else
                                {
                                    replaceParams["CategoryID2"] = cat_id.ToString();
                                }
                                replaceParams["ProductID"] = Null.NullString;
                                replaceParams["PageIndex"] = Null.NullString;
                                String linkCat = currentCatalogNav.GetNavigationUrl(replaceParams);

                                //Response.Write("two_colums: " + two_columns + " mod: " + (count % 2));

                                if (!two_columns || (count % 2 == 0))
                                    labelSubSubCategory.Text += "<tr>";
                                //labelSubSubCategory.Text += "<li><a href='" + linkCat + "' class='newsMenuOff'>" + cat_name + "</a></li>";
                                labelSubSubCategory.Text += "<td><a class='shopIntroText' href='" + linkCat + "'>" + cat_name + "</a></td><td>&nbsp;</td>";
                                labelSubSubCategory.Text += "<td><a href='" + linkCat + "'><img border='0' alt='' src='/images/canadean/shop/shop_bullet.gif' /></a></td>";
                                labelSubSubCategory.Text += "<td width='20%'>&nbsp;</td>";
                                if (!two_columns || (count % 2 == 1))
                                    labelSubSubCategory.Text += "</tr>";
                                count++;
                            }
                            //labelSubSubCategory.Text += "</ul>";
                            labelSubSubCategory.Text += "</table><br />";
                        }

                        //Response.Write("SUBCATEGORYDD make it visible ");
                        return parent;
                    }
                    else
                    {   // Only show the products if we have all the categories information
                        if ((catalogNav.CategoryID != Null.NullInteger) && (catalogNav.CategoryID2 != Null.NullInteger) && (catalogNav.CategoryID3 != Null.NullInteger) && (catalogNav.ProductID == Null.NullInteger))
                        {
                            phSubSubcategory.Visible = true;
                            tableSubSubCategory.Visible = false;
                            phSearchResults.Visible = true;
                            PopulateGridView(true);
                            Label1.Visible = true;
                            return parent;
                        }
                    }

                    return null;
                // Canadean changed: added subcategory token (unused for now)
                case "SUBCATEGORYDD":
                    if ((catalogNav.CategoryID != Null.NullInteger) && (categoryInfo.ParentCategoryID == 4))    // Only show DD sub categories when we're on the Drink Type category
                    {
                        phSubcategoryDD.Visible = true;
                        phSearchResults.Visible = true;
                        ddHidden.Items.Add(new ListItem(catalogNav.CategoryID.ToString(), catalogNav.CategoryID.ToString()));
                        labelAreaName.Text = categoryInfo.CategoryName;
                        //Response.Write("SUBCATEGORYDD make it visible ");
                        return parent;
                    }
                    return null;
                // Canadean changed: added Data Extracts subcategory token
                case "SUBCATEGORYDEDD":
                    //Response.Write("SUBCATEGORYDEDD make it visible {" + catalogNav.CategoryID + "} {" + categoryInfo.ParentCategoryID + "}");
                    //if ((catalogNav.CategoryID != Null.NullInteger) && (categoryInfo.ParentCategoryID == -1))    // Only show DD sub categories when we're on the Data Extracts category
                    if ((catalogNav.CategoryID != Null.NullInteger) && (categoryInfo.CategoryID == 2))    // Only show DD sub categories when we're on the Data Extracts category
                    {
                        phSubcategoryDEDD.Visible = true;
                        ddDEHidden.Items.Add(new ListItem(catalogNav.CategoryID.ToString(), catalogNav.CategoryID.ToString()));
                        //Response.Write("<br>Inside SUBCATEGORYDEDD make it visible. Selected item: " + ddDEHidden.SelectedIndex);
                        ddDEHidden.ClearSelection();

                        System.Collections.ArrayList prods = PopulateDEGridView(true);
                        int numProds = prods.Count;
                        Label2.Text = "Total cart cost: &pound;" + numProds * 50 + "";

                        return parent;
                    }
                    return null;

                case "SELECTED":    // Disabled!!       Show the products that exist in the current selected categories
                    Response.Write("SELECTED: " + catalogNav.CategoryID + " - " + catalogNav.CategoryID2 + " - " + catalogNav.CategoryID3);
                    if ((catalogNav.CategoryID != Null.NullInteger) && (catalogNav.CategoryID2 != Null.NullInteger) && (catalogNav.CategoryID3 != Null.NullInteger))    // Only show the products if we all the categories information
                    {
                        int categoryID1 = catalogNav.CategoryID;
                        int categoryID2 = catalogNav.CategoryID2;
                        int categoryID3 = catalogNav.CategoryID3;

                        phSearchResults.Visible = true;
                        GetSelectedProducts(-1, categoryID1, categoryID2, categoryID3, productList);
                        //productList = truncateList(productList, int.Parse(moduleSettings.NewProducts.RowCount) * int.Parse(moduleSettings.NewProducts.ColumnCount));
                        return loadProductList(productList, ProductListTypes.Category);
                    }
                    return null;

                // Canadean changed: added search token
                case "CATALOGSEARCH":
                    phSearchResults.Visible = true;

                    /*
                    int categoryID = 0;
                    string searchTerm = "";
                    Response.Write("here I am: " + searchTerm);
                    if (Page.IsPostBack)
                        Response.Write(" postback: ");
                    else
                        Response.Write(" not a postback: ");
                    */

                    /*
                    if (!Page.IsPostBack)
                    {
                        if (Request.Params["SearchCategoryId"] != null)
                            int.TryParse(Request.Params["SearchCategoryId"].ToString(), out categoryID);
                        if (Request.Params["Search"] != null)
                            searchTerm = Request.Params["Search"].ToString();
                        GetSearchedProducts(categoryID, searchTerm, productList);
                        //productList = truncateList(productList, int.Parse(moduleSettings.NewProducts.RowCount) * int.Parse(moduleSettings.NewProducts.ColumnCount));
                        if (productList.Count > 0)
                        {
                            gvResults.DataSource = productList;
                            gvResults.DataBind();
                        }
                    }
                    */
                    Label1.Visible = false;
                    PopulateGridView(true);

                    return parent;
                case "NEW":
                    if (bool.Parse(moduleSettings.General.ShowNewProducts))
                    {
                        if (catalogNav.CategoryID != Null.NullInteger)
                        {
                            GetNewProducts(catalogNav.CategoryID, productList);
                            productList = truncateList(productList, int.Parse(moduleSettings.NewProducts.RowCount) * int.Parse(moduleSettings.NewProducts.ColumnCount));
                            return loadProductList(productList, ProductListTypes.New);
                        }
                        else
                        {
                            productList = productController.GetPortalNewProducts(PortalId, false);
                            productList = truncateList(productList, int.Parse(moduleSettings.NewProducts.RowCount) * int.Parse(moduleSettings.NewProducts.ColumnCount));
                            return loadProductList(productList, ProductListTypes.New);
                        }
                    }
                    else
                    {
                        return null;
                    }

                case "FEATURED":
                    if (bool.Parse(moduleSettings.General.ShowFeaturedProducts))
                    {
                        if(catalogNav.CategoryID != Null.NullInteger)
                        {
                            GetFeaturedProducts(catalogNav.CategoryID, productList);
                            productList = SortProductsInRandomOrder(productList);
                            productList = truncateList(productList, int.Parse(moduleSettings.FeaturedProducts.RowCount) * int.Parse(moduleSettings.FeaturedProducts.ColumnCount));
                            return loadProductList(productList, ProductListTypes.Featured);
                        }
                        else
                        {
                            productList = productController.GetPortalFeaturedProducts(PortalId, false);
                            productList = truncateList(productList, int.Parse(moduleSettings.FeaturedProducts.RowCount) * int.Parse(moduleSettings.FeaturedProducts.ColumnCount));
                            return loadProductList(productList, ProductListTypes.Featured);
                        }
                    }
                    else
                    {
                        return null;
                    }

                case "POPULAR":
                    if (bool.Parse(moduleSettings.General.ShowPopularProducts))
                    {
                        if(catalogNav.CategoryID != Null.NullInteger)
                        {
                            GetPopularProducts(catalogNav.CategoryID, productList);
                            productList = SortProductsInRandomOrder(productList);
                            productList = truncateList(productList, int.Parse(moduleSettings.PopularProducts.RowCount) * int.Parse(moduleSettings.PopularProducts.ColumnCount));
                            return loadProductList(productList, ProductListTypes.Popular);
                        }
                        else
                        {
                            productList = productController.GetPortalPopularProducts(PortalId, false);
                            productList = truncateList(productList, int.Parse(moduleSettings.PopularProducts.RowCount) * int.Parse(moduleSettings.PopularProducts.ColumnCount));
                            return loadProductList(productList, ProductListTypes.Popular);
                        }
                    }
                    else
                    {
                        return null;
                    }

                case "CATEGORY":
                    if (bool.Parse(moduleSettings.General.ShowCategoryProducts))
                    {
                        if(catalogNav.CategoryID != Null.NullInteger && catalogNav.ProductID == Null.NullInteger)
                        {
                            GetCategoryProducts(catalogNav.CategoryID, productList);
                            productList = SortProductsInAlphabeticalOrder(productList);
                            return loadProductList(productList, ProductListTypes.Category);
                        }
                        else
                        {
                            return null;
                        }
                    }
                    else
                    {
                        return null;
                    }

                case "DETAIL":
                    if(bool.Parse(moduleSettings.General.ShowProductDetail) && catalogNav.ProductID != Null.NullInteger)
                    {
                        return loadProductDetail();
                    }
                    else
                    {
                        return null;
                    }

                default:
                    LiteralControl litText = new LiteralControl(tokenName);
                    return litText;
            }
        }
Example #22
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            /*
            Response.Write("<br>Page_load2 ");
            if (Page.IsPostBack)
                Response.Write("<br>Postback2 ");
            */

            /*
            if (Page.IsPostBack)
            {
                labelLog.Text = labelLog.Text + "<br>Page load PostBack" + DateTime.Now.ToString();
                int cat1 = -1;
                int.TryParse(DropDownList1.SelectedValue, out cat1);
                int cat2 = -1;
                int.TryParse(DropDownList2.SelectedValue, out cat2);
                labelLog.Text = labelLog.Text + "<br>dd1: " + cat1.ToString() + " dd2: " + cat2.ToString() + DateTime.Now.ToString();
            }
            else
            {
                labelLog.Text = labelLog.Text + "<br>Page load - Not a PostBack" + DateTime.Now.ToString();
            } */
                //Response.Write("Page_PreRender");

                npTitle = Localization.GetString("NPTitle.Text", this.LocalResourceFile);
                fpTitle = Localization.GetString("FPTitle.Text", this.LocalResourceFile);
                ppTitle = Localization.GetString("PPTitle.Text", this.LocalResourceFile);
                cpTitle = Localization.GetString("CPTitle.Text", this.LocalResourceFile);

                try
                {
                    if (storeInfo == null)
                    {
                        StoreController storeController = new StoreController();
                        storeInfo = storeController.GetStoreInfo(PortalId);
                        if (storeInfo.PortalTemplates)
                        {
                            templatesPath = PortalSettings.HomeDirectoryMapPath + "Store\\";
                            CssTools.AddCss(this.Page, PortalSettings.HomeDirectory + "Store", PortalId);
                        }
                        else
                        {
                            templatesPath = MapPath(ModulePath) + "\\";
                            CssTools.AddCss(this.Page, this.TemplateSourceDirectory, PortalId);
                        }
                    }

                    moduleSettings = new ModuleSettings(this.ModuleId, this.TabId);

                    catalogNav = new CatalogNavigation(Request.QueryString);

                    if (catalogNav.CategoryID == Null.NullInteger)
                    {
                        if (bool.Parse(moduleSettings.General.UseDefaultCategory))
                        {
                            catalogNav.CategoryID = int.Parse(moduleSettings.General.DefaultCategoryID);
                        }
                    }

                    if (catalogNav.ProductID != Null.NullInteger)
                    {
                        ProductController productController = new ProductController();
                        productInfo = productController.GetProduct(catalogNav.ProductID);
                        catalogNav.CategoryID = productInfo.CategoryID;
                    }

                    if (catalogNav.CategoryID != Null.NullInteger)
                    {
                        CategoryController categoryController = new CategoryController();
                        categoryInfo = categoryController.GetCategory(catalogNav.CategoryID);
                    }

                    this.Controls.Add(TemplateController.ParseTemplate(templatesPath, moduleSettings.General.Template, new ProcessTokenDelegate(processToken)));

                    // Canadean changed: added current categoryid on a hidden dropdown, to use on the cascade categories
                    /*
                    if (catalogNav.CategoryID != Null.NullInteger)
                    {
                        ddHidden.Items.Add(new ListItem(catalogNav.CategoryID.ToString(), catalogNav.CategoryID.ToString()));
                    }
                    */

                }
                catch (Exception ex)
                {
                    string ErrorSettings = Localization.GetString("ErrorSettings", this.LocalResourceFile);
                    Response.Write("<br>" + ex.Message);
                    Response.Write("<br>" + ex.StackTrace);

                    //Exceptions.ProcessModuleLoadException(ErrorSettings, this, ex, true);
                }
                if (DotNetNuke.Framework.AJAX.IsInstalled())
                {
                    DotNetNuke.Framework.AJAX.RegisterScriptManager();
                }

            //}
        }
Example #23
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.txtIDproduct.Text.Trim().Length <= 0)
            {
                this.errorProvider1.SetError(txtIDproduct, "Chưa nhập ID sản phẩm");
                return;
            }
            else
            {
                this.errorProvider1.Clear();
            }

            if (this.txtNameProduct.Text.Trim().Length <= 0)
            {
                this.errorProvider1.SetError(txtNameProduct, "Chưa nhập tên sản phẩm");
                return;
            }
            else
            {
                this.errorProvider1.Clear();
            }

            if (this.txtPrice.Text.Trim().Length <= 0)
            {
                this.errorProvider1.SetError(txtPrice, "Chưa nhập giá sản phẩm");
                return;
            }
            else
            {
                this.errorProvider1.Clear();
            }

            if (this.txtDescription.Text.Trim().Length <= 0)
            {
                this.errorProvider1.SetError(txtDescription, "Chưa nhập mô tả cho sản phẩm");
                return;
            }
            else
            {
                this.errorProvider1.Clear();
            }
            if (this.ptbSaveImage.Image == null)
            {
                return;
            }
            // // nhap product
            Product product = new Product();

            product.codeBarQR   = this.txtIDproduct.Text.Trim();
            product.nameProduct = this.txtNameProduct.Text.Trim();
            product.Price       = this.txtPrice.Text.Trim();

            product.dateCreate   = DateTime.Now;
            product.Descriptions = this.txtDescription.Text.Trim();
            product.pathImage    = this.duongdan;

            // them product vao list
            if (ProductController.AddProduct(product) == false)
            {
                MessageBox.Show("Không thêm sản phẩm được");
                return;
            }



            // hien thi list len datagridview
            BindingSource source = new BindingSource();

            source.DataSource           = ProductController.getlistProduct();
            this.dataProduct.DataSource = source;



            // clear cac txt de nhap thong tin product
            this.txtIDproduct.Clear();
            this.txtNameProduct.Clear();
            this.txtPrice.Clear();
            this.txtDescription.Clear();
            this.dtpDateCreate.Value = DateTime.Now;
            this.ptbSaveImage.CreateGraphics().Clear(Color.White);
        }
Example #24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                // Get the navigation settings
                _nav = new CatalogNavigation(Request.QueryString)
                {
                    ProductID = (int)DataSource
                };

                // Handle ProductID=0 as Null.NullInteger
                if (_nav.ProductID == 0)
                {
                    _nav.ProductID = Null.NullInteger;
                }

                if (Page.IsPostBack == false)
                {
                    // Get category list
                    CategoryController  categoryController = new CategoryController();
                    List <CategoryInfo> categories         = categoryController.GetCategoriesPath(PortalId, true, Null.NullInteger);

                    // If no category exists, display a warning message
                    if (categories == null || categories.Count == 0)
                    {
                        pnlCategoriesRequired.Visible = true;
                        tblProductForm.Visible        = false;
                    }
                    else
                    {
                        pnlCategoriesRequired.Visible = false;
                        // Bind categories and add 'select' choice to the dropdown
                        cmbCategory.DataSource = categories;
                        cmbCategory.DataBind();
                        cmbCategory.Items.Insert(0, new ListItem(Localization.GetString("SelectComboValue", LocalResourceFile), "-1"));

                        // Allowed file extentions
                        imgProduct.FileFilter = "bmp,png,jpg,jpeg,gif";

                        // Are we editing or creating new item?
                        if (_nav.ProductID != Null.NullInteger || _copyFrom != Null.NullInteger)
                        {
                            ProductController controller = new ProductController();
                            ProductInfo       product    = controller.GetProduct(PortalId, _nav.ProductID == Null.NullInteger ? _copyFrom : _nav.ProductID);

                            if (product != null)
                            {
                                if (_copyFrom == Null.NullInteger)
                                {
                                    // Set delete confirmation
                                    cmdDelete.Attributes.Add("onClick", "javascript:return confirm('" + Localization.GetString("DeleteItem") + "');");
                                    cmdDelete.Visible = true;
                                }
                                // Define fields values
                                cmbCategory.SelectedValue = product.CategoryID.ToString();
                                txtManufacturer.Text      = product.Manufacturer;
                                txtModelNumber.Text       = product.ModelNumber;
                                txtModelName.Text         = product.ModelName;
                                if (StoreSettings.SEOFeature)
                                {
                                    txtSEOName.Text  = product.SEOName;
                                    txtKeywords.Text = product.Keywords;
                                }
                                else
                                {
                                    trSEOName.Visible  = false;
                                    trKeywords.Visible = false;
                                }
                                txtSummary.Text      = product.Summary;
                                txtRegularPrice.Text = product.RegularPrice.ToString("0.00");
                                txtUnitPrice.Text    = product.UnitCost.ToString("0.00");
                                if (StoreSettings.CheckoutMode == CheckoutType.Registred && StoreSettings.AllowVirtualProducts)
                                {
                                    chkVirtualProduct.Checked = product.IsVirtual;
                                }
                                else
                                {
                                    trVirtualProduct.Visible = false;
                                }
                                if (chkVirtualProduct.Checked)
                                {
                                    trVirtualProductSection.Visible = true;
                                    trProductDimensions.Visible     = false;
                                    if (product.VirtualFileID == Null.NullInteger)
                                    {
                                        urlProductFile.UrlType = "N";
                                    }
                                    else
                                    {
                                        urlProductFile.Url     = "FileID=" + product.VirtualFileID;
                                        urlProductFile.UrlType = "F";
                                    }
                                    txtAllowedDownloads.Text = product.AllowedDownloads.ToString();
                                }
                                else
                                {
                                    trVirtualProductSection.Visible = false;
                                    trProductDimensions.Visible     = true;
                                    txtUnitWeight.Text = product.ProductWeight == Null.NullDecimal ? string.Empty : product.ProductWeight.ToString("0.00");
                                    txtUnitHeight.Text = product.ProductHeight == Null.NullDecimal ? string.Empty : product.ProductHeight.ToString("0.00");
                                    txtUnitLength.Text = product.ProductLength == Null.NullDecimal ? string.Empty : product.ProductLength.ToString("0.00");
                                    txtUnitWidth.Text  = product.ProductWidth == Null.NullDecimal ? string.Empty : product.ProductWidth.ToString("0.00");
                                }
                                if (StoreSettings.InventoryManagement)
                                {
                                    txtStockQuantity.Text = product.StockQuantity.ToString();
                                    txtLowThreshold.Text  = product.LowThreshold.ToString();
                                    txtHighThreshold.Text = product.HighThreshold.ToString();
                                    txtDeliveryTime.Text  = product.DeliveryTime.ToString();
                                    txtPurchasePrice.Text = product.PurchasePrice.ToString("0.00");
                                }
                                else
                                {
                                    trStockManagement.Visible = false;
                                }
                                chkArchived.Checked = product.Archived;

                                LoadRole(product.RoleID);

                                bool isFeatured = product.Featured;
                                chkFeatured.Checked   = isFeatured;
                                trFeatured.Visible    = isFeatured;
                                txtSalePrice.Text     = product.SalePrice == Null.NullDecimal ? string.Empty : product.SalePrice.ToString("0.00");
                                txtSaleStartDate.Text = product.SaleStartDate != Null.NullDate ? product.SaleStartDate.ToString("d") : "";
                                txtSaleEndDate.Text   = product.SaleEndDate != Null.NullDate ? product.SaleEndDate.ToString("d") : "";
                                if (isFeatured)
                                {
                                    MakeCalendars();
                                }

                                if (string.IsNullOrEmpty(product.ProductImage) == false)
                                {
                                    if (product.ProductImage.StartsWith("http://") || product.ProductImage.StartsWith("https://"))
                                    {
                                        imgProduct.Url     = product.ProductImage;
                                        imgProduct.UrlType = "U";
                                    }
                                    else
                                    {
                                        imgProduct.Url     = FileSystemHelper.GetUrlFileID(product.ProductImage, PortalSettings);
                                        imgProduct.UrlType = "F";
                                    }
                                }
                                txtDescription.Text = product.Description;
                            }
                            else
                            {
                                // Handle as new item
                                PrepareNew();
                            }
                        }
                        else
                        {
                            // Handle as new item
                            PrepareNew();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
        }
Example #25
0
        protected void cmdUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                if (chkVirtualProduct.Checked && urlProductFile.UrlType == "N")
                {
                    trErrorProductFile.Visible = true;
                    return;
                }

                trErrorProductFile.Visible = false;

                if (Page.IsValid)
                {
                    ProductInfo product = new ProductInfo
                    {
                        ProductID    = _nav.ProductID,
                        PortalID     = PortalId,
                        CategoryID   = int.Parse(cmbCategory.SelectedValue),
                        Manufacturer = txtManufacturer.Text,
                        ModelNumber  = txtModelNumber.Text,
                        ModelName    = txtModelName.Text
                    };
                    if (StoreSettings.SEOFeature)
                    {
                        product.SEOName  = txtSEOName.Text;
                        product.Keywords = txtKeywords.Text;
                    }
                    product.Summary      = txtSummary.Text;
                    product.RegularPrice = Decimal.Parse(txtRegularPrice.Text);
                    product.UnitCost     = Decimal.Parse(txtUnitPrice.Text);
                    product.IsVirtual    = chkVirtualProduct.Checked;
                    if (product.IsVirtual)
                    {
                        product.VirtualFileID    = GetProductFileID();
                        product.AllowedDownloads = int.Parse(txtAllowedDownloads.Text);
                        product.ProductWeight    = 0;
                        product.ProductHeight    = 0;
                        product.ProductLength    = 0;
                        product.ProductWidth     = 0;
                    }
                    else
                    {
                        product.ProductWeight = Decimal.Parse(txtUnitWeight.Text);
                        product.ProductHeight = Decimal.Parse(txtUnitHeight.Text);
                        product.ProductLength = Decimal.Parse(txtUnitLength.Text);
                        product.ProductWidth  = Decimal.Parse(txtUnitWidth.Text);
                    }
                    if (StoreSettings.InventoryManagement)
                    {
                        product.StockQuantity = int.Parse(txtStockQuantity.Text);
                        product.LowThreshold  = int.Parse(txtLowThreshold.Text);
                        product.HighThreshold = int.Parse(txtHighThreshold.Text);
                        product.DeliveryTime  = int.Parse(txtDeliveryTime.Text);
                        product.PurchasePrice = Decimal.Parse(txtPurchasePrice.Text);
                    }
                    else
                    {
                        product.StockQuantity = 0;
                        product.LowThreshold  = 0;
                        product.HighThreshold = 0;
                        product.DeliveryTime  = 0;
                        product.PurchasePrice = 0;
                    }
                    product.Archived = chkArchived.Checked;
                    if (StoreSettings.CheckoutMode == CheckoutType.Registred)
                    {
                        product.RoleID = int.Parse(lstRole.SelectedValue);
                    }
                    product.Featured  = chkFeatured.Checked;
                    product.SalePrice = txtSalePrice.Text.Length > 0 ? Decimal.Parse(txtSalePrice.Text) : Null.NullDecimal;
                    string saleDate = txtSaleStartDate.Text;
                    product.SaleStartDate = product.Featured && !Null.IsNull(saleDate) ? Convert.ToDateTime(saleDate) : Null.NullDate;
                    saleDate              = txtSaleEndDate.Text;
                    product.SaleEndDate   = product.Featured && !Null.IsNull(saleDate) ? Convert.ToDateTime(saleDate) : Null.NullDate;
                    product.ProductImage  = GetImageUrl();
                    product.Description   = txtDescription.Text;
                    product.CreatedByUser = UserId.ToString();
                    product.CreatedDate   = DateTime.Now;

                    ProductController controller = new ProductController();
                    if (product.ProductID == Null.NullInteger)
                    {
                        controller.AddProduct(product);
                    }
                    else
                    {
                        controller.UpdateProduct(product);
                    }
                    InvokeEditComplete();
                }
            }
            catch (Exception ex)
            {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
        }
Example #26
0
        private void buyProduct()
        {
            string user_infoid = (SessionApp.user_info == null) ? "No Login" : SessionApp.user_info.user_infoid;
            string user_name   = (SessionApp.user_info == null) ? "No Login" : SessionApp.user_info.user_name;

            var promotion = PromotionController.GetPromotionByPromotionCode(txtPromotionCode.Text);

            if (!string.IsNullOrEmpty(txtPromotionCode.Text) && promotion == null)
            {
                ShowMessage(Page, "ไม่พบโปรโมชั่นนี้");
                return;
            }
            float  discount        = 0;
            string promotion_id    = null;
            float  totalprice_cart = currentCart.Sum(c => c.sum_price);


            if (promotion != null)
            {
                if (totalprice_cart >= promotion.complete_price)
                {
                    if (promotion.promotion_type == 1)
                    {
                        discount = (total_price / 100) * promotion.discount_percent;
                    }
                    if (promotion.promotion_type == 2)
                    {
                        discount = promotion.discount_value;
                    }
                    promotion_id = promotion.promotion_id;
                }
            }



            var bill = BillController.AddBill(user_infoid, total_price - discount, txtAddress.Text, promotion_id, total_price, user_name);
            List <BillDetailInfo> bills = new List <BillDetailInfo>();

            foreach (var c in currentCart)
            {
                var resultbill = BillController.AddBillDetail(bill.bill_id, c.product_id, c.cart_amount, (c.cart_amount * c.price), user_name);
                bills.Add(resultbill);
            }



            if (promotion != null)
            {
                if (promotion.promotion_type == 3)
                {
                    var product = ProductController.GetProduct(promotion.free_product_id, null);

                    if (product == null)
                    {
                        ShowMessage(Page, "ไม่พบรายการของแถม");
                        return;
                    }
                    var currentPro = product[0];
                    var resultBill = BillController.AddBillDetail(bill.bill_id, currentPro.product_id, promotion.free_amount, 0, user_name);;
                    bills.Add(resultBill);
                }
            }

            var billInfo = BillController.GetBill(bill.bill_id, user_infoid);

            if (bill != null && billInfo.Count > 0)
            {
                var    currentBill = billInfo[0];
                string contentMail = "ท่านได้มีรายการสั่งซื้อ";
                contentMail += "<br/> หมายเลขใบเสร็จที่ : " + currentBill.bill_code.ToString("000000#");
                contentMail += "<br/> ท่านสามารถเข้าดูรายการซื้อขายได้ที่ : <a href='http://www.nungningracingshop.com/Bill/BillDetail?bill_id=" + currentBill.bill_id + "'> คลิกที่นี่ </a>";
                contentMail += "<br/><br/> ขอขอบพระคุณท่านลูกค้าที่อุดหนุนร้าน NungNingRacingShop";
                try
                {
                    MailController.sendEmail(SessionApp.user_info.email, "รายการสั่งซื้อ", contentMail);
                }
                catch
                {
                }
                RedirectTo("~/Bill/BillDetail?bill_id=" + currentBill.bill_id);
            }
        }
Example #27
0
 public ProductList()
 {
     InitializeComponent();
     controller = new ProductController();
 }
 public void Setup()
 {
     _productsService   = A.Fake <IProductsService>();
     _productController = new ProductController(_productsService);
     _productsFixtures  = new ProductsFixtures();
 }
Example #29
0
 public Product_Create_View(Produktverwaltung_View parentView)
 {
     this.parentView = parentView;
     this.prodCont   = new ProductController();
     InitializeComponent();
 }
        public void Generate_Category_Specific_Product_Count()
        {
            //Arrange
            //Create the mock repository
            Mock<IProductsRepository> mockRepo = new Mock<IProductsRepository>();
            mockRepo.Setup(m => m.Products).Returns(new Product[]{
                new Product {ProductID = 1, Name = "P1", Category = "Cat1"},
                new Product {ProductID = 1, Name = "P2", Category = "Cat2"},
                new Product {ProductID = 1, Name = "P3", Category = "Cat1"},
                new Product {ProductID = 1, Name = "P4", Category = "Cat2"},
                new Product {ProductID = 1, Name = "P5", Category = "Cat3"},
            });

            //Arrange
            //Create the controller
            ProductController controller = new ProductController(mockRepo.Object);
            controller.PageSize = 3;

            //Act
            //Test the products for different categories
            int result1 = ((ProductListViewModel)controller.List("Cat1").Model).PagingInfo.TotalItems;
            int result2 = ((ProductListViewModel)controller.List("Cat2").Model).PagingInfo.TotalItems;
            int result3 = ((ProductListViewModel)controller.List("Cat3").Model).PagingInfo.TotalItems;
            int resultAll = ((ProductListViewModel)controller.List(null).Model).PagingInfo.TotalItems;

            //Assert
            Assert.AreEqual(result1, 2);
            Assert.AreEqual(result2, 2);
            Assert.AreEqual(result3, 1);
            Assert.AreEqual(resultAll, 5);
        }
Example #31
0
        public void InserOrderDetail(string AgentAPIID, string AgentAPICode, int OrderID, int ID, string SKU, int ProductType,
                                     string ProductVariableName, string ProductVariableValue, double Quantity, string ProductName, string ProductImageOrigin,
                                     double ProductPrice, string ProductVariableSave, int ExcuteStatus, int PaymentStatus, string CreatedBy, string username, string password)
        {
            var rs = new ResponseClass();

            if (Login(username, password))
            {
                DateTime currentDate = DateTime.Now;
                var      agent       = AgentController.GetByAPICodeID(AgentAPIID, AgentAPICode);
                if (agent != null)
                {
                    int AgentID           = agent.ID;
                    int ProductID         = 0;
                    int ProductVariableID = 0;
                    if (ProductType == 1)
                    {
                        ProductID         = ID;
                        ProductVariableID = 0;
                    }
                    else
                    {
                        ProductID         = 0;
                        ProductVariableID = ID;
                    }

                    if (ExcuteStatus == 2 && PaymentStatus == 3)
                    {
                        OrderDetailController.Insert(AgentID, OrderID, SKU, ProductID, ProductVariableID, ProductVariableSave, Quantity,
                                                     ProductPrice, 1, 0, ProductType, currentDate, CreatedBy, true);
                        if (ProductType == 1)
                        {
                            StockManagerController.Insert(
                                new tbl_StockManager
                            {
                                AgentID           = AgentID,
                                ProductID         = ProductID,
                                ProductVariableID = 0,
                                Quantity          = Quantity,
                                QuantityCurrent   = 0,
                                Type        = 2,
                                NoteID      = String.Empty,
                                OrderID     = OrderID,
                                Status      = 3,
                                SKU         = SKU,
                                CreatedDate = currentDate,
                                CreatedBy   = CreatedBy,
                                MoveProID   = 0,
                                ParentID    = ProductID
                            });
                        }
                        else
                        {
                            int    parentID  = 0;
                            string parentSKU = "";
                            var    productV  = ProductVariableController.GetByID(ProductVariableID);
                            if (productV != null)
                            {
                                parentSKU = productV.ParentSKU;
                            }
                            if (!string.IsNullOrEmpty(parentSKU))
                            {
                                var product = ProductController.GetBySKU(parentSKU);
                                if (product != null)
                                {
                                    parentID = product.ID;
                                }
                            }
                            StockManagerController.Insert(
                                new tbl_StockManager
                            {
                                AgentID           = AgentID,
                                ProductID         = 0,
                                ProductVariableID = ProductVariableID,
                                Quantity          = Quantity,
                                QuantityCurrent   = 0,
                                Type        = 2,
                                NoteID      = String.Empty,
                                OrderID     = OrderID,
                                Status      = 3,
                                SKU         = SKU,
                                CreatedDate = currentDate,
                                CreatedBy   = CreatedBy,
                                MoveProID   = 0,
                                ParentID    = parentID
                            });
                        }
                    }
                    else
                    {
                        OrderDetailController.Insert(AgentID, OrderID, SKU, ProductID, ProductVariableID, ProductVariableSave, Quantity,
                                                     ProductPrice, 1, 0, ProductType, currentDate, CreatedBy, false);
                    }
                    rs.Code    = APIUtils.GetResponseCode(APIUtils.ResponseCode.SUCCESS);
                    rs.Status  = APIUtils.ResponseMessage.Success.ToString();
                    rs.Message = "Tạo mới đơn hàng thành công";
                }
                else
                {
                    rs.Code    = APIUtils.GetResponseCode(APIUtils.ResponseCode.NotFound);
                    rs.Status  = APIUtils.ResponseMessage.Error.ToString();
                    rs.Message = "Không tồn tại thông tin đại lý";
                }
            }
            else
            {
                rs.Code   = APIUtils.GetResponseCode(APIUtils.ResponseCode.FAILED);
                rs.Status = APIUtils.ResponseMessage.Fail.ToString();
            }

            Context.Response.ContentType = "application/json";
            Context.Response.Write(JsonConvert.SerializeObject(rs, Formatting.Indented));
            Context.Response.Flush();
            Context.Response.End();
        }
 public ProductControllerTests()
 {
     productMockRepo = Substitute.For <IRepository <ProductModel> >();
     testController  = new ProductController(productMockRepo);
 }
Example #33
0
        private ArrayList GetSearchedProducts(int categoryID, string searchTerm, ArrayList products)
        {
            ProductController productController = new ProductController();

            foreach (ProductInfo product in productController.GetSearchedProducts(categoryID, searchTerm, false))
            {
                products.Add(product);
            }

            return products;
        }
Example #34
0
        /// <summary>
        /// Creates a new Productcontroller and uses its method read with the given parameters.
        /// </summary>
        /// <param name="name"></param>
        /// <returns>Product product</returns>
        public Product Read(string name)
        {
            ProductController productController = new ProductController();

            return(productController.Read(name));
        }
Example #35
0
        /// <summary>
        /// Creates a new Productcontroller and uses its method FindById with the given parameters.
        /// </summary>
        /// <param name="id"></param>
        /// <returns>Product product</returns>

        public Product FindById(int id)
        {
            ProductController productController = new ProductController();

            return(productController.FindById(id));
        }
Example #36
0
        /// <summary>
        /// Creates a new Productcontroller and uses its method FindUniqueByProduct with the given parameters.
        /// </summary>
        /// <param name="product"></param>
        /// <param name="amount"></param>
        /// <returns>IEnumerable<UniqueProduct> ListOfUnqueProducts</returns>

        public IEnumerable <UniqueProduct> FindUniqueByProduct(Product product, int amount)
        {
            ProductController productController = new ProductController();

            return(productController.FindUniqueByProducts(product, amount));
        }
        private List<UrlRule> GetRulesForCategory(int PortalId, string CultureCode, int TabId, int CatID, string CategoryUrl, ProductController pc, CategoryController cc, string RuleCultureCode, bool chkCascadeResults, bool RewriteProducts, bool IndexProducts)
        {
            List<UrlRule> Rules = new List<UrlRule>();
            var catLst = cc.GetCategories(PortalId, CultureCode, CatID == Null.NullInteger ? 0 : CatID);
            foreach (NB_Store_CategoriesInfo cat in catLst)
            {
                var CatRule = new UrlRule
                {
                    RuleType = UrlRuleType.Module,
                    CultureCode = RuleCultureCode,
                    TabId = TabId,
                    Parameters = "CatID=" + cat.CategoryID,
                    Action = UrlRuleAction.Rewrite,
                    Url = (CategoryUrl == "" ? "" : CategoryUrl + "/") + CleanupUrl(cat.SEOName == "" ? cat.CategoryName : cat.SEOName),
                    InSitemap = IndexProducts
                };
                CatRule.RedirectDestination = CatRule.Parameters.Replace('=', '/').Replace('&', '/') + "/" + CleanupSEO(cat.SEOName == "" ? cat.CategoryName : cat.SEOName);
                CatRule.RedirectDestination = CatRule.RedirectDestination.ToLower();
                if (string.IsNullOrEmpty(CatRule.Url))
                {
                    //continue;
                }
                Rules.Add(CatRule);

                if (RewriteProducts)
                {
                    var productLst = GetProductList(PortalId, pc, cc, cat.CategoryID, CultureCode, chkCascadeResults);
                    //var productLst = pc.GetProductList(PortalId, cat.CategoryID, CultureCode, false);
                    foreach (ProductListInfo prod in productLst)
                    {
                        var rule = new UrlRule
                        {
                            RuleType = UrlRuleType.Module,
                            CultureCode = RuleCultureCode,
                            TabId = TabId,
                            Parameters = "ProdID=" + prod.ProductID + "&" + "CatID=" + cat.CategoryID,
                            Action = UrlRuleAction.Rewrite,
                            Url = (CategoryUrl == "" ? "" : CategoryUrl + "/") + CleanupUrl(cat.SEOName == "" ? cat.CategoryName : cat.SEOName) + "/" + CleanupUrl(prod.SEOName == "" ? prod.ProductName : prod.SEOName),
                            InSitemap = IndexProducts
                        };
                        Rules.Add(rule);
                    }
                }
                var CatRules = GetRulesForCategory(PortalId, CultureCode, TabId, cat.CategoryID, CatRule.Url, pc, cc, RuleCultureCode, chkCascadeResults, RewriteProducts, IndexProducts);
                Rules.AddRange(CatRules);
            }
            return Rules;
        }
Example #38
0
        /// <summary>
        /// Creates a new Productcontroller and uses its method getall.
        /// </summary>
        /// <returns>IEnumerable<Product> ListOfProducts</returns>

        public IEnumerable <Product> GetAll()
        {
            ProductController productController = new ProductController();

            return(productController.GetAll());
        }
        protected void ProductList_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                //determine the selected GridView Row
                //This opbtains a pointer to the selected row
                GridViewRow agvrow = ProductList.Rows[ProductList.SelectedIndex];
                //obtaining a pointer to the control on the row
                //warning: if you cannot find the control on the gridview
                //  your error will be Object Reference set to null
                HiddenField aPointerToControl = agvrow.FindControl("ProductID") as HiddenField;
                //obtain the contents of the control on the gridview
                //most contents of controls are returned as a string
                string hiddenfieldvalue = aPointerToControl.Value;
                //convert the string value to a numeric
                int productid = int.Parse(hiddenfieldvalue);
                //the last 3 lines could be coded as one
                //int productid = int.Parse((agvrow.FindControl("ProductID") as HiddenField).Value);


                //string productname = (agvrow.FindControl("ProductName") as Label).Text;

                //standard lookup
                ProductController sysmgr = new ProductController();
                Product           info   = sysmgr.Product_FindByID(productid);
                //a single row test
                if (info == null)
                {
                    MessageLabel.Text = "Product not currently on file. Refresh your search";
                    //optionally clear your display
                    //reuse a method (event) in your program
                    Clear_Click(sender, e);
                }
                else
                {
                    ProductID.Text   = info.ProductID.ToString();
                    ProductName.Text = info.ProductName;
                    //Typecasting: ? "0" : (int) info.CategoryID.ToString()
                    CategoryList.SelectedValue = info.CategoryID.HasValue ? info.CategoryID.ToString() : "0";
                    SupplierList.SelectedValue = info.SupplierID.HasValue ? info.SupplierID.ToString() : "0";
                    QuantityPerUnit.Text       = string.IsNullOrEmpty(info.QuantityPerUnit) ? "" : info.QuantityPerUnit;
                    UnitPrice.Text             = string.Format("{0:0.00}", info.UnitPrice);
                    //long form version of the above ^

                    if (info.UnitsInStock == null)
                    {
                        UnitsInStock.Text = "0";
                    }
                    else
                    {
                        UnitsInStock.Text = info.UnitsInStock.ToString();
                    }

                    if (info.UnitsOnOrder == null)
                    {
                        UnitsOnOrder.Text = "0";
                    }
                    else
                    {
                        UnitsOnOrder.Text = info.UnitsOnOrder.ToString();
                    }

                    if (info.ReorderLevel == null)
                    {
                        ReorderLevel.Text = "0";
                    }
                    else
                    {
                        ReorderLevel.Text = info.ReorderLevel.ToString();
                    }

                    Discontinued.Checked = info.Discontinued;
                }
            }
            catch (Exception ex)
            {
                MessageLabel.Text = GetInnerException(ex).Message;
            }
        }
        private static void Main()
        {
            UPSContext context = new UPSContext(UPSContext.StringConnectToMainServer);
            Client     сlient  = default;
            Basket     basket  = new Basket(сlient);

            #region Authorization

            while (true)
            {
                Console.Clear();
                Console.WriteLine("Здравствуйте уважаемый пользователь! Если вы зарегистрированы, введите L и введите свои данные.");
                Console.WriteLine("Или если вы не зарегистрированы, введите R и введите данные о вас.");
                switch (Console.ReadKey(true).Key)
                {
                    #region key L (log-in)

                case ConsoleKey.L:
                    Console.Write("Имя: ");
                    string newName = Console.ReadLine();
                    Console.Write("Пароль: ");
                    string newPassword = Console.ReadLine();

                    сlient = ClientController.LoadOfPerson <Client>(newName, newPassword, context) as Client;

                    if (сlient is null)
                    {
                        Console.Write("Данные некорректны (пустое имя/пароль/в них только символы разделители или они неверны).");
                        continue;
                    }
                    else
                    {
                        basket.Client = сlient;
                        Console.WriteLine($"Добро пожаловать, {сlient}!");
                    }

                    Thread.Sleep(6000);
                    break;

                    #endregion

                    #region key R (registration)

                case ConsoleKey.R:
                    Console.Write("Ваше новое имя: ");
                    string name = Console.ReadLine();
                    Console.Write("Ваш новый пароль: ");
                    string password = Console.ReadLine();

                    сlient = ClientController.RegistrationOfPerson <Client>(name, password, context) as Client;

                    if (сlient is null)
                    {
                        Console.Write("Данные некорректны (пустое имя/пароль/в них только символы разделители), ");
                        Console.WriteLine("или пользователь с таким именем уже существует!");
                        Thread.Sleep(6000);
                        continue;
                    }
                    basket.Client = сlient;

                    Thread.Sleep(6000);
                    break;

                    #endregion
                }
                break;
            }

            #endregion


            var products = ProductController.LoadProducts(context);

            while (true)
            {
                bool productsIsAvailable = false;
                Console.Clear();

                if (products.Count > 0)
                {
                    productsIsAvailable = true;
                    Console.WriteLine("Нам доступны следующие продукты:");
                    foreach (var product in products)
                    {
                        Console.WriteLine($"{ProductController.GetName(product)}, ");
                        Console.Write($"стоимость: {ProductController.GetCost(product)} рублей. \n\n");
                    }
                    Console.WriteLine("Нажмите A(англ), если хотите добавить один из продуктов в корзину.");
                    Console.WriteLine("Если ваша корзина уже заполнена, нажмите Y, что бы совершить покупку.");
                    Console.WriteLine("Если хотите удалить продукт из корзины, нажмите D, после чего вы введёте его имя.");
                }
                Console.WriteLine("\nНажмите Q, если хотите пополнить счёт.");
                Console.WriteLine("(раскладка не учитывается)");

                switch (Console.ReadKey(true).Key)
                {
                    #region key A (adding product)

                case ConsoleKey.A:
                    if (productsIsAvailable)
                    {
                        Console.WriteLine("Введите полное название продукта.");
                        string inputNameOfProduct = Console.ReadLine();

                        var product = products.FirstOrDefault(prod => prod.Name == inputNameOfProduct);
                        if (product != default)
                        {
                            if (ClientController.AddProductInBasket(basket, product))
                            {
                                Console.WriteLine($"Продукт с именем {product} добавлен в корзину!");
                            }
                        }
                        else
                        {
                            Console.WriteLine("Продукта с таким именем не существует в продаже!");
                        }
                        Thread.Sleep(6000);
                    }
                    break;

                    #endregion

                    #region key Y (buy)

                case ConsoleKey.Y:

                    if (productsIsAvailable)
                    {
                        const string constYes = "yes";
                        Console.Clear();
                        Console.WriteLine($@"Вы уверены, что хотите совершить покупку? Введите ""{constYes}"", если согласны.");
                        Console.WriteLine("(регистр не учитывается)");

                        if (Console.ReadLine().ToLower() == constYes)
                        {
                            if (ClientController.Buy(basket, context))
                            {
                                Console.WriteLine("Покупка успешно совершена. Ваши данные после покупки:");
                                Console.WriteLine($"Баланс: {ClientController.GetBalance(сlient)} рублей.");
                                Thread.Sleep(6000);
                            }
                            else
                            {
                                Console.Write("Ваш баланс меньше чем общая стоимость корзины с учётом коэффициента скидки, ");
                                Console.Write("ваш аккаунт повреждён или корзина пуста! \n");
                            }
                            Thread.Sleep(6000);
                        }
                    }
                    break;

                    #endregion

                    #region key D (deleting product)

                case ConsoleKey.D:
                    if (productsIsAvailable)
                    {
                        Console.Write("Название удаляемого продукта: ");
                        string name = Console.ReadLine();

                        if (ClientController.DeleteProductFromBasket(basket, name))
                        {
                            Console.WriteLine($"Продукт {name} был удалён из корзины.");
                        }
                        else
                        {
                            Console.WriteLine("Продукт не был удалён!");
                        }

                        Thread.Sleep(6000);
                    }
                    break;
                    #endregion

                    #region key Q (upping balance)

                case ConsoleKey.Q:
                    Console.Write("Сумма пополнения в рублях: ");

                    if (decimal.TryParse(Console.ReadLine(), out decimal input) == false)
                    {
                        Console.WriteLine("Были введены некорректные данные!");
                        Thread.Sleep(3000);
                        continue;
                    }
                    if (ClientController.UpBalance(сlient, input, context) != -1)
                    {
                        Console.WriteLine($"Ваш баланс пополнен на {input} рублей и теперь составляет {ClientController.GetBalance(сlient)} рублей.");
                        Thread.Sleep(6000);
                    }
                    break;

                    #endregion
                }
            }
        }
Example #41
0
        public static string getProduct(string textsearch, int typeinout)
        {
            List <ProductGetOut> ps = new List <ProductGetOut>();
            string username         = HttpContext.Current.Request.Cookies["usernameLoginSystem"].Value;
            var    acc = AccountController.GetByUsername(username);

            if (acc != null)
            {
                int AgentID = Convert.ToInt32(acc.AgentID);
                if (typeinout == 1)
                {
                    var products = ProductController.GetByTextSearchIsHidden(textsearch.Trim(), false);
                    if (products.Count > 0)
                    {
                        foreach (var item in products)
                        {
                            var productvariable = ProductVariableController.GetProductID(item.ID);
                            if (productvariable.Count > 0)
                            {
                                foreach (var pv in productvariable)
                                {
                                    string SKU   = pv.SKU.Trim().ToUpper();
                                    var    check = StockManagerController.GetBySKU(AgentID, SKU);
                                    if (check.Count > 0)
                                    {
                                        double total = PJUtils.TotalProductQuantityInstock(AgentID, SKU);
                                        if (total > 0)
                                        {
                                            var variables = ProductVariableValueController.GetByProductVariableID(pv.ID);
                                            if (variables.Count > 0)
                                            {
                                                string variablename  = "";
                                                string variablevalue = "";
                                                string variable      = "";

                                                foreach (var v in variables)
                                                {
                                                    variable      += v.VariableName.Trim() + ":" + v.VariableValue.Trim() + "|";
                                                    variablename  += v.VariableName.Trim() + "|";
                                                    variablevalue += v.VariableValue.Trim() + "|";
                                                }

                                                ProductGetOut p = new ProductGetOut();
                                                p.ID                    = pv.ID;
                                                p.ProductName           = item.ProductTitle;
                                                p.ProductVariable       = variable;
                                                p.ProductVariableName   = variablename;
                                                p.ProductVariableValue  = variablevalue;
                                                p.ProductType           = 2;
                                                p.ProductImage          = "<img src=\"" + Thumbnail.getURL(pv.Image, Thumbnail.Size.Small) + "\" alt=\"\" style=\"width: 50px\" />";
                                                p.ProductImageOrigin    = Thumbnail.getURL(pv.Image, Thumbnail.Size.Small);
                                                p.QuantityInstock       = total;
                                                p.QuantityInstockString = string.Format("{0:N0}", total);
                                                p.SKU                   = SKU;
                                                int supplierID = 0;
                                                if (pv.SupplierID != null)
                                                {
                                                    supplierID = pv.SupplierID.ToString().ToInt(0);
                                                }
                                                p.SupplierID = supplierID;
                                                string supplierName = "";
                                                if (!string.IsNullOrEmpty(pv.SupplierName))
                                                {
                                                    supplierName = pv.SupplierName;
                                                }
                                                p.SupplierName = supplierName;
                                                ps.Add(p);
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                string SKU   = item.ProductSKU.Trim().ToUpper();
                                var    check = StockManagerController.GetBySKU(AgentID, SKU);
                                if (check.Count > 0)
                                {
                                    double total = PJUtils.TotalProductQuantityInstock(AgentID, SKU);
                                    if (total > 0)
                                    {
                                        string variablename  = "";
                                        string variablevalue = "";
                                        string variable      = "";

                                        ProductGetOut p = new ProductGetOut();
                                        p.ID                   = item.ID;
                                        p.ProductName          = item.ProductTitle;
                                        p.ProductVariable      = variable;
                                        p.ProductVariableName  = variablename;
                                        p.ProductVariableValue = variablevalue;
                                        p.ProductType          = 1;
                                        var img = ProductImageController.GetFirstByProductID(item.ID);
                                        if (img != null)
                                        {
                                            p.ProductImage       = "<img src=\"" + Thumbnail.getURL(img.ProductImage, Thumbnail.Size.Small) + "\" alt=\"\" style=\"width: 50px\"  />";
                                            p.ProductImageOrigin = Thumbnail.getURL(img.ProductImage, Thumbnail.Size.Small);
                                        }
                                        else
                                        {
                                            p.ProductImage       = "";
                                            p.ProductImageOrigin = "";
                                        }
                                        p.QuantityInstock       = total;
                                        p.QuantityInstockString = string.Format("{0:N0}", total);
                                        p.SKU = SKU;
                                        int supplierID = 0;
                                        if (item.SupplierID != null)
                                        {
                                            supplierID = item.SupplierID.ToString().ToInt(0);
                                        }
                                        p.SupplierID = supplierID;
                                        string supplierName = "";
                                        if (!string.IsNullOrEmpty(item.SupplierName))
                                        {
                                            supplierName = item.SupplierName;
                                        }
                                        p.SupplierName = supplierName;
                                        ps.Add(p);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    var products = ProductController.GetBySKU(textsearch);
                    if (products != null)
                    {
                        var productvariable = ProductVariableController.GetProductID(products.ID);
                        if (productvariable.Count > 0)
                        {
                            foreach (var pv in productvariable)
                            {
                                string SKU   = pv.SKU.Trim().ToUpper();
                                var    check = StockManagerController.GetBySKU(AgentID, SKU);
                                if (check.Count > 0)
                                {
                                    double total = PJUtils.TotalProductQuantityInstock(AgentID, SKU);

                                    if (total > 0)
                                    {
                                        var variables = ProductVariableValueController.GetByProductVariableID(pv.ID);
                                        if (variables.Count > 0)
                                        {
                                            string variablename  = "";
                                            string variablevalue = "";
                                            string variable      = "";

                                            foreach (var v in variables)
                                            {
                                                variable      += v.VariableName.Trim() + ":" + v.VariableValue.Trim() + "|";
                                                variablename  += v.VariableName.Trim() + "|";
                                                variablevalue += v.VariableValue.Trim() + "|";
                                            }

                                            ProductGetOut p = new ProductGetOut();
                                            p.ID                    = pv.ID;
                                            p.ProductName           = products.ProductTitle;
                                            p.ProductVariable       = variable;
                                            p.ProductVariableName   = variablename;
                                            p.ProductVariableValue  = variablevalue;
                                            p.ProductType           = 2;
                                            p.ProductImage          = "<img src=\"" + Thumbnail.getURL(pv.Image, Thumbnail.Size.Small) + "\" alt=\"\" style=\"width: 50px\"  />";
                                            p.ProductImageOrigin    = Thumbnail.getURL(pv.Image, Thumbnail.Size.Small);
                                            p.QuantityInstock       = total;
                                            p.QuantityInstockString = string.Format("{0:N0}", total);
                                            p.SKU                   = SKU;
                                            int supplierID = 0;
                                            if (pv.SupplierID != null)
                                            {
                                                supplierID = pv.SupplierID.ToString().ToInt(0);
                                            }
                                            p.SupplierID = supplierID;
                                            string supplierName = "";
                                            if (!string.IsNullOrEmpty(pv.SupplierName))
                                            {
                                                supplierName = pv.SupplierName;
                                            }
                                            p.SupplierName = supplierName;
                                            ps.Add(p);
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            string SKU   = products.ProductSKU.Trim().ToUpper();
                            var    check = StockManagerController.GetBySKU(AgentID, SKU);
                            if (check.Count > 0)
                            {
                                double total = PJUtils.TotalProductQuantityInstock(AgentID, SKU);
                                if (total > 0)
                                {
                                    string variablename  = "";
                                    string variablevalue = "";
                                    string variable      = "";

                                    ProductGetOut p = new ProductGetOut();
                                    p.ID                   = products.ID;
                                    p.ProductName          = products.ProductTitle;
                                    p.ProductVariable      = variable;
                                    p.ProductVariableName  = variablename;
                                    p.ProductVariableValue = variablevalue;
                                    p.ProductType          = 1;
                                    var img = ProductImageController.GetFirstByProductID(products.ID);
                                    if (img != null)
                                    {
                                        p.ProductImage       = "<img src=\"" + Thumbnail.getURL(img.ProductImage, Thumbnail.Size.Small) + "\" alt=\"\" style=\"width: 50px\"  />";
                                        p.ProductImageOrigin = Thumbnail.getURL(img.ProductImage, Thumbnail.Size.Small);
                                    }
                                    else
                                    {
                                        p.ProductImage       = "";
                                        p.ProductImageOrigin = "";
                                    }
                                    p.SKU                   = SKU;
                                    p.QuantityInstock       = total;
                                    p.QuantityInstockString = string.Format("{0:N0}", total);
                                    int supplierID = 0;
                                    if (products.SupplierID != null)
                                    {
                                        supplierID = products.SupplierID.ToString().ToInt(0);
                                    }
                                    p.SupplierID = supplierID;
                                    string supplierName = "";
                                    if (!string.IsNullOrEmpty(products.SupplierName))
                                    {
                                        supplierName = products.SupplierName;
                                    }
                                    p.SupplierName = supplierName;
                                    ps.Add(p);
                                }
                            }
                        }
                    }
                    else
                    {
                        var productvariable = ProductVariableController.GetBySKU(textsearch);
                        if (productvariable != null)
                        {
                            string SKU   = productvariable.SKU.Trim().ToUpper();
                            var    check = StockManagerController.GetBySKU(AgentID, SKU);
                            if (check.Count > 0)
                            {
                                double total = PJUtils.TotalProductQuantityInstock(AgentID, SKU);
                                if (total > 0)
                                {
                                    var variables = ProductVariableValueController.GetByProductVariableID(productvariable.ID);

                                    if (variables.Count > 0)
                                    {
                                        string variablename  = "";
                                        string variablevalue = "";
                                        string variable      = "";

                                        foreach (var v in variables)
                                        {
                                            variable      += v.VariableName + ":" + v.VariableValue + "|";
                                            variablename  += v.VariableName + "|";
                                            variablevalue += v.VariableValue + "|";
                                        }

                                        ProductGetOut p = new ProductGetOut();
                                        p.ID = productvariable.ID;
                                        var product = ProductController.GetByID(Convert.ToInt32(productvariable.ProductID));
                                        if (product != null)
                                        {
                                            p.ProductName = product.ProductTitle;
                                        }
                                        p.ProductVariable      = variable;
                                        p.ProductVariableName  = variablename;
                                        p.ProductVariableValue = variablevalue;
                                        p.ProductType          = 2;
                                        p.ProductImage         = "<img src=\"" + Thumbnail.getURL(productvariable.Image, Thumbnail.Size.Small) + "\" alt=\"\" style=\"width:50px;\" />";
                                        p.ProductImageOrigin   = Thumbnail.getURL(productvariable.Image, Thumbnail.Size.Small);
                                        p.SKU                   = productvariable.SKU.Trim().ToUpper();
                                        p.QuantityInstock       = total;
                                        p.QuantityInstockString = string.Format("{0:N0}", total);
                                        int supplierID = 0;
                                        if (productvariable.SupplierID != null)
                                        {
                                            supplierID = productvariable.SupplierID.ToString().ToInt(0);
                                        }
                                        p.SupplierID = supplierID;
                                        string supplierName = "";
                                        if (!string.IsNullOrEmpty(productvariable.SupplierName))
                                        {
                                            supplierName = productvariable.SupplierName;
                                        }
                                        p.SupplierName = supplierName;
                                        ps.Add(p);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            return(serializer.Serialize(ps));
        }
 protected void BindGridList()
 {
     GridView1.DataSource = ProductController.GetAllProducts();
     GridView1.DataBind();
 }
        private ProductController CreateController()
        {
            var controller = new ProductController(
                _promotionServiceMock.Object,
                _contentLoaderMock.Object,
                _priceServiceMock.Object,
                _currentMarketMock.Object,
                _currencyserviceMock.Object,
                _relationRepositoryMock.Object,
                _appContextFacadeMock.Object,
                _urlResolverMock.Object,
                _filterPublished,
                () => _preferredCulture,
                () => _isInEditMode);

            controller.ControllerContext = new ControllerContext(_httpContextBaseMock.Object, new RouteData(), controller);

            return controller;
        }
Example #44
0
        private void UpdateProductList(int categoryID)
        {
            grdProducts.DataSource = null;

            // Get current category
            //int categoryID = int.Parse(cmbCategory.SelectedValue);
            if (categoryID >= 0)
            {
                ProductController controller = new ProductController();
                //ArrayList productList = controller.GetCategoryProducts(categoryID, true);
                String searchTerm = this.tbProductFilter.Text;
                //ArrayList productList = controller.GetSearchedProducts(-1, searchTerm, true);
                bool archived = false;
                if (int.Parse(this.ddArchive.SelectedValue) == 1) archived = true;
                ArrayList productList = controller.GetSearchedProducts(-1, searchTerm, archived);

                if (productList.Count > 0)
                {
                    // Has page index been initialized?
                    if (_nav.PageIndex == Null.NullInteger)
                    {
                        _nav.PageIndex = 0;
                    }

                    // Update the grid
                    grdProducts.PageSize = 20;
                    grdProducts.AllowPaging = true;
                    grdProducts.DataSource = productList;
                    grdProducts.CurrentPageIndex = _nav.PageIndex;
                    grdProducts.DataBind();
                }
            }
        }
        public void Can_Send_Pagination_View_Model()
        {
            //Arrange
            Mock<IProductsRepository> mockRepo = new Mock<IProductsRepository>();
            mockRepo.Setup(m => m.Products).Returns(new Product[]
                {
                    new Product {ProductID = 1, Name = "P1"},
                    new Product {ProductID = 2, Name = "P2"},
                    new Product {ProductID = 3, Name = "P3"},
                    new Product {ProductID = 4, Name = "P4"},
                    new Product {ProductID = 5, Name = "P5"}
                });

            //Arrange
            ProductController controller = new ProductController(mockRepo.Object);
            controller.PageSize = 3;

            //Act
            ProductListViewModel result = (ProductListViewModel)controller.List(null, 2).Model;

            //Assert
            PagingInfo pageInfo = result.PagingInfo;
            Assert.AreEqual(pageInfo.CurrentPage, 2);
            Assert.AreEqual(pageInfo.ItemsPerPage, 3);
            Assert.AreEqual(pageInfo.TotalItems, 5);
            Assert.AreEqual(pageInfo.TotalPages, 2);
        }
 private void buttonAddProduct_Click(object sender, EventArgs e)
 {
     //`var c = (Category)comboBoxCategory.SelectedItem;
     ProductController.AddProduct(textBoxProductId.Text, textBoxProductName.Text, textBoxProductPrice.Text, textBoxProductQuantaty.Text, comboBoxCategory.Text);
     dataGridViewAllProducts.DataSource = ProductController.GetAllProduct();
 }
        private ProductController CreateController()
        {
            var controller = new ProductController(
                _mockPromotionService.Object,
                _mockContentLoader.Object,
                _mockPriceService.Object,
                _mockCurrentMarket.Object,
                _mockCurrencyservice.Object,
                _mockRelationRepository.Object,
                _appContextFacade.Object,
                _mockUrlResolver.Object,
                _filterPublished,
                () => _preferredCulture,
                () => _isInEditMode);

            controller.ControllerContext = new ControllerContext(_mockHttpContextBase.Object, new RouteData(), controller);

            return controller;
        }
Example #48
0
        public void InserOrder1(string AgentAPIID, string AgentAPICode, int OrderType, string CustomerName, string CustomerPhone, string CustomerEmail,
                                string CustomerAddress, double TotalPrice, int PaymentStatus, int ExcuteStatus, List <ProductOrder> ListProduct, string CreatedBy, string username, string password)
        {
            var rs = new ResponseClass();

            if (Login(username, password))
            {
                DateTime currentDate = DateTime.Now;
                var      agent       = AgentController.GetByAPICodeID(AgentAPIID, AgentAPICode);
                if (agent != null)
                {
                    int    AgentID     = agent.ID;
                    int    CustomerID  = 0;
                    string AdditionFee = "0";
                    string DisCount    = "0";
                    var    checkphone  = CustomerController.GetByPhone(CustomerPhone);
                    if (checkphone != null)
                    {
                        CustomerID = checkphone.ID;
                    }
                    else
                    {
                        string kq = CustomerController.Insert(CustomerName, CustomerPhone, CustomerAddress, CustomerEmail, 0, 0, currentDate, CreatedBy, false, "", "", "", "", "");
                        if (kq.ToInt(0) > 0)
                        {
                            CustomerID = kq.ToInt(0);
                        }
                    }
                    bool IsHidden = false;
                    int  Wayin    = 2;

                    var ret = OrderController.Insert(AgentID, OrderType, AdditionFee, DisCount, CustomerID, CustomerName, CustomerPhone, CustomerAddress,
                                                     CustomerEmail, TotalPrice.ToString(), TotalPrice.ToString(), PaymentStatus, ExcuteStatus, IsHidden, Wayin, currentDate, CreatedBy, 0, 0, "0", 0, 0, DateTime.Now.ToString(), 0, 0, 0, 0, "", 0, 1);
                    int OrderID = ret.ID;
                    if (OrderID > 0)
                    {
                        if (ListProduct.Count > 0)
                        {
                            foreach (var p in ListProduct)
                            {
                                int ProductID         = 0;
                                int ProductVariableID = 0;

                                int    ID          = p.ID;
                                string SKU         = p.SKU;
                                int    producttype = p.ProductType;
                                if (producttype == 1)
                                {
                                    ProductID         = ID;
                                    ProductVariableID = 0;
                                }
                                else
                                {
                                    ProductID         = 0;
                                    ProductVariableID = ID;
                                }

                                string ProductVariableName  = p.ProductVariableName;
                                string ProductVariableValue = p.ProductVariableValue;
                                double Quantity             = Convert.ToDouble(p.Quantity);
                                string ProductName          = p.ProductName;
                                string ProductImageOrigin   = p.ProductImageOrigin;
                                double ProductPrice         = p.Price;
                                string ProductVariableSave  = p.ProductVariableDescription;


                                if (ExcuteStatus == 2 && PaymentStatus == 3)
                                {
                                    OrderDetailController.Insert(AgentID, OrderID, SKU, ProductID, ProductVariableID, ProductVariableSave, Quantity,
                                                                 ProductPrice, 1, 0, producttype, currentDate, CreatedBy, true);
                                    if (producttype == 1)
                                    {
                                        StockManagerController.Insert(
                                            new tbl_StockManager()
                                        {
                                            AgentID           = AgentID,
                                            ProductID         = ProductID,
                                            ProductVariableID = 0,
                                            Quantity          = Quantity,
                                            QuantityCurrent   = 0,
                                            Type        = 2,
                                            NoteID      = String.Empty,
                                            OrderID     = OrderID,
                                            Status      = 3,
                                            SKU         = SKU,
                                            CreatedDate = currentDate,
                                            CreatedBy   = CreatedBy,
                                            MoveProID   = 0,
                                            ParentID    = ProductID
                                        });
                                    }
                                    else
                                    {
                                        int    parentID  = 0;
                                        string parentSKU = "";
                                        var    productV  = ProductVariableController.GetByID(ProductVariableID);
                                        if (productV != null)
                                        {
                                            parentSKU = productV.ParentSKU;
                                        }
                                        if (!string.IsNullOrEmpty(parentSKU))
                                        {
                                            var product = ProductController.GetBySKU(parentSKU);
                                            if (product != null)
                                            {
                                                parentID = product.ID;
                                            }
                                        }
                                        StockManagerController.Insert(
                                            new tbl_StockManager
                                        {
                                            AgentID           = AgentID,
                                            ProductID         = 0,
                                            ProductVariableID = ProductVariableID,
                                            Quantity          = Quantity,
                                            QuantityCurrent   = 0,
                                            Type        = 2,
                                            NoteID      = String.Empty,
                                            OrderID     = OrderID,
                                            Status      = 3,
                                            SKU         = SKU,
                                            CreatedDate = currentDate,
                                            CreatedBy   = CreatedBy,
                                            MoveProID   = 0,
                                            ParentID    = parentID,
                                        });
                                    }
                                }
                                else
                                {
                                    OrderDetailController.Insert(AgentID, OrderID, SKU, ProductID, ProductVariableID, ProductVariableSave, Quantity,
                                                                 ProductPrice, 1, 0, producttype, currentDate, CreatedBy, false);
                                }
                            }
                        }
                        rs.Code    = APIUtils.GetResponseCode(APIUtils.ResponseCode.SUCCESS);
                        rs.Status  = APIUtils.ResponseMessage.Success.ToString();
                        rs.Message = "Tạo mới đơn hàng thành công";
                    }
                    else
                    {
                        rs.Code    = APIUtils.GetResponseCode(APIUtils.ResponseCode.NotFound);
                        rs.Status  = APIUtils.ResponseMessage.Error.ToString();
                        rs.Message = "Có lỗi trong quá trình tạo mới đơn hàng, vui lòng thử lại sau.";
                    }
                }
                else
                {
                    rs.Code    = APIUtils.GetResponseCode(APIUtils.ResponseCode.NotFound);
                    rs.Status  = APIUtils.ResponseMessage.Error.ToString();
                    rs.Message = "Không tồn tại thông tin đại lý";
                }
            }
            else
            {
                rs.Code   = APIUtils.GetResponseCode(APIUtils.ResponseCode.FAILED);
                rs.Status = APIUtils.ResponseMessage.Fail.ToString();
            }

            Context.Response.ContentType = "application/json";
            Context.Response.Write(JsonConvert.SerializeObject(rs, Formatting.Indented));
            Context.Response.Flush();
            Context.Response.End();
        }
Example #49
0
    void Awake()
    {
        productSelectionDic.Add(0, 2);
        productSelectionDic.Add(1, 0);
        productSelectionDic.Add(2, 4);
        productSelectionDic.Add(3, 1);
        productSelectionDic.Add(4, 3);
        productSelectionDic.Add(5, 6);
        productSelectionDic.Add(6, 8);
        productSelectionDic.Add(7, 7);
        productSelectionDic.Add(8, 5);

        // Add event handlers
        //		ProductController.OnSuccess += PurchaseSuccessful;
        //		ProductController.OnProductLoaded += OnProductLoaded;
        ProductController.OnCarPurchased += OnCarPurchased;
        ProductController.OnFailedToPurchase += OnFailedToPurchase;
        ProductController.OnTalentOpened += OnTalentOpened;
        ProductController.OnFailedToOpenTalent += OnFailedToOpenTalent;

        productController = FindObjectOfType(typeof(ProductController)) as ProductController;
    }
Example #50
0
 private void ProductControl_Load(object sender, EventArgs e)
 {
     m_Controller = new ProductController(this);
     m_Controller.Initialize();
 }
Example #51
0
        public static string copyProductInfo(int id)
        {
            var           product = ProductController.GetByID(id);
            StringBuilder html    = new StringBuilder();

            if (product != null)
            {
                html.AppendLine("<p>" + product.ProductSKU + " - " + product.ProductTitle + "</p>\r\n");
                html.AppendLine("<p>📌 Sỉ: " + (product.Regular_Price / 1000).ToString() + "k</p>\r\n");
                html.AppendLine("<p>📌 Lẻ: " + (product.Retail_Price / 1000).ToString() + "k</p>\r\n");

                if (!string.IsNullOrEmpty(product.Materials))
                {
                    html.AppendLine("<p>🔖 " + (product.CategoryID == 44 ? "" : "Chất liệu: ") + product.Materials + "</p>\r\n");
                }

                if (!string.IsNullOrEmpty(product.ProductContent))
                {
                    string content = Regex.Replace(product.ProductContent, @"<img\s[^>]*>(?:\s*?</img>)?", "").ToString();
                    html.AppendLine("<p>🔖 " + content + "</p>\r\n");
                }

                // liệt kê thuộc tính sản phẩm

                List <ProductVariable> variableTemp = new List <ProductVariable>();

                List <tbl_ProductVariable> v = new List <tbl_ProductVariable>();

                v = ProductVariableController.SearchProductID(id, "");

                string Variable = "";
                if (v.Count > 0)
                {
                    for (int i = 0; i < v.Count; i++)
                    {
                        var item  = v[i];
                        var value = ProductVariableValueController.GetByProductVariableIDSortByName(item.ID);
                        if (value != null)
                        {
                            for (int j = 0; j < value.Count; j++)
                            {
                                variableTemp.Add(new ProductVariable()
                                {
                                    VariableName = value[j].VariableName, VariableValue = value[j].VariableValue
                                });
                            }
                        }
                    }
                    var vari = variableTemp
                               .GroupBy(x => new { x.VariableName, x.VariableValue })
                               .Select(x => new { VariableName = x.Key.VariableName, VariableValue = x.Key.VariableValue })
                               .OrderBy(x => x.VariableName)
                               .ToList();

                    string stringVariable = vari[0].VariableName;

                    Variable = "<p><strong>📚 " + vari[0].VariableName + "</strong>: ";

                    int count = 0;

                    for (int y = 0; y < vari.Count; y++)
                    {
                        if (stringVariable == vari[y].VariableName)
                        {
                            if (vari[y].VariableValue.IndexOf("Mẫu") >= 0)
                            {
                                count = count + 1;

                                if (y == (vari.Count - 1))
                                {
                                    Variable += count.ToString() + " mẫu khác nhau";
                                }
                            }
                            else
                            {
                                Variable += vari[y].VariableValue + "; ";
                            }
                        }
                        else
                        {
                            if (count > 0)
                            {
                                Variable += count.ToString() + " mẫu khác nhau";
                            }
                            Variable      += "</p>\r\n";
                            Variable      += "<p><strong>📐 " + vari[y].VariableName + "</strong>: " + vari[y].VariableValue + "; ";
                            stringVariable = vari[y].VariableName;
                        }
                    }

                    html.AppendLine(Variable);
                }

                html.AppendLine("<p></p>\r\n");
            }

            return(html.ToString());
        }
Example #52
0
        public void LoadData()
        {
            DateTime year       = new DateTime(2018, 6, 22);
            DateTime DateConfig = year;

            DateTime fromDate = DateConfig;
            DateTime toDate   = DateTime.Now;

            if (!String.IsNullOrEmpty(Request.QueryString["fromdate"]))
            {
                fromDate = Convert.ToDateTime(Request.QueryString["fromdate"]);
            }

            if (!String.IsNullOrEmpty(Request.QueryString["todate"]))
            {
                toDate = Convert.ToDateTime(Request.QueryString["todate"]).AddDays(1).AddMinutes(-1);
            }

            rFromDate.SelectedDate = fromDate;
            rFromDate.MinDate      = DateConfig;
            rFromDate.MaxDate      = DateTime.Now;

            rToDate.SelectedDate = toDate;
            rToDate.MinDate      = DateConfig;
            rToDate.MaxDate      = DateTime.Now;

            string TextSearch  = String.Empty;
            int    CategoryID  = 0;
            int    StockStatus = 0;
            string strColor    = String.Empty;
            string strSize     = String.Empty;
            int    Page        = 1;
            // add filter quantity
            string Quantity     = String.Empty;
            int    QuantityFrom = 0;
            int    QuantityTo   = 0;

            string orderBy = String.Empty;
            int    tag     = 0;

            if (Request.QueryString["textsearch"] != null)
            {
                TextSearch = Request.QueryString["textsearch"].Trim();
            }
            if (Request.QueryString["stockstatus"] != null)
            {
                StockStatus = Request.QueryString["stockstatus"].ToInt();
            }
            if (Request.QueryString["categoryid"] != null)
            {
                CategoryID = Request.QueryString["categoryid"].ToInt();
            }
            // Add filter valiable value
            if (Request.QueryString["color"] != null)
            {
                strColor = Request.QueryString["color"].Trim();
            }
            if (Request.QueryString["size"] != null)
            {
                strSize = Request.QueryString["size"].Trim();
            }
            if (Request.QueryString["Page"] != null)
            {
                Page = Request.QueryString["Page"].ToInt();
                if (Page < 1)
                {
                    Page = 1;
                }
            }
            // add filter quantity
            if (Request.QueryString["quantityfilter"] != null)
            {
                Quantity = Request.QueryString["quantityfilter"];

                if (Quantity == "greaterthan")
                {
                    QuantityFrom = Request.QueryString["quantity"].ToInt();
                }
                else if (Quantity == "lessthan")
                {
                    QuantityTo = Request.QueryString["quantity"].ToInt();
                }
                else if (Quantity == "between")
                {
                    QuantityFrom = Request.QueryString["quantitymin"].ToInt();
                    QuantityTo   = Request.QueryString["quantitymax"].ToInt();
                }
            }
            if (Request.QueryString["orderby"] != null)
            {
                orderBy = Request.QueryString["orderby"];
            }
            if (Request.QueryString["tag"] != null)
            {
                tag = Request.QueryString["tag"].ToInt();
            }

            txtSearchProduct.Text        = TextSearch;
            ddlCategory.SelectedValue    = CategoryID.ToString();
            ddlStockStatus.SelectedValue = StockStatus.ToString();
            // add filter quantity
            ddlQuantityFilter.SelectedValue = Quantity.ToString();
            if (Quantity == "greaterthan")
            {
                txtQuantity.Text    = QuantityFrom.ToString();
                txtQuantityMin.Text = "0";
                txtQuantityMax.Text = "0";
            }
            else if (Quantity == "lessthan")
            {
                txtQuantity.Text    = QuantityTo.ToString();
                txtQuantityMin.Text = "0";
                txtQuantityMax.Text = "0";
            }
            else if (Quantity == "between")
            {
                txtQuantity.Text    = "0";
                txtQuantityMin.Text = QuantityFrom.ToString();
                txtQuantityMax.Text = QuantityTo.ToString();
            }

            // Add filter valiable value
            ddlColor.SelectedValue = strColor;
            ddlSize.SelectedValue  = strSize;

            ddlTag.SelectedValue     = tag.ToString();
            ddlOrderBy.SelectedValue = orderBy;

            // Create order filter
            var filter = new ProductFilterModel()
            {
                category     = CategoryID,
                search       = TextSearch,
                color        = strColor,
                size         = strSize,
                stockStatus  = StockStatus,
                quantity     = Quantity,
                quantityFrom = QuantityFrom,
                quantityTo   = QuantityTo,
                fromDate     = fromDate,
                toDate       = toDate,
                showHomePage = "",
                webPublish   = "",
                preOrder     = "",
                tag          = tag,
                orderBy      = orderBy
            };
            // Create pagination
            var page = new PaginationMetadataModel()
            {
                currentPage = Page,
                pageSize    = 20
            };

            List <ProductSQL> a = new List <ProductSQL>();

            a = ProductController.GetAllSql(filter, ref page);

            pagingall(a, page);

            ltrNumberOfProduct.Text = page.totalCount.ToString();
        }
Example #53
0
 protected bool HasTOC_Html(String productId)
 {
     ProductController productController = new ProductController();
     productInfo = productController.GetProduct(Int32.Parse(productId));
     if (productInfo.TOC_Html != "")
         return true;
     else
         return false;
 }
Example #54
0
 public void Init()
 {
     controller = new ProductController(new ProductService(new ProductRepository()));
 }
Example #55
0
        private ArrayList GetPopularProducts(int categoryID, ArrayList products)
        {
            CategoryController categoryController = new CategoryController();
            ProductController productController = new ProductController();

            CategoryInfo category = categoryController.GetCategory(categoryID);

            foreach (ProductInfo product in productController.GetPopularProducts(PortalId, categoryID, false))
            {
                products.Add(product);
            }

            foreach (CategoryInfo childCategory in categoryController.GetCategories(PortalId, false, categoryID))
            {
                if (childCategory.CategoryID != Null.NullInteger)
                {
                    GetPopularProducts(childCategory.CategoryID, products);
                }
            }

            return products;
        }
Example #56
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            DateTime currentDate = DateTime.Now;
            int      AgentID     = 0;
            string   username    = Request.Cookies["userLoginSystem"].Value;

            if (!string.IsNullOrEmpty(username))
            {
                var a = AccountController.GetByUsername(username);
                if (a != null)
                {
                    AgentID = Convert.ToInt32(a.AgentID);
                    string phone = hdfPhone.Value;
                    if (!string.IsNullOrEmpty(phone))
                    {
                        var cust = CustomerController.GetByPhone(phone);
                        if (cust != null)
                        {
                            int    custID        = cust.ID;
                            string totalprice    = hdfTotalPrice.Value;
                            string totalquantity = hdfTotalQuantity.Value;
                            string totalrefund   = hdfTotalRefund.Value;
                            var    agent         = AgentController.GetByID(AgentID);
                            string agentName     = "";
                            if (agent != null)
                            {
                                agentName = agent.AgentName;
                            }
                            //insert ddlstatus, refundnote
                            int    status      = ddlRefundStatus.SelectedValue.ToInt();
                            string RefundsNote = txtRefundsNote.Text;
                            int    rID         = RefundGoodController.Insert(AgentID, totalprice, status, custID, Convert.ToDouble(totalquantity),
                                                                             totalrefund, agentName, cust.CustomerName, cust.CustomerPhone, currentDate, username, RefundsNote);
                            if (rID > 0)
                            {
                                string   listString = hdfListProduct.Value;
                                string[] items      = listString.Split('|');
                                if (items.Length - 1 > 0)
                                {
                                    for (int i = 0; i < items.Length - 1; i++)
                                    {
                                        string[] element                 = items[i].Split(';');
                                        var      sku                     = element[0];
                                        var      orderID                 = element[1].ToInt(0);
                                        var      orderDetailID           = element[2];
                                        var      ProductName             = element[3];
                                        var      GiavonPerProduct        = Convert.ToDouble(element[5]);
                                        var      SoldPricePerProduct     = Convert.ToDouble(element[6]);
                                        var      DiscountPricePerProduct = Convert.ToDouble(element[7]);
                                        var      quantity                = Convert.ToDouble(element[10]);
                                        var      quantityMax             = Convert.ToDouble(element[8]);
                                        var      ProductType             = element[4].ToInt(1);
                                        var      RefundType              = element[9].ToInt(1);
                                        var      RefundFeePerProduct     = Convert.ToDouble(element[11]);
                                        var      TotalPriceRow           = element[12];
                                        var      PriceNotFeeRefund       = SoldPricePerProduct * quantity;
                                        var      rdTotalRefundFee        = RefundFeePerProduct * quantity;

                                        int rdID = RefundGoodDetailController.Insert(rID, AgentID, orderID, ProductName, custID, sku, quantity,
                                                                                     quantityMax, PriceNotFeeRefund.ToString(), ProductType, true, RefundType, RefundFeePerProduct.ToString(),
                                                                                     rdTotalRefundFee.ToString(), GiavonPerProduct.ToString(), DiscountPricePerProduct.ToString(), SoldPricePerProduct.ToString(),
                                                                                     TotalPriceRow, currentDate, username);
                                        if (rdID > 0)
                                        {
                                            if (RefundType < 3)
                                            {
                                                int    typeRe = 0;
                                                string note   = "";
                                                if (RefundType == 1)
                                                {
                                                    note   = "Đổi size";
                                                    typeRe = 8;
                                                }
                                                else if (RefundType == 2)
                                                {
                                                    note   = "Đổi sản phẩm";
                                                    typeRe = 9;
                                                }
                                                if (ProductType == 1)
                                                {
                                                    var product = ProductController.GetBySKU(sku);
                                                    if (product != null)
                                                    {
                                                        int    productID          = product.ID;
                                                        string ProductImageOrigin = "";
                                                        var    ProductImage       = ProductImageController.GetFirstByProductID(product.ID);
                                                        if (ProductImage != null)
                                                        {
                                                            ProductImageOrigin = ProductImage.ProductImage;
                                                        }
                                                        StockManagerController.Insert(
                                                            new tbl_StockManager {
                                                            AgentID           = AgentID,
                                                            ProductID         = productID,
                                                            ProductVariableID = 0,
                                                            Quantity          = quantity,
                                                            QuantityCurrent   = 0,
                                                            Type        = 1,
                                                            NoteID      = note,
                                                            OrderID     = orderID,
                                                            Status      = typeRe,
                                                            SKU         = sku,
                                                            CreatedDate = currentDate,
                                                            CreatedBy   = username,
                                                            MoveProID   = 0,
                                                            ParentID    = productID,
                                                        });
                                                    }
                                                }
                                                else
                                                {
                                                    string ProductVariableName  = "";
                                                    string ProductVariableValue = "";
                                                    string ProductVariable      = "";
                                                    int    parentID             = 0;
                                                    string parentSKU            = "";
                                                    string ProductImageOrigin   = "";
                                                    int    ID = 0;

                                                    var productvariable = ProductVariableController.GetBySKU(sku);
                                                    if (productvariable != null)
                                                    {
                                                        ID = productvariable.ID;
                                                        ProductImageOrigin = productvariable.Image;
                                                        parentSKU          = productvariable.ParentSKU;
                                                        var variables = ProductVariableValueController.GetByProductVariableID(productvariable.ID);
                                                        if (variables.Count > 0)
                                                        {
                                                            foreach (var v in variables)
                                                            {
                                                                ProductVariable      += v.VariableName.Trim() + ":" + v.VariableValue.Trim() + "|";
                                                                ProductVariableName  += v.VariableName + "|";
                                                                ProductVariableValue += v.VariableValue + "|";
                                                            }
                                                        }
                                                    }
                                                    if (!string.IsNullOrEmpty(parentSKU))
                                                    {
                                                        var product = ProductController.GetBySKU(parentSKU);
                                                        if (product != null)
                                                        {
                                                            parentID = product.ID;
                                                        }
                                                    }


                                                    StockManagerController.Insert(
                                                        new tbl_StockManager {
                                                        AgentID           = AgentID,
                                                        ProductID         = 0,
                                                        ProductVariableID = ID,
                                                        Quantity          = quantity,
                                                        QuantityCurrent   = 0,
                                                        Type        = 1,
                                                        NoteID      = note,
                                                        OrderID     = orderID,
                                                        Status      = typeRe,
                                                        SKU         = sku,
                                                        CreatedDate = currentDate,
                                                        CreatedBy   = username,
                                                        MoveProID   = 0,
                                                        ParentID    = parentID,
                                                    });
                                                }
                                            }
                                        }
                                        PJUtils.ShowMessageBoxSwAlertCallFunction("Tạo đơn hàng đổi trả thành công", "s", true, "redirectTo(" + rID + ")", Page);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Example #57
0
        private ArrayList GetSelectedProducts(int categoryID, int categoryID1, int categoryID2, int categoryID3, ArrayList products)
        {
            ProductController productController = new ProductController();

            foreach (ProductInfo product in productController.GetSelectedProducts(categoryID, categoryID1, categoryID2, categoryID3, false))
            {
                products.Add(product);
            }

            return products;
        }
Example #58
0
 private void IsolateController()
 {
     _dto        = Isolate.Fake.Instance <ProductDto>();
     _controller = new ProductController();
 }
Example #59
0
        public static string getAllProductImage1MB(string sku)
        {
            List <string> result = new List <string>();

            string rootPath          = HostingEnvironment.ApplicationPhysicalPath;
            string uploadsImagesPath = rootPath + "/uploads/images/";
            var    product           = ProductController.GetBySKU(sku);

            if (product != null)
            {
                List <string> images = new List <string>();

                // lấy ảnh đại diện
                string imgAdd = product.ProductImage;
                if (File.Exists(uploadsImagesPath + imgAdd))
                {
                    images.Add(imgAdd);
                }

                // lấy ảnh sản phẩm từ thư viện
                var imageProduct = ProductImageController.GetByProductID(product.ID);
                if (imageProduct != null)
                {
                    foreach (var img in imageProduct)
                    {
                        imgAdd = img.ProductImage;
                        if (File.Exists(uploadsImagesPath + imgAdd))
                        {
                            images.Add(imgAdd);
                        }
                    }
                }

                // lấy ảnh sản phẩm từ biến thể
                var variable = ProductVariableController.GetByParentSKU(product.ProductSKU);
                if (variable != null)
                {
                    foreach (var v in variable)
                    {
                        if (!String.IsNullOrEmpty(v.Image))
                        {
                            imgAdd = v.Image;
                            if (File.Exists(uploadsImagesPath + imgAdd))
                            {
                                images.Add(imgAdd);
                            }
                        }
                    }
                }

                // lọc hình trùng lặp
                images = images.Distinct().ToList();

                if (images.Count() > 0)
                {
                    for (int i = 0; i < images.Count - 1; i++)
                    {
                        for (int y = i + 1; y < images.Count; y++)
                        {
                            string img1 = Thumbnail.getURL(images[i], Thumbnail.Size.Micro);
                            string img2 = Thumbnail.getURL(images[y], Thumbnail.Size.Micro);

                            // so sánh 2 hình và lọc hình trùng lặp
                            Bitmap bmp1 = (Bitmap)Bitmap.FromFile(rootPath + img1);
                            Bitmap bmp2 = (Bitmap)Bitmap.FromFile(rootPath + img2);
                            if (CompareBitmapsLazy(bmp1, bmp2))
                            {
                                images.RemoveAt(y);
                                y--;
                            }
                        }
                    }
                }

                // lấy hình dưới 1MB
                for (int i = 0; i < images.Count; i++)
                {
                    string item = uploadsImagesPath + images[i];
                    var    size = new System.IO.FileInfo(item).Length;
                    if (size > 1000000)
                    {
                        // kiểm tra size hình rộng 600px
                        item = uploadsImagesPath + "600/" + images[i];
                        if (File.Exists(item))
                        {
                            size = new System.IO.FileInfo(item).Length;
                            if (size > 1000000)
                            {
                                result.Add(Thumbnail.getURL(images[i], Thumbnail.Size.Large));
                            }
                            else
                            {
                                result.Add(Thumbnail.getURL(images[i], Thumbnail.Size.XLarge));
                            }
                        }
                        else
                        {
                            result.Add(Thumbnail.getURL(images[i], Thumbnail.Size.Large));
                        }
                    }
                    else
                    {
                        result.Add(Thumbnail.getURL(images[i], Thumbnail.Size.Source));
                    }
                }
            }

            JavaScriptSerializer serializer = new JavaScriptSerializer();

            return(serializer.Serialize(result.ToList()));
        }
Example #60
0
 public ProductControllerTest()
 {
     _productsService   = new ProductsServiceFake();
     _productController = new ProductController(_productsService, DtoProfile.CreateMapper());
 }