Summary description for ProductData
Exemplo n.º 1
0
 public Product(ProductData.DOM.Product domProduct, Catalog domCatalog, string langCode, string currency)
 {
     _domProduct = domProduct;
     _domCatalog = domCatalog;
     _langCode = langCode;
     _currency = currency;
 }
        public ActionResult StockList(int page, int rows, string sort, string order, string search)
        {
            string where = "";
            string orderby = Utilities.OrdeerBy(sort, order);
            if (!string.IsNullOrEmpty(search))
            {
                where = Utilities.Resolve(search);
                if (where.Length > 0)
                {
                    where = " where " + where;
                }
            }
            IList<object[]> objList = NSession.CreateSQLQuery("select SKU,OldSKU,ProductName as Title,Price,(select COUNT(1) from SKUCode where IsOut=0 and SKU=P.SKU ) as Qty,(Price*(select COUNT(1) from SKUCode where IsOut=0 and SKU=P.SKU )) as TotalPrice from Products P " + where + " " + orderby)
                .SetFirstResult(rows * (page - 1))
                .SetMaxResults(rows)
                .List<object[]>();
            List<ProductData> list = new List<ProductData>();
            foreach (object[] objectse in objList)
            {
                ProductData pd = new ProductData();
                pd.SKU = objectse[0].ToString();
                pd.Title = objectse[2].ToString();
                pd.Price = Convert.ToDouble(objectse[3]);
                pd.Qty = Convert.ToInt32(objectse[4]);
                pd.TotalPrice = Math.Round(Convert.ToDouble(objectse[5]), 2);

                list.Add(pd);
            }
            object count = NSession.CreateQuery("select count(Id) from ProductType " + where).UniqueResult();
            object total = NSession.CreateSQLQuery("select SUM(qty) from (select (Price*(select COUNT(1) from SKUCode where IsOut=0 and SKU=P.SKU)) as Qty from Products P " + where + ") as t").UniqueResult();
            List<object> footers = new List<object>();
            footers.Add(new { TotalPrice = Math.Round(Convert.ToDouble(total), 2), SKU = "合计:" });
            return Json(new { total = count, rows = list, footer = footers });
        }
    public void UpdateList(ProductData[] itemsInInventoy)
    {
        for (int i = 0; i < elements.Count; i++)
        {
            if(i < itemsInInventoy.Length)
            {
                //Debug.Log((i < itemsInInventoy.Length) + " - " + itemsInInventoy[i].ProductSprite);
                elements[i].sprite = itemsInInventoy[i].ProductSprite;
                elements[i].enabled = true;

                if (elementTexts != null)
                {
                    if(i < elementTexts.Length)
                    {
                        if(itemsInInventoy[i].isCollect)
                        {
                            elementTexts[i].text = itemsInInventoy[i].scoreValue + " Mio. $";
                            elementTexts[i].color = Color.green;
                        }
                        else
                        {
                            elementTexts[i].text = itemsInInventoy[i].scoreValue + " Mio. $";
                            elementTexts[i].color = Color.red;
                        }
                    }
                }
            }
            else
            {
                elements[i].enabled = false;
                elements[i].sprite = null;
            }
        }
    }
Exemplo n.º 4
0
		private static void ReceivedProductInformation(ProductData[] products)
		{
			Assert.AreEqual("testId", products[0].Id);
			Assert.AreEqual("testTitle", products[0].Title);
			Assert.AreEqual("testDescription", products[0].Description);
			Assert.AreEqual(1.99m, products[0].Price);
			Assert.IsTrue(products[0].IsValid);
		}
Exemplo n.º 5
0
            private static ProductData ExtractProductDataFromReader(IDataReader reader)
            {
                ProductData pd = new ProductData();
                pd.sku = reader["sku"].ToString();
                pd.name = reader["name"].ToString();
                pd.price =Convert.ToInt32(reader["price"]);

                return pd;
            }
Exemplo n.º 6
0
 public Variant(ProductData.DOM.Variant domVariant, ProductData.DOM.Product domProduct, Catalog domCatalog,
     Item item, string langCode)
 {
     _domVariant = domVariant;
     _domProduct = domProduct;
     _domCatalog = domCatalog;
     _item = item;
     _langCode = langCode;
 }
Exemplo n.º 7
0
            private static SqlCommand BuildInsertionCommand(ProductData pd)
            {
                string sql= "INSERT INTO Products VALUES (@sku, @name, @price)";
                SqlCommand command = new SqlCommand(sql, connection);
                command.Parameters.Add("@sku", pd.sku);
                command.Parameters.Add("@name", pd.name);
                command.Parameters.Add("@price", pd.price);

                return command;
            }
    public void Initalize(ProductData _productData)
    {
        this.productData = _productData;
        picture.sprite = _productData.ProductSprite;

        //spriteRenderer = GetComponent<SpriteRenderer>();
        //spriteRenderer.sprite = _productData.ProductSprite;

        //transform.localScale = new Vector3(0.1f, 0.1f, 1.0f);
        //borderSpriteRenderer.transform.localScale;
        // new Vector3(1 * (spriteRenderer.sprite.rect.width / spriteRenderer.sprite.pixelsPerUnit), 1 * (spriteRenderer.sprite.rect.height / spriteRenderer.sprite.pixelsPerUnit), 1);
    }
 public void UpdateList(ProductData[] itemsToCollect)
 {
     for (int i = 0; i < elements.Length; i++)
     {
         if(itemsToCollect[i].isCollect)
         {
             elements[i].text = System.String.Format(" - <color=#00ff00>{0}</color>", itemsToCollect[i].Title);
         }
         else
         {
             elements[i].text = System.String.Format("- {0}", itemsToCollect[i].Title);
         }
     }
 }
        private void CheckAsserts(List<Product> allProducts, ProductData data, double currencyRate = 1)
        {
            Assert.AreEqual(allProducts[0].Id, data.LawnMowers.First().Id);
            Assert.AreEqual(allProducts[0].Name, data.LawnMowers.First().Name);
            Assert.AreEqual(allProducts[0].Price, data.LawnMowers.First().Price * currencyRate);
            Assert.AreEqual(allProducts[0].Type, "Lawnmower");

            Assert.AreEqual(allProducts[1].Id, data.PhoneCases.First().Id);
            Assert.AreEqual(allProducts[1].Name, data.PhoneCases.First().Name);
            Assert.AreEqual(allProducts[1].Price, data.PhoneCases.First().Price * currencyRate);
            Assert.AreEqual(allProducts[1].Type, "Phone Case");

            Assert.AreEqual(allProducts[2].Id, data.TShirts.First().Id);
            Assert.AreEqual(allProducts[2].Name, data.TShirts.First().Name);
            Assert.AreEqual(allProducts[2].Price, data.TShirts.First().Price * currencyRate);
            Assert.AreEqual(allProducts[2].Type, "T-Shirt");

        }
        public IEnumerable<ProductData> GetProducts()
        {
            foreach (var file in Directory.EnumerateFiles(_settings.InputDirectory))
            {
                using (var stream = File.OpenText(file))
                {
                    while (!stream.EndOfStream)
                    {
                        var line = stream.ReadLine();

                        var parts = line.Split(',');

                        var productData = new ProductData();
                        productData.ProductID = Guid.Parse(parts[0]);
                        productData.Description = parts[1];
                        productData.Price = decimal.Parse(parts[2]);

                        yield return productData;
                    }
                }
            }
        }
        public IEnumerable<ProductData> RecurseNodes(HtmlDocument document)
        {
            var nodes = document.DocumentNode.SelectNodes("//li[contains(@class,'filteredItem')]");

            var data = new List<ProductData>();

            var titleAndHandle = new Dictionary<string, string>();
            foreach (var node in nodes)
            {
                var img =
                    node.SelectNodes("a/img").First().Attributes["data-src"].Value.Split(new[] { "?" }, StringSplitOptions.None)[0];
                var title =
                    node.SelectNodes("div[@class='infoProd']/a")
                    .First()
                    .InnerText
                    .Replace("\n", "")
                    .Replace("\t", "")
                    .Replace("É", "E")
                    .Replace("É".ToLower(), "e")
                    .Trim();

                var price = (
                                (Convert.ToDouble(
                                    node.SelectNodes("div[@class='infoProd']/p[@class='price']").First().InnerText
                                        .Replace("\n", "")
                                        .Replace("\t", "")
                                        .Replace("\r", "")
                                        .Replace("GBP", "")
                                        .Replace("&pound;", string.Empty)
                                        .Replace("£", "")
                                        .Trim()
                                        .Split(new[] { " - " }, StringSplitOptions.RemoveEmptyEntries)[0]
                                ) * profitRate + deliveryRate) * cardRate).ToString("0.00");

                if (Convert.ToDecimal(price) > 49.99m) continue;

                var handle = (productType + " " + Guid.NewGuid()).Replace(" ", "-");
                handle = CheckHandle(handle, titleAndHandle);
                titleAndHandle.Add(handle, title);
                var product = new ProductData { Handle = handle, Title = title, Price = price, Image = img };

                var images = DeepHarvestZaraNode(node, product).ToList();
                var count = 0;
                foreach (var size in product.Sizes)
                {
                    if (count == 0)
                    {
                        //if (data.Contains())
                        data.Add(product);
                        count++;
                        continue;
                    }
                    var subProduct = ProductData.Clone(product);
                    subProduct.Option1Name = "Size";
                    subProduct.Option1Value = size.InnerText;
                    if (images.Count >= count)
                    {
                        subProduct.Image = images[count - 1];
                    }
                    count++;
                    data.Add(subProduct);

                }
            }
            return data;
        }
Exemplo n.º 13
0
 public void OnPriceChanged(ProductData product)
 {
     Console.WriteLine("\nCallback from service:\nPrice of {0} changed to {1:C}",
         product.Name, product.ListPrice);
 }
Exemplo n.º 14
0
        // update database row using the current values
        public void UpdateFromCurrent(SqlTransaction trans)
        {
            ProductData dao = new ProductData(ConnStr, trans);

            dao.Update(Id, Name, Price);
        }
Exemplo n.º 15
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddControllersWithViews();
     services.AddSingleton(provider => ProductData.initData());
 }
Exemplo n.º 16
0
        public ActionResult Uproduct(string psort, string id, string pname, string pidno, string pcontent, string plink, HttpPostedFileBase txt_file)
        {
            Product p = new Product();
            ProductData pd = new ProductData();
            p.Pid = Convert.ToInt32(id);
            p.PName = pname;
            p.PidnoNum = pidno;
            p.PContent = pcontent;
            p.PLink = plink;
            p.Sort = Convert.ToInt32(psort);
            //檢查是否有選擇檔案
            if (txt_file != null)
            {
                //檢查檔案大小要限制也可以在這裡做
                if (txt_file.ContentLength > 0)
                {
                    string savedName = Path.Combine(Server.MapPath("~/images/product/"), txt_file.FileName);
                    txt_file.SaveAs(savedName);
                }
                p.PbigImg = "~/images/product/" + txt_file.FileName;
            }
            //if (txt_file == null)
            //{
            //   p.PbigImg = "~/images/example_img.jpg";
            //}
            else
            {
                p.PbigImg = pd.GetProduct_Once(p);
            }
            p.PbannerImg = "";

            pd.Update(p);
            return RedirectToAction("Conter", new { tabid = "1", m = "1" });
        }
Exemplo n.º 17
0
		public void InvokeOnTransactionFinished(ProductData productId, bool wasSuccessfull)
		{
			if (OnTransactionFinished != null)
				OnTransactionFinished(productId, wasSuccessfull);
		}
Exemplo n.º 18
0
        private void RazorDisplayDataEntry(String entryId)
        {
            var productData = new ProductData();

            if (Utils.IsNumeric(entryId))
            {
                productData = ProductUtils.GetProductData(Convert.ToInt32(entryId), Utils.GetCurrentCulture(), true, EntityTypeCode);
            }

            if (productData.Exists)
            {
                if (PortalSettings.HomeTabId == TabId)
                {
                    PageIncludes.IncludeCanonicalLink(Page, Globals.AddHTTP(PortalSettings.PortalAlias.HTTPAlias)); //home page always default of site.
                }
                else
                {
                    PageIncludes.IncludeCanonicalLink(Page, NBrightBuyUtils.GetEntryUrl(PortalId, _eid, "", productData.SEOName, TabId.ToString("")));
                }

                // overwrite SEO data
                if (productData.SEOTitle != "")
                {
                    BasePage.Title = productData.SEOTitle;
                }
                else
                {
                    BasePage.Title = productData.SEOName;
                }

                if (BasePage.Title == "")
                {
                    BasePage.Title = productData.ProductName;
                }

                if (productData.SEODescription != "")
                {
                    BasePage.Description = productData.SEODescription;
                }

                // if debug , output the xml used.
                if (DebugMode)
                {
                    productData.Info.XMLDoc.Save(PortalSettings.HomeDirectoryMapPath + "debug_entry.xml");
                }
                // insert page header text
                NBrightBuyUtils.RazorIncludePageHeader(ModuleId, Page, Path.GetFileNameWithoutExtension(RazorTemplate) + "_seohead" + Path.GetExtension(RazorTemplate), _controlPath, ModSettings.ThemeFolder, ModSettings.Settings(), productData);

                #region "do razor template"

                var strOut = NBrightBuyUtils.RazorTemplRender(RazorTemplate, ModuleId, "productdetailrazor" + ModuleId.ToString() + "*" + entryId, productData, _controlPath, ModSettings.ThemeFolder, Utils.GetCurrentCulture(), ModSettings.Settings());
                var lit    = new Literal();
                lit.Text = strOut;
                phData.Controls.Add(lit);

                #endregion
            }
            else
            {
                DisplayProductError(productData, "");
            }
        }
        public static ProductData MatchingProductDataPreview(string host, HtmlDocument doc, string nameXpath, string priceXpath, string imageXpath, string cpuXpath, string vgaXpath, string hddXpath, string ramXpath, string displayXpath)
        {
            var data = new ProductData();
            HtmlNode name = null;
            HtmlNode cpu = null;
            HtmlNode vga = null;
            HtmlNode hdd = null;
            HtmlNode ram = null;
            HtmlNode display = null;
            HtmlNode price = null;
            // modify xpath for vienthong a
            if (host.Contains("vienthonga.vn"))
            {
                if (nameXpath.Contains("form"))
                {
                    string[] seperator = { "/form" };
                    string take2stString = nameXpath.Split(seperator, StringSplitOptions.RemoveEmptyEntries)[1];
                    string final = "//form" + take2stString.Replace("/", "//");
                    name = doc.DocumentNode.SelectSingleNode(final);
                }
                else
                {
                    name = doc.DocumentNode.SelectSingleNode(nameXpath);
                }

            }
            else
            {
                name = doc.DocumentNode.SelectSingleNode(nameXpath);
            }

            if (host.Contains("www.nguyenkim.com") || host.Contains("www.dienmaythienhoa.vn") || host.Contains("thietbiso.com") || host.Contains("trananh.vn"))
            {
                if (priceXpath != null)
                {
                    price = doc.DocumentNode.SelectSingleNode(priceXpath);
                }
                cpu = doc.DocumentNode.SelectSingleNode(ReplaceUntable(cpuXpath, "/t", "//t"));
                vga = doc.DocumentNode.SelectSingleNode(ReplaceUntable(vgaXpath, "/t", "//t"));
                hdd = doc.DocumentNode.SelectSingleNode(ReplaceUntable(hddXpath, "/t", "//t"));
                ram = doc.DocumentNode.SelectSingleNode(ReplaceUntable(ramXpath, "/t", "//t"));
                display = doc.DocumentNode.SelectSingleNode(ReplaceUntable(displayXpath, "/t", "//t"));
                if (host.Contains("dienmaythienhoa"))
                {
                    imageXpath = ReplaceUntable(imageXpath, "/t", "//t");
                }
            }
            else
            {
                if (priceXpath != null)
                {
                    price = doc.DocumentNode.SelectSingleNode(priceXpath);
                }
                cpu = doc.DocumentNode.SelectSingleNode(cpuXpath);
                vga = doc.DocumentNode.SelectSingleNode(vgaXpath);
                hdd = doc.DocumentNode.SelectSingleNode(hddXpath);
                ram = doc.DocumentNode.SelectSingleNode(ramXpath);
                display = doc.DocumentNode.SelectSingleNode(displayXpath);
            }
            // check name Node
            if (name != null)
            {
                data.Name = name.InnerText;
            }
            else
            {
                data.Name = "Chưa xác định";
            }
            //check price Node
            if (price != null)
            {
                data.Price = price.InnerText;
            }
            else
            {
                data.Price = "Chưa xác định";
            }

            //check cpu Node
            if (cpu != null)
            {
                data.CPU = cpu.InnerText;

            }
            else
            {
                data.CPU = "Chưa xác định";
            }
            //check vga Node
            if (vga != null)
            {
                data.VGA = vga.InnerText;
            }
            else
            {
                data.VGA = "Chưa xác định";
            }
            //check ram Node
            if (ram != null)
            {
                data.RAM = ram.InnerText;
            }
            else
            {
                data.RAM = "Chưa xác định";
            }
            // check HDD Node
            if (hdd != null)
            {
                data.HDD = hdd.InnerText;
            }
            else
            {
                data.HDD = "Chưa xác định";
            }
            //check Display Node
            if (display != null)
            {
                data.Display = display.InnerText;
            }
            else
            {
                data.Display = "Chưa xác định";
            }
            // modify xpath for lazada Images
            if (host.Contains("lazada.vn"))
            {
                imageXpath = "//*[@id='productZoom']";
            }
            // Take image
            data.Image = ImageHelper.TakePathPreview(host, doc, imageXpath);
            return data;
        }
Exemplo n.º 20
0
        public OpenFoodFactsData(ProductData productData)
        {
            Code = productData.Code;
            Name = productData.GenericName != null ? productData.GenericName : productData.ProductName;

            if (productData.Nutriments != null)
            {
                if (TryGetFloat(productData, ENERGY_100G_KEY, out float energy100g))
                {
                    Energy100g = energy100g;
                }

                if (TryGetFloat(productData, SODIUM_100G_KEY, out float sodium100g))
                {
                    Sodium100g = sodium100g;
                }

                if (TryGetFloat(productData, SALT_100G_KEY, out float salt100g))
                {
                    Salt100g = salt100g;
                }

                if (TryGetFloat(productData, FAT_100G_KEY, out float fat100g))
                {
                    Fat100g = fat100g;
                }

                if (TryGetFloat(productData, SATURATED_FAT_100G_KEY, out float saturatedFat100g))
                {
                    SaturatedFat100g = saturatedFat100g;
                }

                if (TryGetFloat(productData, PROTEINS_100G_KEY, out float proteins100g))
                {
                    Proteins100g = proteins100g;
                }

                if (TryGetFloat(productData, SUGARS_100_KEY, out float sugars100g))
                {
                    Sugars100g = sugars100g;
                }

                if (TryGetFloat(productData, ENERGY_SERVING_KEY, out float energyServing))
                {
                    EnergyServing = energyServing;
                }

                if (TryGetFloat(productData, SODIUM_SERVING_KEY, out float sodiumServing))
                {
                    SodiumServing = sodiumServing;
                }

                if (TryGetFloat(productData, SALT_SERVING_KEY, out float saltServing))
                {
                    SaltServing = saltServing;
                }

                if (TryGetFloat(productData, FAT_SERVING_KEY, out float fatServing))
                {
                    FatServing = fatServing;
                }

                if (TryGetFloat(productData, SATURATED_FAT_SERVING_KEY, out float saturatedFatServing))
                {
                    SaturatedFat100g = saturatedFatServing;
                }

                if (TryGetFloat(productData, PROTEINS_SERVING_KEY, out float proteinsServing))
                {
                    ProteinsServing = proteinsServing;
                }

                if (TryGetFloat(productData, SUGARS_SERVING_KEY, out float sugarsServing))
                {
                    SugarsServing = sugarsServing;
                }

                ImgUrl = productData.ImageURL;
            }
        }
Exemplo n.º 21
0
 public AuthorizationBuilder WithProductData(ProductData value)
 {
     ProductData = value;
     return(this);
 }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            Console.WriteLine("Pressione ENTER quando o serviço for iniciado");
            Console.ReadLine();

            // Create a proxy object and connect to the service
            ServicoEstoqueClient proxy = new ServicoEstoqueClient("BasicHttpBinding_IServicoEstoque");

            // Test the operations in the service
            Console.WriteLine("Cliente 1");
            Console.WriteLine();

            //****************************************************************

            Console.WriteLine("Teste 1: Adicionar o produto 11");

            ProductData productData = new ProductData()
            {
                NumeroProduto    = "1",
                NomeProduto      = "Produto 11",
                DescricaoProduto = "Novo produto 11",
                EstoqueProduto   = 11
            };

            if (proxy.IncluirProduto(productData))
            {
                Console.WriteLine("Produto incluído com sucesso!");
            }
            else
            {
                Console.WriteLine("Erro ao incluir novo produto!");
            }

            Console.WriteLine();

            //****************************************************************

            Console.WriteLine("Teste 2: Remover produto 10");

            if (proxy.RemoverProduto("10000"))
            {
                Console.WriteLine("Produto 10 removido com sucesso!");
            }
            else
            {
                Console.WriteLine("Erro ao remover produto 10!");
            }

            Console.WriteLine();

            //****************************************************************

            Console.WriteLine("Teste 3: Listar todos os produtos");

            List <String> products = proxy.ListarProdutos().ToList();

            foreach (String p in products)
            {
                Console.WriteLine("Nome do produto: {0}", p);
                Console.WriteLine();
            }

            Console.WriteLine();

            //****************************************************************

            Console.WriteLine("Teste 4: Mostrar informações do produto 2");

            ProductData product = proxy.VerProduto("2000");

            Console.WriteLine("Número do produto: {0}", product.NumeroProduto);
            Console.WriteLine("Nome do produto: {0}", product.NomeProduto);
            Console.WriteLine("Descrição do produto: {0}", product.DescricaoProduto);
            Console.WriteLine("Estoque de produto: {0}", product.EstoqueProduto);

            Console.WriteLine();

            //****************************************************************

            Console.WriteLine("Teste 5: Adicionar estoque para produto 2");

            if (proxy.AdicionarEstoque("2000", 7))
            {
                Console.WriteLine("Estoque adicionado com sucesso!");
            }
            else
            {
                Console.WriteLine("Erro ao adicionar estoque");
            }

            Console.WriteLine();

            //****************************************************************

            Console.WriteLine("Teste 6: Verificar estoque do produto 2");

            Console.WriteLine("Estoque produto 2: {0}", proxy.ConsultarEstoque("2000"));

            Console.WriteLine();

            //****************************************************************

            Console.WriteLine("Teste 7: Verificar estoque do produto 1");

            Console.WriteLine("Estoque do produto 1: {0}", proxy.ConsultarEstoque("1000"));

            Console.WriteLine();

            //****************************************************************

            Console.WriteLine("Teste 8: Remover estoque do produto 1");

            if (proxy.RemoverEstoque("1000", 20))
            {
                Console.WriteLine("Estoque removido com sucesso!");
            }
            else
            {
                Console.WriteLine("Erro ao remover estoque do produto 1!");
            }

            Console.WriteLine();

            //****************************************************************

            Console.WriteLine("Teste 9: Verificar estoque do produto 1 novamente");

            Console.WriteLine("Estoque do produto 1 novamente: {0}", proxy.ConsultarEstoque("1000"));

            Console.WriteLine();

            //****************************************************************

            Console.WriteLine("Teste 10: Ver informações do produto 1");

            ProductData product1 = proxy.VerProduto("1000");

            Console.WriteLine("Número do produto: {0}", product1.NumeroProduto);
            Console.WriteLine("Nome do produto: {0}", product1.NomeProduto);
            Console.WriteLine("Descrição do produto: {0}", product1.DescricaoProduto);
            Console.WriteLine("Estoque de produto: {0}", product1.EstoqueProduto);

            Console.WriteLine();

            //****************************************************************

            // Disconnect from the service
            proxy.Close();
            Console.WriteLine("Press ENTER to finish");
            Console.ReadLine();
        }
Exemplo n.º 23
0
        public void SetUp()
        {
            providerRepository = A.Fake <IRepository>();
            providerData       = new ProviderData
            {
                Id         = Guid.Parse("666f730d-876b-42e4-a59b-254aba887f9d"),
                ProviderId = Guid.Parse("268798db-72c9-4246-98bb-6be06d88090c"),
                Products   = new ProductData[0],
                Timestamp  = DateTime.FromFileTimeUtc(1576674756L)
            };
            A.CallTo(() => providerRepository.FindByProviderId(Guid.Empty))
            .WithAnyArguments()
            .Returns(providerData);
            A.CallTo(() => providerRepository.RemoveById(Guid.Empty))
            .WithAnyArguments();
            A.CallTo(() => providerRepository.Save(providerData))
            .WithAnyArguments();
            A.CallTo(() => providerRepository.Update(providerData))
            .WithAnyArguments();

            productsReference = A.Fake <IProductsReference>();
            A.CallTo(() => productsReference.FindCodeByName(""))
            .WithAnyArguments()
            .Returns(null);

            productsReferenceBuilder = A.Fake <IProductsReferenceBuilder>();
            A.CallTo(() => productsReferenceBuilder.GetInstance())
            .Returns(productsReference);

            measureUnitsReference = A.Fake <IMeasureUnitsReference>();
            A.CallTo(() => measureUnitsReference.FindByCode(null))
            .WithAnyArguments()
            .Returns(null);
            measureUnitsReferenceBuilder = A.Fake <IMeasureUnitsReferenceBuilder>();
            A.CallTo(() => measureUnitsReferenceBuilder.GetInstance())
            .Returns(measureUnitsReference);
            A.CallTo(() => productsReference.FindCodeByName("Banana"))
            .Returns(42);
            A.CallTo(() => measureUnitsReference.FindByCode("u"))
            .Returns(new MeasureUnit());

            goodProduct = new ProductData
            {
                Id = Guid.Parse("4279c077-b7fb-4aed-bf35-5794ab327ce7"),
                MeasureUnitCode = "u",
                Name            = "Banana",
                Price           = 10.000m
            };

            productWithInvalidName = new ProductData
            {
                Id = Guid.Parse("4279c077-b7fb-4aed-bf35-5794ab327ce7"),
                MeasureUnitCode = "u",
                Name            = "Apple",
                Price           = 10.000m
            };

            productWithInvalidMeasureUnit = new ProductData
            {
                Id = Guid.Parse("4279c077-b7fb-4aed-bf35-5794ab327ce7"),
                MeasureUnitCode = "m",
                Name            = "Banana",
                Price           = 10.000m
            };

            productWithInvalidPrice = new ProductData
            {
                Id = Guid.Parse("4279c077-b7fb-4aed-bf35-5794ab327ce7"),
                MeasureUnitCode = "u",
                Name            = "Banana",
                Price           = -10.000m
            };

            products = new Dictionary <string, ProductData>
            {
                { "good", goodProduct },
                { "name", productWithInvalidName },
                { "unit", productWithInvalidMeasureUnit },
                { "price", productWithInvalidPrice }
            };

            providerProcessor = new ProviderProcessor(providerRepository,
                                                      productsReferenceBuilder,
                                                      measureUnitsReferenceBuilder,
                                                      new ProductValidator(productsReferenceBuilder, measureUnitsReferenceBuilder));
        }
Exemplo n.º 24
0
        public ActionResult ViewCart(string quantity, string product_id, string coupon)
        {
            //get the list of products in session["cart"]
            List <Product> cart = (List <Product>)Session["cart"];

            //if there are no items in the cart
            if (cart.Count == 0)
            {
                return(View());
            }

            //if there are items in the cart
            else
            {
                if (quantity == null && product_id == null)//this means that the user has not changed any quantity in the view cart page
                {
                    ViewBag.cart = cart;
                    IEnumerable <Product> testcart     = cart.Distinct();
                    List <Product>        distinctcart = new List <Product>();
                    foreach (var p in testcart)
                    {
                        distinctcart.Add(p);
                    }
                    ViewBag.distinctcart = distinctcart;
                    Coupon couponobj = CouponData.GetCoupon(coupon);
                    Session["discount"]   = couponobj.Discount;
                    Session["couponcode"] = couponobj.Couponcode;
                    ViewBag.discount      = couponobj.Discount;
                    return(View());
                }

                else //user has changed the quantity of product in the view cart page
                {
                    int qtyint        = Convert.ToInt32(quantity);
                    int qtyofproducts = 0;
                    //qtyint is the new quantity and qtyofproducts is the original quantity in the cart
                    for (int i = 0; i < cart.Count; i++)
                    {
                        if (product_id == cart[i].Id)
                        {
                            qtyofproducts++;
                        }
                    }
                    //for an increase of the number of product
                    if (qtyint > qtyofproducts)
                    {
                        int add = qtyint - qtyofproducts;
                        for (int j = 0; j < add; j++)
                        {
                            Product addproduct = new Product();
                            addproduct = ProductData.GetProduct(product_id);
                            cart.Add(addproduct);
                        }
                    }
                    //for a decrease in the number of product
                    else
                    {
                        int minus = qtyofproducts - qtyint;
                        for (int j = 0; j < minus; j++)
                        {
                            Product minusproduct = new Product();
                            minusproduct = ProductData.GetProduct(product_id);
                            cart.Remove(minusproduct);
                        }
                    }
                    //check if cart is empty. If empty redirect to same controller to display another screen
                    if (cart.Count == 0)
                    {
                        return(RedirectToAction("ViewCart", "Products"));
                    }
                    //if cart is not empty, return updated view
                    else
                    {
                        ViewBag.cart    = cart;
                        Session["cart"] = cart;
                        IEnumerable <Product> testcart     = cart.Distinct();
                        List <Product>        distinctcart = new List <Product>();
                        //distinctcart is the cart with no duplicates
                        foreach (var p in testcart)
                        {
                            distinctcart.Add(p);
                        }
                        ViewBag.distinctcart = distinctcart;
                        Coupon couponobj = CouponData.GetCoupon(coupon);
                        Session["discount"]   = couponobj.Discount;
                        Session["couponcode"] = couponobj.Couponcode;
                        ViewBag.discount      = couponobj.Discount;
                        return(View());
                    }
                }
            }
        }
Exemplo n.º 25
0
        public IEnumerable<ProductData> RecurseNodes(HtmlDocument document)
        {
            //Debugger.Launch();
            var nodes = document.DocumentNode.SelectNodes("//ul[@class = 'product']");
            //var nodes = document.DocumentNode.SelectNodes("//div/ul[@id='list-products']/li").Where(x => x.Attributes["class"].Value != "getTheLook");

            var data = new List<ProductData>();

            var titleAndHandle = new Dictionary<string, string>();

            foreach (var node in nodes)
            {
                // /a/img[@src]
                var title = node.SelectNodes("li[@class='product_description']/a").First().InnerText
                    .Replace("&eacute;", "e")
                    .Replace("&acute;", "e")
                    .Replace("w/", "with")
                    .Replace("&reg;", "")
                    .Replace("From", "")
                    .Replace("&amp;", "and")
                    .Replace("&trade;", "")
                    .Replace("&", "and")
                    .Replace("3/4", "3-quarter")
                    .Replace("\t", " ")
                    .Replace("\r", " ")
                    .Replace("\n", " ")
                    .Replace("/t", " ")
                    .Replace("'", " ").Split(new string[] { "£" }, StringSplitOptions.RemoveEmptyEntries)[0]
                    .Trim();

                string price = "";
                var amounts = node.SelectNodes("li[@class='product_price']");
                if (amounts != null)
                {
                    var priceArray = new string[] { };
                    try
                    {
                        var innerText = amounts.First().InnerText;
                        priceArray =
                            innerText
                            .Replace("Orig.:", "")
                            .Replace("From ", "")
                            .Replace("\r", "")
                            .Replace("\n", "")
                            .Replace("&pound;", string.Empty)
                            .Replace("&#163;", string.Empty)
                            .Split(new[] { "£" }, StringSplitOptions.RemoveEmptyEntries);

                        price = ((
                            (Convert.ToDouble((priceArray[0]).Trim()) * profitRate + deliveryRate) * cardRate)
                            .ToString("0.00"));
                    }
                    catch (Exception e)
                    {
                        Debugger.Launch();
                        var t = e;
                    }
                }
                else
                {

                }

                if (Convert.ToDecimal(price) > 39.99m) continue;
                //Debugger.Launch();
                var imgSrc = node.SelectNodes("li[@class='product_image']/a/img").First().Attributes["src"].Value.Replace(" ", "%20");
                var image = "\"" + (imgSrc.StartsWith("//") ? "http:" + imgSrc : imgSrc) + "\"";
                var handle = (productType + " " + Guid.NewGuid()).Replace(" ", "-");
                handle = CheckHandle(handle, titleAndHandle);
                titleAndHandle.Add(handle, title);
                var product = new ProductData { Handle = handle, Title = title, Price = price, Image = image };

                //Debugger.Launch();
                var images = DeepHarvestDPNode(node, product).ToList();
                if (images.First() == "skip") continue;

                var count = 0;
                foreach (var size in product.Sizes)
                {
                    if (count == 0)
                    {
                        //if (data.Contains())
                        data.Add(product);
                        count++;
                        continue;
                    }
                    var subProduct = ProductData.Clone(product);
                    subProduct.Option1Name = "Size";
                    subProduct.Option1Value = size.InnerText;
                    if (images.Count >= count)
                    {
                        subProduct.Image = "\"" + images[count - 1] + "\"";
                    }
                    count++;
                    data.Add(subProduct);

                }
            }
            return data;
        }
Exemplo n.º 26
0
        private void GetProductDataResponseCallback(GetProductDataResponse eventName)
        {
            if (eventName.Status == "NOT_SUPPORTED")
            {
                EB.Debug.LogError("GetProductDataResponseCallback: NOT_SUPPORTED");

                if (_items != null)
                {
                    foreach (Item item in _items)
                    {
                        item.valid = false;
                    }

                    if (_config.OnEnumerate != null)
                    {
                        _config.OnEnumerate();
                    }
                }

                return;
            }

            if (eventName.Status == "FAILED")
            {
                EB.Debug.LogError("GetProductDataResponseCallback: FAILED");

                if (_items != null)
                {
                    foreach (Item item in _items)
                    {
                        item.valid = false;
                    }

                    if (_config.OnEnumerate != null)
                    {
                        _config.OnEnumerate();
                    }
                }

                return;
            }

            if (_items != null && eventName.ProductDataMap != null)
            {
                EB.Debug.Log("GetProductDataResponseCallback: products = {0}", eventName.ToJson());
                foreach (Item item in _items)
                {
                    if (eventName.ProductDataMap.ContainsKey(item.productId))
                    {
                        ProductData productData = eventName.ProductDataMap[item.productId];
                        item.valid          = true;
                        item.localizedTitle = productData.Title;
                        item.localizedDesc  = productData.Description;
                        item.localizedCost  = productData.Price;

                        //TODO: amazon doesn't seem to provide a currency code, or cents value
                        //item.currencyCode = "";

                        EB.Debug.Log("parsing cents: {0}", productData.Price);
                        float  costValue = 0.0f;
                        string price     = productData.Price;

                        //TODO: need to make sure this works for all currency
                        if (float.TryParse(price, out costValue))
                        {
                            item.cents = (int)(costValue * 100);
                            EB.Debug.Log("cents: {0}", item.cents);
                            break;
                        }
                        else
                        {
                            item.cents = (int)item.cost * 100;
                        }

                        EB.Debug.Log("Cost {0}", item.cost);
                        EB.Debug.Log("item currency code {0}", item.currencyCode);

                        //TODO: Are there other item members that need filling here?
                    }
                }

                if (_config.OnEnumerate != null)
                {
                    _config.OnEnumerate();
                }

                // now that we've successfully called Amazon, AmazonIAP.initiateItemDataRequest we are allowed to start other AmazonIAP operations.
                Coroutines.Run(RequestAmazonUserId());
            }
        }
 public static ProductData GetProductData(HtmlWeb web, ParseInfo parseInfo)
 {
     var data = new ProductData();
     try
     {
         //load page
         System.Net.ServicePointManager.Expect100Continue = false;
         var uri = new Uri(parseInfo.Parselink);
         string host = uri.GetLeftPart(UriPartial.Authority);
         HtmlNode.ElementsFlags.Remove("form");
         var doc = web.Load(parseInfo.Parselink);
         data = MatchingProductData(host, doc, parseInfo.Name, parseInfo.PriceXPath, parseInfo.ImageXpath, parseInfo.CPUXPath, parseInfo.VGAXPath, parseInfo.HDDXPath, parseInfo.RAMXPath, parseInfo.DisplayXPath);
         return data;
     }
     catch (System.Net.WebException ex)
     {
         GetProductData(web, parseInfo);
     }
     catch (HtmlWebException ex)
     {
         GetProductData(web, parseInfo);
     }
     return data;
 }
 public GeneralTabViewModel(ProductData product, IEnumerable <Language> languages)
 {
     this.product = product;
     Languages    = languages;
     BuildDescriptionViewModels();
 }
Exemplo n.º 29
0
 private void UpdateView(ProductData data)
 {
     valueText.text            = data.Value.ToString();
     descriptionText.text      = data.Description;
     clickHandler.interactable = data.CanBuy;
 }
Exemplo n.º 30
0
        private String DoProductIdx(DotNetNuke.Entities.Portals.PortalInfo portal, DateTime lastrun, Boolean debug)
        {
            if (debug)
            {
                InternalSearchController.Instance.DeleteAllDocuments(portal.PortalID, SearchHelper.Instance.GetSearchTypeByName("tab").SearchTypeId);
            }
            var searchDocs      = new List <SearchDocument>();
            var culturecodeList = DnnUtils.GetCultureCodeList(portal.PortalID);
            var storeSettings   = new StoreSettings(portal.PortalID);

            foreach (var lang in culturecodeList)
            {
                var strContent = "";
                // select all products
                var objCtrl   = new NBrightBuyController();
                var strFilter = " and NB1.ModifiedDate > convert(datetime,'" + lastrun.ToString("s") + "') ";
                if (debug)
                {
                    strFilter = "";
                }
                var l = objCtrl.GetList(portal.PortalID, -1, "PRD", strFilter);

                foreach (var p in l)
                {
                    var prodData = new ProductData(p.ItemID, portalId, lang);

                    strContent = prodData.Info.GetXmlProperty("genxml/textbox/txtproductref") + " : " + prodData.SEODescription + " " + prodData.SEOName + " " + prodData.SEOTagwords + " " + prodData.SEOTitle;

                    if (strContent != "")
                    {
                        var tags = new List <String>();
                        tags.Add("nbsproduct");

                        //Get the description string
                        string strDescription = HtmlUtils.Shorten(HtmlUtils.Clean(strContent, false), 100, "...");
                        var    searchDoc      = new SearchDocument();
                        // Assigns as a Search key the SearchItems'
                        searchDoc.UniqueKey   = prodData.Info.ItemID.ToString("");
                        searchDoc.QueryString = "ref=" + prodData.Info.GetXmlProperty("genxml/textbox/txtproductref");
                        searchDoc.Title       = prodData.ProductName;
                        searchDoc.Body        = strContent;
                        searchDoc.Description = strDescription;
                        if (debug)
                        {
                            searchDoc.ModifiedTimeUtc = DateTime.Now.Date;
                        }
                        else
                        {
                            searchDoc.ModifiedTimeUtc = prodData.Info.ModifiedDate;
                        }
                        searchDoc.AuthorUserId = 1;
                        searchDoc.TabId        = storeSettings.ProductDetailTabId;
                        searchDoc.PortalId     = portal.PortalID;
                        searchDoc.SearchTypeId = SearchHelper.Instance.GetSearchTypeByName("tab").SearchTypeId;
                        searchDoc.CultureCode  = lang;
                        searchDoc.Tags         = tags;
                        //Add Module MetaData
                        searchDoc.ModuleDefId = 0;
                        searchDoc.ModuleId    = 0;

                        searchDocs.Add(searchDoc);
                    }
                }
            }

            //Index
            InternalSearchController.Instance.AddSearchDocuments(searchDocs);
            InternalSearchController.Instance.Commit();


            return(" - NBS-DNNIDX scheduler ACTIVATED ");
        }
Exemplo n.º 31
0
	void OnBuyProduct(ProductData productData)
	{
		if (productData.coinPrice <= mainMenu.CoinBalance)
		{
			mainMenu.CoinBalance -= productData.coinPrice;
			AddProductToBalance(productData);
			DialogEnabled = false; // hide dialog
			mainMenu.AddPopupMessage("Purchase Complete",1);
		}
		else
		{
			mainMenu.AddPopupMessage("Not enough coins",1);
		}
	}
Exemplo n.º 32
0
 private IEnumerable <ProductValidationResult> ValidatePricesAndMeasureUnitCodes(ProductData product)
 {
     if (product.Price <= 0)
     {
         yield return(new ProductValidationResult(product, "Bad price", ProductValidationSeverity.Warning));
     }
     if (!IsValidMeasureUnitCode(product.MeasureUnitCode))
     {
         yield return(new ProductValidationResult(product,
                                                  "Bad units of measure", ProductValidationSeverity.Warning));
     }
 }
Exemplo n.º 33
0
		public void InvokeOnReceivedProductInformation(ProductData[] products)
		{
			if (OnReceivedProductInformation != null)
				OnReceivedProductInformation(products);
		}
    public override void mPhoneUpdate()
    {
        base.mPhoneUpdate();
        if (uguiHitUI.uiHited == true)
        {
            return;
        }
        //Debug.LogWarning("Input.touchCount = "+ Input.touchCount);
        if (Input.touchCount != 1)
        {
            return;
        }
        Touch   touch = Input.GetTouch(0);
        Ray     ray   = inputCamera.ScreenPointToRay(touch.position);
        Vector2 pos   = ray.origin;

        if (lastMousePos == pos && touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled)
        {
            return;
        }
        lastMousePos = pos;

        Vector3 world = Vector3.one;
        int     count = Physics.RaycastNonAlloc(ray, hits);

        if (count > 1 || (count == 1 && hits[0].collider.gameObject != targetObj))
        {
            float dis = float.MaxValue;
            for (int i = 0; i < count; i++)
            {
                if (hits[i].collider.gameObject == targetObj)
                {
                    continue;
                }
                float itemDis = Vector3.Distance(hits[i].point, inputCamera.transform.position);
                if (itemDis < dis)
                {
                    dis     = itemDis;
                    world   = hits[i].point;
                    world.y = 0;
                }
            }
        }
        else
        {
            Vector3 v3  = inputCamera.transform.position;
            Vector3 v32 = ray.origin;
            world.y = 0;
            float lerp = (world.y - v32.y) / (v3.y - v32.y);
            world.x = lerp * (v3.x - v32.x) + v32.x;
            world.z = lerp * (v3.z - v32.z) + v32.z;
        }

        float Angle = -targetObj.transform.rotation.eulerAngles.y + forTop;

        world.y = targetProduct.defaultHeight;

        switch (targetVO.type)
        {
        case 1:    //吸附墙
        {
            Adsorb(ref world, ref Angle);
        }
        break;

        case 2:    //门窗
        {
            //if (targetProduct.entityType == "window")
            //{
            //    world.y = 1;
            //}
            Inlay(ref world, ref Angle);
        }
        break;

        case 3:    //吊顶
        {
            world.y = defaultSetting.DefaultHeight - targetSize.y + targetProduct.defaultHeight;
        }
        break;

        case 4:    //地毯
        {
            world.y = -0.001f + defaultSetting.DefaultHeight + targetProduct.defaultHeight;
        }
        break;

        case 5:    //天花板
        {
            world.y = defaultSetting.DefaultHeight - 0.001f + targetProduct.defaultHeight;
        }
        break;

        case 6:    //吸附各个平面 暂时不做
        {
            //world.y = defaultSetting.DefaultHeight - 0.01f;
        }
        break;

        default:    //不吸附
            break;
        }

        targetObj.transform.position = world;
        if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
        {
            undoHelper.save();

            Product     product     = targetProduct;
            ProductData productData = data.AddProduct(targetVO.id, world, Angle, product, targetWall, targetVO.type);
            RefreshView();//必须先刷新
            ToSelectGoodsState(productData);
        }
    }
Exemplo n.º 35
0
 public CartController(ProductData productData)
 {
     this.productData = productData;
 }
Exemplo n.º 36
0
        static void Main(string[] args)
        {
            Maximize();
            AppDomain.CurrentDomain.SetData("DataDirectory", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
            Console.BackgroundColor = ConsoleColor.Gray;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.Clear();

            CategoryData cd = new CategoryData();
            Category     CT = new Category();

            ProductData pd = new ProductData();
            Product     PD = new Product();

            SupplierData sd = new SupplierData();
            Supplier     SP = new Supplier();

            CustomerData cud  = new CustomerData();
            Customer     CUST = new Customer();

            TerritoryData td = new TerritoryData();
            Territory     TR = new Territory();

            RegionData rd  = new RegionData();
            Region     REG = new Region();

            OrderData od    = new OrderData();
            Order     ORDER = new Order();

            OrderDetailData odetdat = new OrderDetailData();
            Order_Detail    ORDT    = new Order_Detail();

            string IDTer, path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            int    SEL, SELMenu2, SEL2, SEL3, IDSup, IDCat, IDProd, IDReg, IDFact, x = 0;

            while (x < 3)
            {
                Console.WriteLine("\n ==================== MENÚ PRINCIPAL ====================");
                Console.Write("\n 1) Mantenimiento de tablas");
                Console.Write("\n 2) Exportar una factura en un archivo txt");
                Console.Write("\n 3) Carga de archivo CSV de clientes");
                Console.Write("\n");
                Console.Write("\n Ingrese el dígito de la opción deseada: ");

                while (!int.TryParse(Console.ReadLine(), out SEL))
                {
                    Console.Write("\n Sólo se permiten números. Intente nuevamente: ");
                }

                switch (SEL)
                {
                case 1:
                    Console.WriteLine("\n ====================MANTENIMIENTO DE TABLAS====================");
                    Console.Write("\n Seleccione la tabla a la que desea darle mantenimiento");
                    Console.Write("\n 1) Categorías");
                    Console.Write("\n 2) Territorios");
                    Console.Write("\n 3) Productos");
                    Console.Write("\n");
                    Console.Write("\n Ingrese el dígito de la opción deseada: ");

                    while (!int.TryParse(Console.ReadLine(), out SELMenu2))
                    {
                        Console.Write("\n Sólo se permiten números. Intente nuevamente: ");
                    }

                    switch (SELMenu2)
                    {
                    case 1:
                        Console.WriteLine("\n **************** Bienvenido al mantenimiento de la tabla Categorías ****************");
                        Console.Write("\n ¿Qué desea realizar?");
                        Console.Write("\n 1) Insertar registros");
                        Console.Write("\n 2) Actualizar registros");
                        Console.Write("\n 3) Eliminar registros");
                        Console.Write("\n 4) Mostrar todos los registros");
                        Console.Write("\n");
                        Console.Write("\n Ingrese el dígito de la opción deseada: ");

                        while (!int.TryParse(Console.ReadLine(), out SEL2))
                        {
                            Console.Write("\n Sólo se permiten números. Intente nuevamente: ");
                        }

                        switch (SEL2)
                        {
                        case 1:
                            Console.Write("\n Ingrese el nombre de la categoría que desea agregar: ");
                            CT.CategoryName = Console.ReadLine();
                            while (!Regex.IsMatch(CT.CategoryName, @"[a-zA-Z]"))
                            {
                                Console.WriteLine("\n No se permiten números. Intente nuevamente: ");
                                Console.Write("\n Ingrese el nombre de la categoría que desea agregar: ");
                                CT.CategoryName = Console.ReadLine();
                            }
                            Console.WriteLine("\n Estamos procesando su petición.................\n");
                            cd.Agregar <Category>(CT);
                            break;

                        case 2:
                            Console.Write("\n Ingrese el código de la categoría que desea actualizar: ");
                            while (!int.TryParse(Console.ReadLine(), out IDCat))
                            {
                                Console.Write("\n Sólo se permiten números. Intente nuevamente: ");
                            }
                            Console.WriteLine("\n Estamos procesando su búsqueda.................\n");
                            while (!cd.Listado <Category>().Exists(c => c.CategoryID == IDCat))
                            {
                                Console.Write("\n Este código no pertenece a ninguna categoría registrada. Intente nuevamente: ");
                                IDCat = int.Parse(Console.ReadLine());
                            }
                            var resultCAT = cd.Listado <Category>().Find(a => a.CategoryID == IDCat);
                            if (resultCAT != null && cd.Listado <Category>().Exists(c => c.CategoryID == IDCat))
                            {
                                var ctNombre = cd.Model.Categories.Where(ct => ct.CategoryID == IDCat).Select(ctn => ctn).FirstOrDefault();
                                Console.Write("\n Categoría: " + ctNombre.CategoryName);
                                Console.Write("\n Ingrese el nuevo nombre de esta categoría: ");
                                CT.CategoryName = Console.ReadLine();
                                CT.CategoryID   = IDCat;
                                cd.Model.Entry(resultCAT).State = EntityState.Detached;
                                cd.Actualizar <Category>(CT);
                            }
                            break;

                        case 3:
                            Console.Write("\n Ingrese el código de la categoría que desea eliminar: ");
                            while (!int.TryParse(Console.ReadLine(), out IDCat))
                            {
                                Console.Write("\n Sólo se permiten números. Intente nuevamente: ");
                            }

                            while (!cd.Listado <Category>().Exists(c => c.CategoryID == IDCat))
                            {
                                Console.Write("\n Este código no pertenece a ninguna categoría registrada. Intente nuevamente: ");
                                IDCat = int.Parse(Console.ReadLine());
                            }
                            var resultCT = cd.Listado <Category>().Find(a => a.CategoryID == IDCat);
                            if (resultCT != null && cd.Listado <Category>().Exists(c => c.CategoryID == IDCat))
                            {
                                CT.CategoryID = IDCat;
                                cd.Model.Entry(resultCT).State = EntityState.Detached;
                                cd.Eliminar <Category>(CT);
                            }
                            break;

                        case 4:
                            ConsoleTable TablaCAT = new ConsoleTable("Código", "Nombre");
                            foreach (Category ListCAT in cd.Listado <Category>())
                            {
                                TablaCAT.AddRow(ListCAT.CategoryID, ListCAT.CategoryName);
                            }
                            TablaCAT.Write(Format.Alternative);
                            break;
                        }
                        break;

                    case 2:
                        Console.WriteLine("\n **************** Bienvenido al mantenimiento de la tabla Territorios ****************");
                        Console.Write("\n ¿Qué desea realizar?");
                        Console.Write("\n 1) Insertar registros");
                        Console.Write("\n 2) Actualizar registros");
                        Console.Write("\n 3) Eliminar registros");
                        Console.Write("\n 4) Mostrar todos los registros");
                        Console.Write("\n");
                        Console.Write("\n Ingrese el dígito de la opción deseada: ");

                        while (!int.TryParse(Console.ReadLine(), out SEL2))
                        {
                            Console.Write("\n Sólo se permiten números. Intente nuevamente: ");
                        }

                        switch (SEL2)
                        {
                        case 1:
                            Console.Write("\n Código: ");
                            TR.TerritoryID = Console.ReadLine();

                            Console.Write("\n Nombre: ");
                            TR.TerritoryDescription = Console.ReadLine();
                            while (!Regex.IsMatch(TR.TerritoryDescription, @"[a-zA-Z]"))
                            {
                                Console.WriteLine("\n No se permiten números. Intente nuevamente: ");
                                Console.Write("\n Nombre: ");
                                TR.TerritoryDescription = Console.ReadLine();
                            }
                            Console.Write("\n");
                            Console.Write("\n A continuación se presentan las regiones registradas, favor ingresar el código de la requerida para el nuevo territorio. Presione Enter. ");
                            Console.ReadLine();
                            ConsoleTable TablaRegiones = new ConsoleTable("Código", "Nombre");
                            foreach (Region RG in rd.Listado <Region>())
                            {
                                TablaRegiones.AddRow(RG.RegionID, RG.RegionDescription);
                            }
                            TablaRegiones.Write(Format.Alternative);
                            Console.Write("\n");

                            Console.Write("\n Código de la región: ");
                            while (!int.TryParse(Console.ReadLine(), out IDReg))
                            {
                                Console.Write("\n Sólo se permiten números. Intente nuevamente: ");
                            }
                            while (!rd.Listado <Region>().Exists(c => c.RegionID == IDReg))
                            {
                                Console.Write("\n Este código no corresponde a ninguna región registrada. Intente nuevamente: ");
                                IDReg = int.Parse(Console.ReadLine());
                            }
                            if (rd.Listado <Region>().Exists(c => c.RegionID == IDReg))
                            {
                                TR.RegionID = IDReg;
                            }
                            Console.WriteLine("\n Estamos procesando su petición.................\n");
                            td.Agregar <Territory>(TR);
                            break;

                        case 2:
                            Console.Write("\n Ingrese el código del territorio que desea actualizar: ");
                            IDTer = Console.ReadLine();
                            Console.WriteLine("\n Estamos procesando su búsqueda.................\n");
                            while (!td.Listado <Territory>().Exists(c => c.TerritoryID == IDTer))
                            {
                                Console.Write("\n Este código no pertenece a ningún territorio registrado. Intente nuevamente: ");
                                IDTer = Console.ReadLine();
                            }
                            var resultTER = td.Listado <Territory>().Find(a => a.TerritoryID == IDTer);
                            if (resultTER != null && td.Listado <Territory>().Exists(c => c.TerritoryID == IDTer))
                            {
                                var terNombre = td.Model.Territories.Where(tr => tr.TerritoryID == IDTer).Select(terr => terr).FirstOrDefault();
                                Console.Write("\n Territorio: " + terNombre.TerritoryDescription);
                                Console.Write("\n Ingrese el nuevo nombre de este territorio: ");
                                TR.TerritoryDescription = Console.ReadLine();
                                TR.TerritoryID          = IDTer;
                                var search = td.Model.Territories.Where(t => t.TerritoryID == IDTer).Select(m => m).FirstOrDefault();
                                TR.RegionID = search.RegionID;

                                td.Model.Entry(resultTER).State = EntityState.Detached;
                                td.Actualizar <Territory>(TR);
                            }
                            break;

                        case 3:
                            Console.Write("\n Ingrese el código del territorio que desea eliminar: ");
                            IDTer = Console.ReadLine();
                            Console.WriteLine("\n Estamos procesando su búsqueda.................\n");
                            while (!td.Listado <Territory>().Exists(c => c.TerritoryID == IDTer))
                            {
                                Console.Write("\n Este código no pertenece a ningún territorio registrado. Intente nuevamente: ");
                                IDTer = Console.ReadLine();
                            }
                            var resultTER2 = td.Listado <Territory>().Find(a => a.TerritoryID == IDTer);
                            if (resultTER2 != null && td.Listado <Territory>().Exists(c => c.TerritoryID == IDTer))
                            {
                                TR.TerritoryID = IDTer;
                                td.Model.Entry(resultTER2).State = EntityState.Detached;
                                td.Eliminar <Territory>(TR);
                            }
                            break;

                        case 4:
                            Console.Write("\n");
                            ConsoleTable TablaTerritorios = new ConsoleTable("Código", "Nombre", "Región");
                            foreach (Territory TERT in td.Listado <Territory>())
                            {
                                TablaTerritorios.AddRow(TERT.TerritoryID, TERT.TerritoryDescription, TERT.Region.RegionDescription);
                            }
                            TablaTerritorios.Write(Format.Alternative);
                            break;
                        }
                        break;

                    case 3:
                        Console.WriteLine("\n **************** Bienvenido al mantenimiento de la tabla Productos ****************");
                        Console.Write("\n ¿Qué desea realizar?");
                        Console.Write("\n 1) Insertar registros");
                        Console.Write("\n 2) Actualizar registros");
                        Console.Write("\n 3) Eliminar registros");
                        Console.Write("\n 4) Mostrar todos los registros");
                        Console.Write("\n");
                        Console.Write("\n Ingrese el dígito de la opción deseada: ");

                        while (!int.TryParse(Console.ReadLine(), out SEL2))
                        {
                            Console.Write("\n Sólo se permiten números. Intente nuevamente: ");
                        }

                        switch (SEL2)
                        {
                        case 1:
                            Console.Write("\n Nombre del producto: ");
                            PD.ProductName = Console.ReadLine();
                            while (!Regex.IsMatch(PD.ProductName, @"[a-zA-Z]"))
                            {
                                Console.WriteLine("\n No se permiten números. Intente nuevamente: ");
                                Console.Write("\n Nombre del producto: ");
                                PD.ProductName = Console.ReadLine();
                            }
                            Console.Write("\n");
                            Console.Write("\n A continuación se presentan los suplidores registrados, favor ingresar el código del requerido para el nuevo producto. Presione Enter.");
                            Console.ReadLine();
                            ConsoleTable TablaSuplidores = new ConsoleTable("Código", "Nombre", "Teléfono", "Dirección");
                            foreach (Supplier SUP in sd.Listado <Supplier>())
                            {
                                TablaSuplidores.AddRow(SUP.SupplierID, SUP.CompanyName, SUP.Phone, SUP.Address);
                            }
                            TablaSuplidores.Write(Format.Alternative);
                            Console.Write("\n");

                            Console.Write("\n Código del suplidor: ");
                            while (!int.TryParse(Console.ReadLine(), out IDSup))
                            {
                                Console.Write("\n Sólo se permiten números. Intente nuevamente: ");
                            }
                            while (!pd.Listado <Supplier>().Exists(c => c.SupplierID == IDSup))
                            {
                                Console.Write("\n Este código no corresponde a ningún suplidor registrado. Intente nuevamente: ");
                                IDSup = int.Parse(Console.ReadLine());
                            }
                            if (pd.Listado <Supplier>().Exists(s => s.SupplierID == IDSup))
                            {
                                PD.SupplierID = IDSup;
                            }

                            Console.Write("\n A continuación se presentan las categorías registradas, favor ingresar el código de la requerida para el nuevo producto:");
                            Console.Write("\n");
                            ConsoleTable TablaCAT = new ConsoleTable("Código", "Nombre");
                            foreach (Category ListCAT in cd.Listado <Category>())
                            {
                                TablaCAT.AddRow(ListCAT.CategoryID, ListCAT.CategoryName);
                            }
                            TablaCAT.Write(Format.Alternative);
                            Console.Write("\n");

                            Console.Write("\n Código de la categoría: ");
                            while (!int.TryParse(Console.ReadLine(), out IDCat))
                            {
                                Console.Write("\n Sólo se permiten números. Intente nuevamente: ");
                            }

                            while (!pd.Listado <Category>().Exists(c => c.CategoryID == IDCat))
                            {
                                Console.Write("\n Este código no corresponde a ninguna categoría registrada. Intente nuevamente: ");
                                IDCat = int.Parse(Console.ReadLine());
                            }
                            if (pd.Listado <Category>().Exists(s => s.CategoryID == IDCat))
                            {
                                PD.CategoryID = IDCat;
                            }

                            Console.Write("\n Cantidad: ");
                            PD.QuantityPerUnit = Console.ReadLine();

                            Console.Write("\n Precio: ");
                            PD.UnitPrice = decimal.Parse(Console.ReadLine());

                            Console.Write("\n Unidades disponibles: ");
                            PD.UnitsInStock = short.Parse(Console.ReadLine());

                            Console.Write("\n Unidades pedidas: ");
                            PD.UnitsOnOrder = short.Parse(Console.ReadLine());

                            Console.WriteLine("\n Estamos procesando su petición.................\n");
                            pd.Agregar <Product>(PD);
                            break;

                        case 2:
                            Console.Write("\n Ingrese el código del producto que desea actualizar: ");
                            while (!int.TryParse(Console.ReadLine(), out IDProd))
                            {
                                Console.Write("\n Sólo se permiten números. Intente nuevamente: ");
                            }
                            Console.WriteLine("\n Estamos procesando su búsqueda.................\n");
                            while (!pd.Listado <Product>().Exists(p => p.ProductID == IDProd))
                            {
                                Console.Write("\n Este código no pertenece a ningún producto registrado. Intente nuevamente: ");
                                IDProd = int.Parse(Console.ReadLine());
                            }
                            var resultPROD = pd.Listado <Product>().Find(r => r.ProductID == IDProd);
                            if (resultPROD != null && cd.Listado <Product>().Exists(d => d.ProductID == IDProd))
                            {
                                var pdNombre = pd.Model.Products.Where(pr => pr.ProductID == IDProd).Select(pt => pt).FirstOrDefault();
                                Console.Write("\n Producto: " + pdNombre.ProductName);
                                Console.Write("\n");
                                Console.Write("\n ------------------- ¿Qué desea modificar de este producto? -------------------");
                                Console.Write("\n 1) Nombre");
                                Console.Write("\n 2) Unidades disponibles");
                                Console.Write("\n 3) Precio");
                                Console.Write("\n Ingrese el dígito de la opción que desea modificar: ");

                                while (!int.TryParse(Console.ReadLine(), out SEL3))
                                {
                                    Console.Write("\n Sólo se permiten números. Intente nuevamente: ");
                                }

                                switch (SEL3)
                                {
                                case 1:
                                    Console.Write("\n Ingrese el nuevo nombre de este producto: ");
                                    PD.ProductName = Console.ReadLine();
                                    while (!Regex.IsMatch(PD.ProductName, @"[a-zA-Z]"))
                                    {
                                        Console.WriteLine("\n No se permiten números. Intente nuevamente: ");
                                        Console.Write("\n Ingrese el nuevo nombre de este producto: ");
                                        PD.ProductName = Console.ReadLine();
                                    }
                                    PD.ProductID = IDProd;
                                    var search = pd.Model.Products.Where(p => p.ProductID == IDProd).Select(m => m).FirstOrDefault();
                                    PD.CategoryID      = search.CategoryID;
                                    PD.Discontinued    = search.Discontinued;
                                    PD.QuantityPerUnit = search.QuantityPerUnit;
                                    PD.ReorderLevel    = search.ReorderLevel;
                                    PD.SupplierID      = search.SupplierID;
                                    PD.UnitPrice       = search.UnitPrice;
                                    PD.UnitsInStock    = search.UnitsInStock;
                                    PD.UnitsOnOrder    = search.UnitsOnOrder;
                                    pd.Model.Entry(resultPROD).State = EntityState.Detached;
                                    pd.Actualizar <Product>(PD);
                                    break;

                                case 2:
                                    Console.Write("\n Ingrese la nueva cantidad de unidades disponibles de este producto: ");
                                    PD.UnitsInStock = short.Parse(Console.ReadLine());
                                    PD.ProductID    = IDProd;
                                    var search2 = pd.Model.Products.Where(p => p.ProductID == IDProd).Select(m => m).FirstOrDefault();
                                    PD.ProductName     = search2.ProductName;
                                    PD.CategoryID      = search2.CategoryID;
                                    PD.Discontinued    = search2.Discontinued;
                                    PD.QuantityPerUnit = search2.QuantityPerUnit;
                                    PD.ReorderLevel    = search2.ReorderLevel;
                                    PD.SupplierID      = search2.SupplierID;
                                    PD.UnitPrice       = search2.UnitPrice;
                                    PD.UnitsOnOrder    = search2.UnitsOnOrder;
                                    pd.Model.Entry(resultPROD).State = EntityState.Detached;
                                    pd.Actualizar <Product>(PD);
                                    break;

                                case 3:
                                    Console.Write("\n Ingrese el nuevo precio de este producto: ");
                                    PD.UnitPrice = decimal.Parse(Console.ReadLine());
                                    PD.ProductID = IDProd;
                                    var search3 = pd.Model.Products.Where(p => p.ProductID == IDProd).Select(m => m).FirstOrDefault();
                                    PD.ProductName     = search3.ProductName;
                                    PD.CategoryID      = search3.CategoryID;
                                    PD.Discontinued    = search3.Discontinued;
                                    PD.QuantityPerUnit = search3.QuantityPerUnit;
                                    PD.ReorderLevel    = search3.ReorderLevel;
                                    PD.SupplierID      = search3.SupplierID;
                                    PD.UnitsInStock    = search3.UnitsInStock;
                                    PD.UnitsOnOrder    = search3.UnitsOnOrder;
                                    pd.Model.Entry(resultPROD).State = EntityState.Detached;
                                    pd.Actualizar <Product>(PD);
                                    break;
                                }
                            }
                            break;

                        case 3:
                            Console.Write("\n Ingrese el código del producto que desea eliminar: ");
                            while (!int.TryParse(Console.ReadLine(), out IDProd))
                            {
                                Console.Write("\n Sólo se permiten números. Intente nuevamente: ");
                            }
                            Console.WriteLine("\n Estamos procesando su búsqueda.................\n");
                            while (!pd.Listado <Product>().Exists(p => p.ProductID == IDProd))
                            {
                                Console.Write("\n Este código no pertenece a ningún producto registrado. Intente nuevamente: ");
                                IDProd = int.Parse(Console.ReadLine());
                            }
                            var resultPROD2 = pd.Listado <Product>().Find(a => a.ProductID == IDProd);
                            if (resultPROD2 != null && pd.Listado <Product>().Exists(p => p.ProductID == IDProd))
                            {
                                PD.ProductID = IDProd;
                                pd.Model.Entry(resultPROD2).State = EntityState.Detached;
                                pd.Eliminar <Product>(PD);
                            }
                            break;

                        case 4:
                            Console.Write("\n");
                            ConsoleTable TablaMuestra = new ConsoleTable("Código", "Nombre", "Suplidor", "Categoría", "Cantidad", "Precio",
                                                                         "Unidades en Stock", "Unidades pedidas");
                            foreach (Product PROD in pd.Listado <Product>())
                            {
                                TablaMuestra.AddRow(PROD.ProductID, PROD.ProductName, PROD.Supplier.CompanyName, PROD.Category.CategoryName, PROD.QuantityPerUnit,
                                                    PROD.UnitPrice, PROD.UnitsInStock, PROD.UnitsOnOrder);
                            }
                            TablaMuestra.Write(Format.Minimal);
                            break;
                        }
                        break;
                    }
                    break;

                case 2:
                    Console.Write("\n A continuación se presentan todas las facturas creadas. Favor de tomar el código de la deseada para exportar en un archivo txt. Presione Enter.");
                    Console.ReadLine();
                    Console.Write("\n");
                    ConsoleTable TablaDetallesPedidos = new ConsoleTable("Código del pedido", "Producto", "Precio", "Cantidad", "Descuento");
                    foreach (Order_Detail ORDET in odetdat.Listado <Order_Detail>())
                    {
                        TablaDetallesPedidos.AddRow(ORDET.OrderID, ORDET.Product.ProductName, ORDET.UnitPrice, ORDET.Quantity, ORDET.Discount);
                    }
                    TablaDetallesPedidos.Write(Format.Alternative);

                    Console.Write("\n Ingrese el código de la factura que desea exportar: ");
                    while (!int.TryParse(Console.ReadLine(), out IDFact))
                    {
                        Console.Write("\n Sólo se permiten números. Intente nuevamente: ");
                    }
                    var resultFact = odetdat.Listado <Order_Detail>().Find(odt => odt.OrderID == IDFact);
                    if (resultFact != null && odetdat.Listado <Order_Detail>().Exists(ordt => ordt.OrderID == IDFact))
                    {
                        odetdat.TotalProductos = 0;
                        odetdat.TotalFactura   = 0;
                        ConsoleTable TablaFacturas = new ConsoleTable("Producto", "Precio", "Cantidad", "Importe");
                        foreach (Order_Detail ORDEN in odetdat.Listado <Order_Detail>().Where(ordt => ordt.OrderID == IDFact))
                        {
                            odetdat.TotalProductos = odetdat.TotalProductos + ORDEN.Quantity;
                            odetdat.Importe        = ORDEN.Quantity * ORDEN.UnitPrice;
                            odetdat.TotalFactura   = odetdat.TotalFactura + odetdat.Importe;
                            TablaFacturas.AddRow(ORDEN.Product.ProductName, ORDEN.UnitPrice, ORDEN.Quantity, odetdat.Importe);
                        }
                        TablaFacturas.Write(Format.Alternative);
                        Console.Write("\n Total de artículos: ".PadRight(10) + odetdat.TotalProductos + "\t" + "Total a pagar: RD$".PadRight(15) + odetdat.TotalFactura);
                        Console.Write("\n");
                        var custNombre = odetdat.Model.Orders.Where(or => or.OrderID == IDFact).Select(pt => pt).FirstOrDefault();
                        using (StreamWriter Archivo = new StreamWriter(path))
                        {
                            Archivo.Write("\n Cliente: ".PadRight(10) + custNombre.Customer.CompanyName);
                            Archivo.WriteLine("\n");
                            Archivo.WriteLine(TablaFacturas);
                            Archivo.WriteLine("\n");
                            Archivo.Write("\n Total de artículos: " + odetdat.TotalProductos + "\t" + "Total a pagar: RD$" + odetdat.TotalFactura);
                        }
                        Console.Write("\n Seleccione la factura ");
                    }

                    break;

                case 3:
                    break;
                }
                x = 4;
                if (SEL > 3)
                {
                    Console.Write("\n Este dígito no corresponde al rango permitido. Presione Enter para salir. :) ");
                    Console.ReadKey();
                }
            }
        }
Exemplo n.º 37
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseStaticFiles();

            // do not change the name of defaultCulture
            var defaultCulture = "en-US";
            IList <CultureInfo> supportedCultures = new List <CultureInfo>
            {
                new CultureInfo(defaultCulture)
            };

            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture(defaultCulture),
                SupportedCultures     = supportedCultures,
                SupportedUICultures   = supportedCultures
            });

            app.UseMvc();

            // Anything unhandled
            app.Run(context =>
            {
                var defaultPage = PageTemplate.IsJPCulture ? "/default.ja.html" : "/default.html";
                context.Response.Redirect(context.Request.PathBase + defaultPage);
                return(Task.FromResult(0));
            });

            app.UseStorageProviders()
            .AddDiskStorage("ExcelRoot", Path.Combine(env.WebRootPath, "ExcelRoot"))
            .AddDiskStorage("PdfRoot", Path.Combine(env.WebRootPath, "PdfRoot"));

            var ssrsUrl      = Configuration["AppSettings:SsrsUrl"];
            var ssrsUserName = Configuration["AppSettings:SsrsUserName"];
            var ssrsPassword = Configuration["AppSettings:SsrsPassword"];

            app.UseReportProviders()
            .AddFlexReportDiskStorage("ReportsRoot", Path.Combine(env.WebRootPath, "ReportsRoot"))
            .AddSsrsReportHost("c1ssrs", ssrsUrl, new System.Net.NetworkCredential(ssrsUserName, ssrsPassword));

            var oneDriveAccessToken = Configuration["AppSettings:OneDriveAccessToken"];

            app.UseStorageProviders().AddOneDriveStorage("OneDrive", oneDriveAccessToken);

            string[] scopes          = { DriveService.Scope.Drive };
            string   applicationName = "C1WebApi";

            // Azure storage
            app.UseStorageProviders().AddAzureStorage("Azure", Configuration["AppSettings:AzureStorageConnectionString"]);

            // please uncomment this line when you want to test GoogleDrive service.
            // Google storage
            //app.UseStorageProviders().AddGoogleDriveStorage("GoogleDrive", GetUserCredential(scopes), applicationName);

            // Dropbox storage
            app.UseStorageProviders().AddDropBoxStorage("DropBox", Configuration["AppSettings:DropBoxStorageAccessToken"], applicationName);

            // AWS storage
            var    aWSAccessToken = Configuration["AppSettings:AWSStorageAccessToken"];
            var    secretKey      = Configuration["AppSettings:AWSStorageSecretKey"];
            var    bucketName     = Configuration["AppSettings:AWSStorageBucketName"];
            string region         = "us-east-1";

            app.UseStorageProviders().AddAWSStorage("AWS", aWSAccessToken, secretKey, bucketName, region);

            app.UseDataProviders()
            .AddItemsSource("Sales", () => Sale.GetData(10).ToList())
            .AddItemsSource("Orders", () => CustomerOrder.GetOrderData(20).ToList())
            .Add("Nwind", new SqlDataProvider(GetConnectionString(env)));

            var dataPath = Path.Combine(env.WebRootPath, "Data");

            app.UseDataEngineProviders()
            .AddDataEngine("complex10", () =>
            {
                return(ProductData.GetData(100000));
            })
            .AddDataEngine("complex50", () =>
            {
                return(ProductData.GetData(500000));
            })
            .AddDataEngine("complex100", () =>
            {
                return(ProductData.GetData(1000000));
            })
            .AddDataSource("dataset10", () => ProductData.GetData(100000).ToList())
            .AddDataSource("dataset50", () => ProductData.GetData(500000).ToList())
            .AddDataSource("dataset100", () => ProductData.GetData(1000000).ToList())
            .AddCube("cube",
                     @"Data Source=http://ssrs.componentone.com/OLAP/msmdpump.dll;Provider=msolap;Initial Catalog=AdventureWorksDW2012Multidimensional",
                     "Adventure Works");

            C1Controller.CacheDataEngineDataKey(app);
        }
Exemplo n.º 38
0
 public override void SetData(ObjData data)
 {
     base.SetData(data);
     this.data = data as ProductData;
 }
Exemplo n.º 39
0
        public ActionResult CreateProductsAndGroup()
        {
            // fetching the connected e-conomic session 
            var session = EcoSession;
            if (session == null) return View("ExampleView");

            try
            {
                //create a product-group for the new product
                var accHandle = session.Account_FindByNumber(1010);
                var productGroup = new ProductGroupData
                {
                    Number = 1,
                    Name = "Fruits",
                    AccountForVatLiableDebtorInvoicesCurrentHandle = accHandle
                };
                ProductGroupHandle productGroupHandle = session.ProductGroup_CreateFromData(productGroup);

                //create produkts
                var product1 = new ProductData
                {
                    Number = "1",
                    Name = "Apples",
                    SalesPrice = 5,
                    IsAccessible = true,
                    ProductGroupHandle = productGroupHandle
                };
                var product2 = new ProductData
                {
                    Number = "2",
                    Name = "Grapes",
                    SalesPrice = 10,
                    IsAccessible = true,
                    ProductGroupHandle = productGroupHandle
                };
                var products = new ProductData[] { product1, product2 };

                ProductHandle[] productsHandle = session.Product_CreateFromDataArray(products);

                productGroup.Handle = productGroupHandle;
                for (int i = 0; i < productsHandle.Length; i++)
                    products[i].Handle = productsHandle[i];

                EconomicModels.ProductGroup = productGroup;
                EconomicModels.Products = products;

            }
            catch (Exception e)
            {
                return ReturnWithError(e.Message);
            }

            ViewData["message"] = "Products and productgroup created!";

            return View("ExampleView");
        }
Exemplo n.º 40
0
        public void UpdateData(ProductData oldProductData, ProductData newProductData)
        {
            var productView = productViews[oldProductData];

            productView.Show(newProductData);
        }
Exemplo n.º 41
0
        private IEnumerable<string> DeepHarvestDPNode(HtmlNode node, ProductData product)
        {
            var ignoreList = new List<string>();

            // ignoreList.Add("http://www.hm.com/gb/product/07049?article=07049-B");

            var productLink = node.SelectNodes("li[@class='product_description']/a").First().Attributes["href"].Value;
            if (ignoreList.Contains(productLink))
            {
                return new[] { "skip" };
            }

            var mainProductHtml = new HtmlDocument();
            var doc = HtmlNode.CreateNode("");
            IEnumerable<string> images = new string[0];
            try
            {
                mainProductHtml.LoadHtml(GetHtmlString(productLink));

                GetValue(productLink);

                //var s = b.Document.Body.InnerHtml;
                //doc = HtmlNode.CreateNode(s);

                var t = Doc;
                // //div[@id="productright"]/div[@class=product_info]/p
                doc = mainProductHtml.DocumentNode;
                var imgSrc = doc.SelectNodes("//img[@id='product-image']").First().Attributes["src"].Value.Replace(" ", "%20");
                images = new[] { imgSrc.StartsWith("//") ? "http:" + imgSrc : imgSrc };

                var body = doc.SelectNodes("//div[@class='description']/p")
                        .First()
                        .InnerText
                        .Replace("\"", "'")
                        .Replace("- US size - refer to size chart for conversion", "")
                        .Replace("See Return Policy", "")
                        .Replace("\t", " ")
                        .Replace("/t", " ")
                        .Replace("&trade;", "")
                        .Replace("&amp;", "and")
                        .Replace("&", "and")
                        .Replace("&nbsp;", " ")
                        .Replace("&eacute", "e")
                        .Replace("&acute", "e")
                        .Trim();

                product.Body = "\"" + body + "\"";

                product.Type = productType;
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception thrown trying to parse: {0}", productLink);
            }

            /*var xsmall = new HtmlNode(HtmlNodeType.Element, mainProductHtml, 0)
            {
                InnerHtml = "3"
            };
            var small = new HtmlNode(HtmlNodeType.Element, mainProductHtml, 1)
            {
                InnerHtml = "4"
            };
            var medium = new HtmlNode(HtmlNodeType.Element, mainProductHtml, 2)
            {
                InnerHtml = "5"
            };
            var large = new HtmlNode(HtmlNodeType.Element, mainProductHtml, 3)
            {
                InnerHtml = "6"
            };
            var xlarge = new HtmlNode(HtmlNodeType.Element, mainProductHtml, 4)
            {
                InnerHtml = "7"
            };
            var xxlarge = new HtmlNode(HtmlNodeType.Element, mainProductHtml, 5)
            {
                InnerHtml = "8"
            };
            var xxxlarge = new HtmlNode(HtmlNodeType.Element, mainProductHtml, 6)
            {
                InnerHtml = "9"
            };
            var xxxxlarge = new HtmlNode(HtmlNodeType.Element, mainProductHtml, 7)
            {
                InnerHtml = "40M"
            };
            var xxxxxlarge = new HtmlNode(HtmlNodeType.Element, mainProductHtml, 8)
            {
                InnerHtml = "40L"
            };
            var xl = new HtmlNode(HtmlNodeType.Element, mainProductHtml, 9)
            {
                InnerHtml = "42S"
            };
            var xxl = new HtmlNode(HtmlNodeType.Element, mainProductHtml, 10)
            {
                InnerHtml = "42M"
            };
            var xxxl = new HtmlNode(HtmlNodeType.Element, mainProductHtml, 11)
            {
                InnerHtml = "42L"
            };
            var xl1 = new HtmlNode(HtmlNodeType.Element, mainProductHtml, 12)
            {
                InnerHtml = "44S"
            };
            var xxl1 = new HtmlNode(HtmlNodeType.Element, mainProductHtml, 13)
            {
                InnerHtml = "44M"
            };
            var xxxl1 = new HtmlNode(HtmlNodeType.Element, mainProductHtml, 14)
            {
                InnerHtml = "44L"
            };*/

            // var sizes = new HtmlNode[] { xsmall, small, medium, large, xlarge, xxlarge, xxxlarge, xxxxlarge, xl, /*xxl, xxxl, xl1, xxl1, xxxl1 */};
            var sizes = new List<HtmlNode>();
            IEnumerable<HtmlNode> sizeNodes = null;
            try
            {
                sizeNodes = doc.SelectNodes("//ul[@id='options-variants']/li")
                               .Where(x => x.Attributes["class"].Value != "outOfStock");
            }
            catch
            {
                Console.WriteLine("Failed to get sizes for node: {0}", productLink);
                return new[] { "skip" };
            }
            foreach (var sizeNode in sizeNodes)
            {
                var count = sizes.Count;
                var innerText = sizeNode
                    .InnerText
                    .Replace("\t", string.Empty)
                    .Replace("/r", string.Empty)
                    .Replace("/n", string.Empty)
                    .Trim();

                var htmlNode = new HtmlNode(HtmlNodeType.Element, mainProductHtml, count)
                    {
                        InnerHtml = "\"" + innerText + "\""
                    };
                sizes.Add(htmlNode);
            }

            if (!sizes.Any()) return new[] { "skip" };

            product.Option1Name = "Size";
            product.Option1Value = sizes.First().InnerText;

            product.Sku = productLink;
            product.Taxable = "FALSE";
            product.RequiresShipping = "TRUE";
            product.FulfillmentService = "manual";
            product.InventoryPolicy = "continue";
            product.Vendor = vendor;
            product.InventoryQuantity = "0";
            product.Tags = productType;
            product.Sizes = sizes;

            return images;
        }
Exemplo n.º 42
0
        public List <ProductModel> Get()
        {
            ProductData data = new ProductData(_config);

            return(data.GetProducts());
        }
 public static void UpdatePriceToDb(int productID, ProductData data)
 {
     ConstantManager.IsUpdateRunning = true;
     //Convert Price
     double valPrice = 0;
     if (data != null)
     {
         if (!String.IsNullOrEmpty(data.Price))
         {
             valPrice = PriceHelper.ConvertPrice(data.Price);
         }
     }
     using (var context = new CPS_SolutionEntities())
     {
         var alias = context.AliasProducts.Where(x => x.ID == productID).FirstOrDefault();
         if (alias != null)
         {
             if (valPrice != 0 && valPrice != alias.Price)
             {
                 alias.Price = valPrice;
                 alias.UpdateTime = DateTime.Now;
                 context.SaveChanges();
             }
         }
         ConstantManager.IsUpdateRunning = false;
     }
 }
        private IEnumerable<string> DeepHarvestMatalanNode(HtmlNode node, ProductData product)
        {
            var ignoreList = new List<string>();

            // ignoreList.Add("http://www.hm.com/gb/product/07049?article=07049-B");

            var productLink = node.SelectNodes("div/a").First().Attributes["href"].Value.Replace("&amp;", "&");
            if (ignoreList.Contains(productLink))
            {
                return new[] { "skip" };
            }

            var mainProductHtml = new HtmlDocument();
            var doc = HtmlNode.CreateNode("");
            IEnumerable<string> images = new string[0];
            try
            {
                mainProductHtml.LoadHtml(GetHtmlString(productLink));
                // //div[@id="productright"]/div[@class=product_info]/p
                doc = mainProductHtml.DocumentNode;
                var imgSrc = doc.SelectNodes("//img[@id='mainProductImage']").First().Attributes["src"].Value.Replace(" ", "%20");
                images = new[] { imgSrc.StartsWith("//") ? "http:" + imgSrc : imgSrc };

                var htmlNode = doc.SelectNodes("//div[contains(@class,'tab_content')]").First().SelectNodes("//div[contains(@class, 'info')]").First().SelectNodes("//ul/li/p").First();
                var body = htmlNode
                        .InnerText
                        .Replace("\"", "'")
                        .Replace("Free Delivery with All Suits Over £50!", "'")
                        .Replace("- US size - refer to size chart for conversion", "")
                        .Replace("See Return Policy", "")
                        .Replace("\t", " ")
                        .Replace("/t", " ")
                        .Replace("&trade;", "")
                        .Replace("&amp;", "and")
                        .Replace("&", "and")
                        .Replace("&nbsp;", " ")
                        .Replace("&eacute", "e")
                        .Replace("&acute", "e")
                        .Trim();

                product.Body = "\"" + body + "\"";

                product.Type = productType;
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception thrown trying to parse: {0}", productLink);
            }

            var sizes = new List<HtmlNode>();
            IEnumerable<HtmlNode> sizeNodes = null;
            try
            {
                sizeNodes = doc.SelectNodes("//ul[@id='alternativeSizes']/li/label")
                               .Where(x => x.ParentNode.Attributes["class"].Value == "in_stock");
            }
            catch
            {
                Console.WriteLine("Failed to get sizes for node: {0}", productLink);
                return new[] { "skip" };
            }
            foreach (var sizeNode in sizeNodes)
            {
                var count = sizes.Count;
                var innerText = sizeNode
                    .InnerText
                    .Replace("\t", string.Empty)
                    .Replace("/r", string.Empty)
                    .Replace("/n", string.Empty)
                    .Trim();

                var htmlNode = new HtmlNode(HtmlNodeType.Element, mainProductHtml, count)
                {
                    InnerHtml = "\"" + innerText + "\""
                };
                sizes.Add(htmlNode);
            }

            if (!sizes.Any()) return new[] { "skip" };

            product.Option1Name = "Size";
            product.Option1Value = sizes.First().InnerText;

            product.Sku = "\"" + productLink + "\"";
            product.Taxable = "FALSE";
            product.RequiresShipping = "TRUE";
            product.FulfillmentService = "manual";
            product.InventoryPolicy = "continue";
            product.Vendor = vendor;
            product.InventoryQuantity = "0";
            product.Tags = productType;
            product.Sizes = sizes;

            return images;
        }
        public static void InsertProductToDb(ProductData data, ProductParserCreator model)
        {
            //create list of Att
            List<Hardware> listAttDic = new List<Hardware>();
            if (data != null)
            {
                //Convert Price
                double valPrice = 0;
                if (!String.IsNullOrEmpty(data.Price))
                {
                    valPrice = PriceHelper.ConvertPrice(data.Price);
                }
                else
                {
                    valPrice = 0;
                }
                if (data.Image.Contains("default.jpg"))
                {
                    data.Image = "Images/I/default.jpg";
                }

                if (!String.IsNullOrEmpty(data.Name) && !String.IsNullOrEmpty(data.CPU) &&
                    !String.IsNullOrEmpty(data.HDD) && !String.IsNullOrEmpty(data.RAM) &&
                    !String.IsNullOrEmpty(data.VGA) && !String.IsNullOrEmpty(data.Display))
                {
                    using (var context = new CPS_SolutionEntities())
                    {
                        //Add table product
                        var prod = new Product
                        {
                            Description = "Chưa cập nhật ",
                            ImageURL = data.Image,
                            TotalWeightPoint = 0,
                            IsActive = null,
                        };
                        //Check for Store

                        var store = context.Stores.Where(x => model.ParseProductLink.Contains(x.StoreUrl)).FirstOrDefault();
                        int StoreID = 1;
                        string patter = "://|/";
                        Regex reg = new Regex(patter);
                        string host = reg.Split(model.ParseProductLink)[1];
                        if (store != null)
                        {
                            StoreID = store.ID;
                        }
                        else
                        {
                            var newStore = new Store
                            {
                                IsActive = false,
                                LogoImage = "default",
                                StoreUrl = host,
                                StoreName = "Chưa xác định",

                            };
                            context.Stores.Add(newStore);
                            context.SaveChanges();
                            StoreID = newStore.ID;
                        }

                        int brand = 13;
                        var allBrands = context.Brands.ToList();
                        foreach (var item in allBrands)
                        {
                            if (model.ParseProductLink.ToUpper().Contains(item.BrandName.ToUpper()))
                            {
                                brand = item.ID;
                            }
                            else if (model.ParseProductLink.ToUpper().Contains("MACBOOK"))
                            {
                                brand = 3;
                            }
                            else
                            {
                                brand = 12;
                            }
                        }

                        prod.AliasProducts.Add(new AliasProduct()
                                        {
                                            Name = data.Name,
                                            URL = model.ParseProductLink,
                                            Price = valPrice,
                                            StoreID = StoreID,
                                            IsMain = true,
                                            IsActive = true,
                                            UpdateTime = DateTime.Now,
                                            BrandID = brand
                                        });
                        context.Products.Add(prod);
                        context.SaveChanges();

                        List<KeyValuePair<string, string>> listofAttributes = new List<KeyValuePair<string, string>>();

                        var cpu = new KeyValuePair<string, string>(data.CPU, "C");
                        var ram = new KeyValuePair<string, string>(data.RAM, "R");
                        var vga = new KeyValuePair<string, string>(data.VGA, "V");
                        var hdd = new KeyValuePair<string, string>(data.HDD, "H");
                        var display = new KeyValuePair<string, string>(data.Display, "D");

                        listofAttributes.Add(cpu);
                        listofAttributes.Add(ram);
                        listofAttributes.Add(hdd);
                        listofAttributes.Add(vga);
                        listofAttributes.Add(display);
                        int count = 0;

                        //add 5 attribute for 1 product
                        foreach (var attribute in listofAttributes)
                        {

                            ////Check good match
                            var goodMatch = new List<int>();
                            var averageMatch = new List<int>();
                            int pId = -1;
                            bool wholeMatch = false;
                            string codeType = "C";

                            if (count == 1)
                            {
                                codeType = "R";
                            }
                            else if (count == 2)
                            {
                                codeType = "H";
                            }
                            else if (count == 3)
                            {
                                codeType = "V";
                            }
                            else if (count == 4)
                            {
                                codeType = "D";
                            }
                            count++;
                            foreach (var alias in context.Dictionaries.Where(x => x.Hardware.IsActive == true && x.Hardware.CodetypeID.Equals(codeType)))
                            {
                                if (attribute.Key == alias.Name)
                                {
                                    wholeMatch = true;
                                    pId = alias.AttributeDicID;

                                    break;
                                }
                                double matchPercent = CompareStringHelper.CompareString(attribute.Key, alias.Name);
                                //good match
                                if (matchPercent > 90)
                                {
                                    goodMatch.Add(alias.AttributeDicID);
                                }
                                // normal Match
                                if (matchPercent > 80)
                                {
                                    averageMatch.Add(alias.AttributeDicID);
                                }

                            }
                            if (!wholeMatch)
                            {
                                if (goodMatch.Count == 1)
                                {
                                    // Match well with only 1 product, take it
                                    pId = goodMatch[0];

                                }
                                else if (goodMatch.Count > 1)
                                {
                                    // Match well with more than 1 product, admin decide
                                    ExportTrainingFileForProduct(goodMatch, attribute.Key, prod.ID);
                                    continue;
                                }
                                else if (averageMatch.Count > 0 && pId == -1)
                                {
                                    // Only average match, admin decide
                                    ExportTrainingFileForProduct(averageMatch, attribute.Key, prod.ID);
                                    continue;
                                }
                            }

                            // If attDic alr Existed?
                            if (pId != -1)
                            {
                                var productAtt = new ProductAttribute
                                {
                                    ProductID = prod.ID,
                                    AttributeID = pId,
                                    IsActive = true
                                };
                                context.ProductAttributes.Add(productAtt);
                                context.SaveChanges();
                            }
                            else
                            {
                                //Add a new record
                                var newADitem = new Hardware { Name = attribute.Key, CodetypeID = attribute.Value, WeightCriteraPoint = 0 };

                                // Add new item for Product Attribute
                                var productAtt = new ProductAttribute
                                {
                                    ProductID = prod.ID,
                                    AttributeID = newADitem.ID,
                                };
                                try
                                {
                                    // Save change into DB
                                    context.Hardwares.Add(newADitem);
                                    context.ProductAttributes.Add(productAtt);
                                    context.SaveChanges();
                                    var aliasDic = new Dictionary
                                    {
                                        AttributeDicID = newADitem.ID,
                                        Name = newADitem.Name,
                                        IsActive = true,
                                    };
                                    context.Dictionaries.Add(aliasDic);
                                    context.SaveChanges();
                                }
                                catch (DbUpdateException)
                                {
                                    // Do nothing
                                }
                            }
                        }
                    }
                }
            }
        }
 public ViewModel()
 {
     this.data            = new ProductData();
     Products             = data.Products;
     PullToRefreshCommand = new Command(ExecutePullToRefreshCommand);
 }
Exemplo n.º 47
0
 private Product MapData(ProductData productData)
 {
     return(new Product(productData.ProductID, productData.Name, productData.WeightInPounds));
 }
Exemplo n.º 48
0
        // list all rows from table
        public DataSet List()
        {
            ProductData dao = new ProductData(ConnStr);

            return(dao.List());
        }
        public IEnumerable<ProductData> RecurseNodes(HtmlDocument document)
        {
            var nodes = document.DocumentNode.SelectNodes("//div[contains(@class,'productCont')]");

            var data = new List<ProductData>();

            var titleAndHandle = new Dictionary<string, string>();

            foreach (var node in nodes)
            {
                var img = node.SelectNodes("div[contains(@class,'productImageCont')]/a/img[starts-with(@id, 'product_')]")
                              .First()
                              .Attributes["src"]
                              .Value
                              .TrimStart(new[] { '.' })
                              .Split(new[] { "?" }, StringSplitOptions.None)[0];

                var title =
                    node.SelectNodes("div[@class='productTitle']/h2/a")
                    .First()
                    .InnerText
                    .Replace("\n", "")
                    .Replace("\t", "")
                    .Replace("É", "E")
                    .Replace("É".ToLower(), "e")
                    .Trim();

                var price = (
                                (Convert.ToDouble(
                                    node.SelectNodes("div[@class='productPrice']/p/span").First().InnerText
                                        .Replace("\n", "")
                                        .Replace("\t", "")
                                        .Replace("\r", "")
                                        .Replace("GBP", "")
                                        .Replace("&pound;", string.Empty)
                                        .Replace("from", string.Empty)
                                        .Replace("From", string.Empty)
                                        .Replace("now", string.Empty)
                                        .Replace("&nbsp;", string.Empty)
                                        .Replace("£", "")
                                        .Trim()
                                        .Split(new[] { " was " }, StringSplitOptions.RemoveEmptyEntries)[0]
                                ) * profitRate + deliveryRate) * cardRate).ToString("0.00");

                var handle = (productType + " " + Guid.NewGuid()).Replace(" ", "-");
                handle = CheckHandle(handle, titleAndHandle);
                titleAndHandle.Add(handle, title);

                var product = new ProductData { Image = img, Title = title, Price = price, Handle = handle };

                var images = DeepHarvestMatalanNode(node, product).ToList();
                if (images.First() == "skip") continue;

                //data.Add(product);
                var count = 0;
                foreach (var size in product.Sizes)
                {
                    if (count == 0)
                    {
                        //if (data.Contains())
                        data.Add(product);
                        count++;
                        continue;
                    }
                    var subProduct = ProductData.Clone(product);
                    subProduct.Option1Name = "Size";
                    subProduct.Option1Value = size.InnerText;
                    if (images.Count >= count)
                    {
                        subProduct.Image = "\"" + images[count - 1] + "\"";
                    }
                    count++;
                    data.Add(subProduct);

                }
            }
            return data;
        }
Exemplo n.º 50
0
 public HomeController(ProductData productData)
 {
     data = productData;
 }
Exemplo n.º 51
0
        public ActionResult Dproduct(string id)
        {
            if (Session["Member"] == null)
            {
                return RedirectToAction("login");
            }

            Product p = new Product();
            p.Pid = Convert.ToInt32(id);
            ProductData pd = new ProductData();
            pd.Delete(p);
            return RedirectToAction("Conter", new { tabid = "1", m = "1" });
        }
Exemplo n.º 52
0
 public HomeController(ProductData productData, DataContext dataContext, IMapper mapper)
 {
     this.productData = productData;
     this.dataContext = dataContext;
     this.mapper      = mapper;
 }
Exemplo n.º 53
0
	void AddProductToBalance(ProductData productData)
	{
		switch(productData.commodity)
		{
			default:
			case Commodity.LIVES: mainMenu.NumLives += productData.quantity; break;
			case Commodity.BOMBS: mainMenu.NumBombs += productData.quantity; break;
		}

	}
Exemplo n.º 54
0
 /// <summary>
 /// обёрточка небольшая
 /// </summary>
 /// <param name="data"></param>
 static void CallOnPurchaseSucess(ProductData data)
 {
     OnPurchaseSuccess?.Invoke(data);
 }
Exemplo n.º 55
0
		public override bool PurchaseProductAsync(ProductData product)
		{
			InvokeOnTransactionFinished(product, true);
			return true;
		}
Exemplo n.º 56
0
    public void ShopListCallBack(C2sSprotoType.shop_all.response resp)
    {
        normalList = new List <ProductData>();
        pointList  = new List <ProductData>();
        dataList   = new List <ProductData>();
        for (int i = 0; i < resp.l.Count; i++)
        {
            ProductData d = new ProductData();
            d.data                  = GameShared.Instance.GetItemData((int)resp.l[i].g_prop_csv_id);
            d.csv_id                = (int)resp.l[i].csv_id;
            d.g_prop_csv_id         = (int)resp.l[i].g_prop_csv_id;
            d.inventory             = (int)resp.l[i].inventory;
            d.currency_type         = (int)resp.l[i].currency_type;
            d.currency_num          = (int)resp.l[i].currency_num;
            store_refresh_count_max = (int)resp.store_refresh_count_max;
            goods_refresh_count     = (int)resp.goods_refresh_count;
            Debug.Log("id" + resp.l[i].g_prop_csv_id + "time" + resp.l[i].countdown);
            d.countdown    = (int)resp.l[i].countdown;
            d.refresh_time = DateTime.Now.AddSeconds(d.countdown);
            switch (d.currency_type)
            {
            case 1:
                d.currency_icon = Def.DiamondTex;
                break;

            case 2:
                d.currency_icon = Def.CoinTex;
                break;

            case 3:
                d.currency_icon = "金币";
                break;

            case 4:
                d.currency_icon = "金币";
                break;
            }
            d.isHot = false;

            if (d != null)
            {
                if (resp.l[i].countdown != null)
                {
                    int a = (int)resp.l[i].countdown;
                    d.isShowTime = true;
                }
                else
                {
                    d.isShowTime = false;
                }
                dataList.Add(d);
            }

            if (d.csv_id / 1000 == 1)
            {
                normalList.Add(d);
            }
            else
            {
                pointList.Add(d);
            }
        }
        SetPopList(dataList);
    }
Exemplo n.º 57
0
		public abstract bool PurchaseProductAsync(ProductData product);
Exemplo n.º 58
0
        public IEncodedString ProductOption(ProductData productdata, int index, String attributes = "", Boolean required = false)
        {
            var strOut = "";

            var objL = productdata.Options;

            if (objL.Count > index)
            {
                var obj        = objL[index];
                var optid      = obj.GetXmlProperty("genxml/hidden/optionid");
                var optvalList = productdata.GetOptionValuesById(optid);

                strOut += "<div  class='option option" + (index + 1) + "' " + attributes + ">";
                strOut += "<span class='optionname optionname" + (index + 1) + "'>" + obj.GetXmlProperty("genxml/lang/genxml/textbox/txtoptiondesc") + "</span>";
                strOut += "<span class='optionvalue optionvalue" + (index + 1) + "'>";

                if (optvalList.Count > 1)
                {
                    //dropdown
                    strOut += "<select id='optionddl" + (index + 1) + "' update='save'>";
                    foreach (var optval in optvalList)
                    {
                        var addcost          = optval.GetXmlPropertyDouble("genxml/textbox/txtaddedcost");
                        var addedcostdisplay = "";
                        if (addcost > 0)
                        {
                            addedcostdisplay = "    (+" + NBrightBuyUtils.FormatToStoreCurrency(addcost) + ")";
                        }


                        strOut += "    <option value='" + optval.GetXmlProperty("genxml/hidden/optionvalueid") + "'>" + optval.GetXmlProperty("genxml/lang/genxml/textbox/txtoptionvaluedesc") + addedcostdisplay + "</option>";
                    }
                    strOut += "</select>";
                }
                if (optvalList.Count == 1)
                {
                    //checkbox
                    foreach (var optval in optvalList)
                    {
                        var addcost          = optval.GetXmlPropertyDouble("genxml/textbox/txtaddedcost");
                        var addedcostdisplay = "";
                        if (addcost > 0)
                        {
                            addedcostdisplay = "    (+" + NBrightBuyUtils.FormatToStoreCurrency(addcost) + ")";
                        }

                        strOut += "    <input id='optionchk" + (index + 1) + "' type='checkbox' " + attributes + " update='save' /><label>" + optval.GetXmlProperty("genxml/lang/genxml/textbox/txtoptionvaluedesc") + addedcostdisplay + "</label>";
                    }
                }
                if (optvalList.Count == 0)
                {
                    // textbox
                    var requiredattr = "";
                    if (required)
                    {
                        requiredattr = " required='' name='optiontxt" + (index + 1) + "'";           // name also needs to be added for JQuery Validation to work correctly
                    }
                    strOut += "<input id='optiontxt" + (index + 1) + "' " + requiredattr + " update='save' type='text' />";
                }
                strOut += "<input id='optionid" + (index + 1) + "' update='save' type='hidden' value='" + optid + "' />";
                strOut += "</span>";
                strOut += "</div>";
            }


            return(new RawString(strOut));
        }
Exemplo n.º 59
0
 public DetailController(ProductData productData)
 {
     this.productData = productData;
 }
    public override void enter()
    {
        base.enter();
        if (viewTarget == null)
        {
            target        = viewData as ProductData;
            targetWall    = target.targetWall;
            targetProduct = mainpagedata.getProduct(target.seekId);
            targetSize    = targetProduct.size;
            targetVO      = mainpagedata.getGoods(target.seekId);
            optionsController.selectMachine = selectGoods3DMachine;

            GameObject go;
            if (selectEmtyObj == null)
            {
                go                  = GameObject.CreatePrimitive(PrimitiveType.Cube);
                selectEmtyObj       = new GameObject("selectEmtyObj");
                go.transform.parent = selectEmtyObj.transform;
            }
            else
            {
                go = selectEmtyObj.transform.GetChild(0).gameObject;
            }
            selectEmtyObj.gameObject.SetActive(true);
            Vector3 size = targetProduct.size;
            go.transform.localScale    = size;
            go.transform.localPosition = size.y / 2 * Vector3.up;
            targetObj = selectEmtyObj;

            Vector3 v3 = target.position;
            v3.y = target.height;
            switch (targetVO.type)
            {
            case 3:    //吊顶
            {
                v3.y = target.height - targetSize.y;
            }
            break;

            case 4:    //地毯
            {
                v3.y = -0.001f + target.height;
            }
            break;

            case 5:    //天花板
            {
                v3.y = target.height - 0.001f;
            }
            break;

            default:
                break;
            }
            targetObj.transform.position = v3;

            string outUrl = targetVO.modelUri;
            loader = LoaderPool.WaitOutterLoad(outUrl, SimpleLoadDataType.prefabAssetBundle, onloaded, null);
            //在3D刷新时移除 3D自己刷新会去加载拥有的模型  若不加入 加载过程中被刷新会在加载完成时候出现多余项
            view3D.loaders.Add(loader);
            return;
        }
        target        = (viewTarget as Goods3DView).data;
        targetWall    = target.targetWall;
        targetVO      = mainpagedata.getGoods(target.seekId);
        targetProduct = mainpagedata.getProduct(target.seekId);
        targetSize    = targetProduct.size;
        optionsController.selectMachine = selectGoods3DMachine;
        targetObj = viewTarget.gameObject;

        RefreshRotateAndMoveHeight(true);

        selectGoods3DMachine.setState(EditTypeOnSelect.Free);

        cameraMachion.addEventListener(CameraEvent.ViewChange, OnViewChange);
    }