public ActionResult CreateProduct(Product product)
        {
            products.Insert(product);
            products.Commit();

            return RedirectToAction("ProductList");
        }
Exemplo n.º 2
0
        public GRNItemModel Add(Product product, DiscriminatorPengirimanBarang discriminator, int qty)
        {
            GRNItemModel item = null;
            item = FindByBarcode(product.Barcode, product.TenanId,discriminator);
            if (item != null)
            {
                item.Qty = qty;
                item.CalculateTotal();
            }
            else
            {
                Unit defaultUnit = MasterDataRepository.FindAllUnits(product.TenanId).Where(u => u.UnitId == product.UnitId).FirstOrDefault();
                item = new GRNItemModel()
                {
                    UserId = context.User.Identity.Name,
                    ProductId = product.ProductId,
                    Barcode = product.Barcode,
                    Code = product.Kode,
                    TenanId = product.TenanId,
                    NamaBarang = product.Nama,
                    Qty = qty,
                    Unit = product.UnitName,
                    Harga = product.HargaJual,
                    Jumlah = product.HargaJual * qty,
                    UnitId = defaultUnit == null ? Guid.Empty : defaultUnit.ModelGuid,
                    Discriminator = Enum.GetName(typeof(DiscriminatorPengirimanBarang), discriminator)
                };
                ap1Db.GRNItem.Add(item);
            }
            ap1Db.SaveChanges();

            return item;
        }
Exemplo n.º 3
0
 public async Task<Boolean> AddToCart(int cartId, Product product, int Quantity)
 {
     using (var db = ResolveDBContextFactory())
     {
         var cart = db.Carts.FirstOrDefault(o => o.Id == cartId);
         if (cart != null)
         {
             var existingsaleitem =
                 await db.SaleItems.FirstOrDefaultAsync(o => o.CartId == cart.Id && o.ProductId == product.Id);
             if (existingsaleitem != null)
             {
                 existingsaleitem.Quantity += Quantity;
             }
             else
             {
                 SaleItem item = new SaleItem() {
                     ProductId = product.Id,
                     Quantity = Quantity,
                     CartId = cartId,
                     Cart = cart
                 };
                 db.SaleItems.Add(item); 
             }
             await db.SaveChangesAsync();
             return true;
         }
         throw  new Exception("no active shopping cart is found");
     }
 }
        public ActionResult EditProduct(Product product)
        {
            products.Update(product);
            products.Commit();

            return RedirectToAction("ProductList");
        }
        public IHttpActionResult PutProduct(int id, Product product)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != product.ProductID)
            {
                return BadRequest();
            }

            db.Entry(product).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
Exemplo n.º 6
0
        public void UpdateProduct(ProductViewModel productViewModel)
        {
            var isNew = false;

            var product = _dbContext.Products
                .SingleOrDefault(p => p.UniqueName == productViewModel.UniqueName);

            if (product == null)
            {
                isNew = true;
                product = new Product();
            }

            product.CategoryId = productViewModel.CategoryId;
            product.UniqueName = productViewModel.UniqueName;
            product.Color = productViewModel.Color;
            product.Description = productViewModel.Description;
            product.ImagePath = productViewModel.ImagePath;
            product.SortOrder = productViewModel.SortOrder;

            if (isNew)
                _dbContext.Products.Add(product);

            _dbContext.SaveChanges();
        }
Exemplo n.º 7
0
        public void Add(int id, string name, string supplier, double price)
        {
            if (products.ContainsKey(id))
            {
                this.Remove(id);
            }

            Product newProduct = new Product(id, name, supplier, price);

            // Add product by Id
            this.products.Add(id, newProduct);

            // Add product by Price Range
            this.productsByPriceRange.AppendValueToKey(price, newProduct);

            // Add product by Title
            this.productsByTitle.AppendValueToKey(name, newProduct);

            // Add product by Title and Price
            this.productsByTitleAndPrice.AppendValueToKey(this.CombineTwoParams(name, price), newProduct);

            // Add product by Title and Price range
            this.productsByPriceRangeAndTitle.EnsureKeyExists(name);
            this.productsByPriceRangeAndTitle[name].AppendValueToKey(price, newProduct);

            // Add product by Supplier and Price
            this.productsBySupplierAndPrice.AppendValueToKey(this.CombineTwoParams(supplier, price), newProduct);

            // Add product by Supplier and Price Range
            this.productsByPriceRangeAndSupplier.EnsureKeyExists(supplier);
            this.productsByPriceRangeAndSupplier[supplier].AppendValueToKey(price, newProduct);
        }
 public void Context()
 {
     Product productInOrder = new Product(10m);
     Product productNotInOrder = new Product(20m);
     Coupon coupon = CreateCoupon.For(productNotInOrder).WithDiscountOf(.1m);
     _order = CreateOrder.Of(productInOrder).Apply(coupon).In(StateOf.UT);
 }
        public object Post(Product request)
        {
            var id = Products.Create(request);
            request.Id = id;

            return new HttpResult(new ProductResponse { Product = request }, HttpStatusCode.Created);
        }
Exemplo n.º 10
0
        public ActionResult Add([Bind(Prefix = "AddForm")] ProductsAddForm form)
        {
            var model = new ProductsAddViewModel { AddForm = form };

            if (ModelState.IsValid)
            {
                using (var transaction = _session.BeginTransaction())
                {
                    var product = new Product
                                  {
                                      Name = form.Name,
                                      Description = form.Description ?? string.Empty
                                  };

                    var primaryVariant = new ProductVariant
                                         {
                                             Price = form.Price.Value,
                                             Sku = form.Sku ?? string.Empty,
                                             Product = product
                                         };

                    product.Variants = new[] { primaryVariant };

                    _session.Save(product);
                    transaction.Commit();
                    return RedirectToAction("View", new { id = product.Id });
                }
            }

            SetupAddViewModel(model);
            return View(model);
        }
Exemplo n.º 11
0
        public void AddToCart(Product product, decimal price)
        {
            // Get the matching cart and product instances
            var cartItem = db.CartItems.SingleOrDefault(
                c => c.CartID == ShoppingCartId
                && c.ProductID == product.ProductID);

            if (cartItem == null)
            {
                // Create a new cart item if no cart item exists
                cartItem = new CartItem
                {
                    ProductID = product.ProductID,
                    CartID = ShoppingCartId,
                    Amount = 1,
                    Price = price,
                    Creation = DateTime.Now
                };

                db.CartItems.AddObject(cartItem);
            }
            else
            {
                // If the item does exist in the cart, then add one to the quantity
                cartItem.Amount++;
            }

            // Save changes
            db.SaveChanges();
        }
Exemplo n.º 12
0
 public AdminProductViewModel(Product product)
 {
     ProductID = product.ProductID;
       BrandID = product.BrandID;
       Condition = product.ProductConditions.FirstOrDefault().ProductConditionID;
       Gender = product.Gender;
       ProductName = product.ProductName;
       ModelName = product.ModelName;
       ModelNumber = product.ModelNumber;
       SerialNumber = product.SerialNumber;
       CaseSize = product.CaseSize;
       CaseMaterial = product.CaseMaterial;
       Bezel = product.Bezel;
       Crystal = product.Crystal;
       DialColour = product.DialColour;
       Movement = product.Movement;
       Functions = product.Functions;
       Strap = product.Strap;
       WaterResistant = product.WaterResistant;
       RetailPrice = product.RetailPrice;
       BoxPapers = product.BoxPapers;
       Warranty = product.Warranty;
       ProductImages = new List<AdminProductImageViewModel>();
       foreach (ProductImage image in product.ProductImages) {
     ProductImages.Add(new AdminProductImageViewModel(image));
       }
       NewArrival = product.NewArrival.GetValueOrDefault();
       HotDeal = product.HotDeal.GetValueOrDefault();
       Sold = product.Sold.GetValueOrDefault();
 }
Exemplo n.º 13
0
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        selectedProduct = new Product();
        this.selectedProduct.Course_id = course_id.ToString();

        if (Page.IsValid)
        {
            CartItemList cart = CartItemList.GetCart();
            int locCount = cart.Count;
            locCount = locCount + 1;
            this.selectedProduct.assignmentNumber = locCount.ToString();
            this.selectedProduct.aGUID = Guid.NewGuid().ToString();
            this.selectedProduct.Num_Assignment = locCount;
            CartItem cartItem = new CartItem();

            int Num_Assignments=0;
            int assignment = 1; //will be produced from loop according to Num_Assignments
            cart = CartItemList.GetCart();
            cartItem = cart[selectedProduct.Course_id];

            if (cartItem == null)
            {
                cart.AddItem(selectedProduct, Num_Assignments,assignment);
            }
            else
            {
                cart.AddItem(selectedProduct, Num_Assignments, assignment);
                cartItem.AddQuantity(1);
            }
            this.DisplayCart();

        }
    }
        public static List<Product> GetProductsByPartialName(string partialName)
        {
            List<Product> results = new List<Product>(); //empty list

            string query = "SELECT ProductCode, Name " +
                           "FROM Products " +
                           "WHERE Name LIKE @PartialName " +
                           "ORDER BY ProductCode";

            using (SqlConnection con = new SqlConnection(GetConnectionString()))
            {
                using (SqlCommand cmd = new SqlCommand(query, con))
                {
                    cmd.Parameters.AddWithValue("@PartialName", "%" + partialName + "%");

                    con.Open();
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read()) //while there is still another record
                        {
                            Product p = new Product();
                            p.ProductCode = reader["ProductCode"].ToString();
                            p.Name = reader["Name"].ToString();
                            results.Add(p); //add to the list
                        }
                    }
                }
            }

            return results;
        }
        public bool IsSatisfiedBy(Product product)
        {
            if (_sizeIds.Count() > 0 )
                return _sizeIds.Any(s => product.Title.Products.Any(p => p.Size.Id == s));

            return true;
        }
        public Product SelectByProductID(int ProductID)
        {
            string query = "select * from Product WHERE ProductID = @ProductID";
            List<SqlParameter> lstParams = new List<SqlParameter>();
            lstParams.Add(new SqlParameter("@ProductID", ProductID));

            DataTable dt = DBUtility.SelectData(query, lstParams);

            Product objProduct = new Product();
            if (dt.Rows.Count > 0)
            {
                objProduct.Name = dt.Rows[0]["Name"].ToString();
                objProduct.CreateDate = Convert.ToDateTime(dt.Rows[0]["CreateDate"]);
                objProduct.DesignFiles = dt.Rows[0]["DesignFiles"].ToString();
                objProduct.Status = dt.Rows[0]["Status"].ToString();
                objProduct.Description = dt.Rows[0]["Description"].ToString();
                objProduct.Size = dt.Rows[0]["Size"].ToString();
                objProduct.Colors = dt.Rows[0]["Colors"].ToString();
                objProduct.Type = dt.Rows[0]["Type"].ToString();
                objProduct.CustomerID = Convert.ToInt32(dt.Rows[0]["CustomerID"]);
                objProduct.ProductID = Convert.ToInt32(dt.Rows[0]["ProductID"]);
              
            }

            return objProduct;
        }
        public static List<Product> GetAllProducts()
        {
            List<Product> products = new List<Product>();

            string query = "SELECT ProductCode, Name " +
                           "FROM Products " +
                           "ORDER BY ProductCode";

            using (SqlConnection con = new SqlConnection(GetConnectionString()))
            {
                using (SqlCommand cmd = new SqlCommand(query, con))
                {
                    con.Open();
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read()) //while there is still another record
                        {
                            Product p = new Product();
                            p.ProductCode = reader["ProductCode"].ToString();
                            p.Name = reader["Name"].ToString();
                            products.Add(p); //add to the list
                        }
                    }
                }
            }

            return products;
        }
Exemplo n.º 18
0
        public ActionResult CreateProduct(Product p, HttpPostedFileBase file)
        {
            string imgPath = "/Content/images/product";
            string path = "";
            if (ModelState.IsValid)
            {
                if (file != null)
                {
                    string pic = System.IO.Path.GetFileName(file.FileName);
                    path = System.IO.Path.Combine(
                                           Server.MapPath("~" + imgPath), pic);
                    // file is uploaded
                    file.SaveAs(path);
                    p.ProductPictureUrl = imgPath + "/" + file.FileName;
                }

                p.CreatedDate = DateTime.Now;
                _productRepository.Add(p);
                _productRepository.Save();
                int i = p.ProductId;
                return Json(i);
            }
            else
            {
                int wrongData = -2;
                return Json(wrongData);
            }
        }
Exemplo n.º 19
0
            public ProductFactory(Parameters parameters)
            {
                try
                {
                    using (var server = new VentsCad())
                    {
                        switch (parameters.Name)
                        {
                            case "spigot":                                
                                product = new Spigot(parameters.Type.SubType, parameters.Sizes[0].Width, parameters.Sizes[0].Height);
                                break;
                            case "dumper":
                                var material = new string[] { parameters.Materials[0].Value, parameters.Materials[0].Thikness, parameters.Materials[0].Name, parameters.Materials[0].Code };
                                product = new Dumper(parameters.Type.SubType, parameters.Sizes[0].Width, parameters.Sizes[0].Height, true, material);
                                break;
                            case "montageFrame":                                
                                product = new MontageFrame(parameters.Type.SubType, parameters.Sizes[0].Width, parameters.Sizes[0].Lenght, parameters.Sizes[0].Additional1, parameters.Materials[0]);
                                break;
                            default:
                                break;
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
                }

                
            }
		public void Init()
		{
			var en = CultureInfo.CreateSpecificCulture("en");

			Thread.CurrentThread.CurrentCulture	= en;
			Thread.CurrentThread.CurrentUICulture = en;

			helper = new FormHelper();

			subscription = new Subscription();
			mock = new MockClass();
			months = new[] {new Month(1, "January"), new Month(1, "February")};
			product = new Product("memory card", 10, (decimal) 12.30);
			user = new SimpleUser();
			users = new[] { new SimpleUser(1, false), new SimpleUser(2, true), new SimpleUser(3, false), new SimpleUser(4, true) };
			mock.Values = new[] { 2, 3 };

			var controller = new HomeController();
			var context = new ControllerContext();

			context.PropertyBag.Add("product", product);
			context.PropertyBag.Add("user", user);
			context.PropertyBag.Add("users", users);
			context.PropertyBag.Add("roles", new[] { new Role(1, "a"), new Role(2, "b"), new Role(3, "c") });
			context.PropertyBag.Add("sendemail", true);
			context.PropertyBag.Add("confirmation", "abc");
			context.PropertyBag.Add("fileaccess", FileAccess.Read);
			context.PropertyBag.Add("subscription", subscription);
			context.PropertyBag.Add("months", months);
			context.PropertyBag.Add("mock", mock);

			helper.SetController(controller, context);
		}
        public SingleProductViewModel(Product p, MerchantTribeApplication mtapp)
        {
            var profiler = MiniProfiler.Current;

            using (profiler.Step("Price Product " + p.ProductName))
            {
                this.UserPrice = mtapp.PriceProduct(p, mtapp.CurrentCustomer, null, mtapp.CurrentlyActiveSales);
            }
            this.IsFirstItem = false;
            this.IsLastItem = false;
            this.Item = p;
            using (profiler.Step("Image Url Product" + p.ProductName))
            {
                this.ImageUrl = MerchantTribe.Commerce.Storage.DiskStorage.ProductImageUrlSmall(
                    mtapp,
                    p.Bvin,
                    p.ImageFileSmall,
                    mtapp.IsCurrentRequestSecure());
            }
            using (profiler.Step("Product Link " + p.ProductName))
            {
                this.ProductLink = UrlRewriter.BuildUrlForProduct(p,
                                                mtapp.CurrentRequestContext.RoutingContext,
                                                string.Empty);
            }
        }
Exemplo n.º 22
0
        private string GetProduct(TextBox txtProductID,
                          ref Product product)
        {
            string result = "";

            try
            {
                int productID = Int32.Parse(txtProductID.Text);
                var client = new ProductServiceClient();
                product = client.GetProduct(productID);

                var sb = new StringBuilder();
                sb.Append("ProductID:" +
                    product.ProductID.ToString() + "\n");
                sb.Append("ProductName:" +
                    product.ProductName + "\n");
                sb.Append("UnitPrice:" +
                    product.UnitPrice.ToString() + "\n");
                sb.Append("RowVersion:");
                foreach (var x in product.RowVersion.AsEnumerable())
                {
                    sb.Append(x.ToString());
                    sb.Append(" ");
                }
                result = sb.ToString();

            }
            catch (Exception ex)
            {
                result = "Exception: " + ex.Message.ToString();
            }

            return result;
        }
Exemplo n.º 23
0
        public static void add(Product product)
        {
            var existingProduct = false;
            Product fetchedProduct;

            if (product.Id != 0)
            {
                throw new
                Exception(@"Posted products cannot
              contain an id");
            }

            try
            {
                fetchedProduct = get(product.Name);
                existingProduct = true;
            }
            catch (Exception)
            {
                //this is actually good that we are here. Means we didn't
                //find an existing product so it is OK to insert;
                product.Id = ProductsRepository.data.Select(x => x.Id).Max() + 1;

                var data = ProductsRepository.data.ToList();
                data.Add(product);
                ProductsRepository.data = data;
            }

            if (existingProduct)
            {
                throw new
                Exception(@"The product name you are
              attempting to insert already exists.");
            }
        }
Exemplo n.º 24
0
        public void TestActiveAtSpecification()
        {
            var productSpecification1 = new ProductSpecification
            {
                ActiveFrom = DateTime.Now.AddDays(-3),
                ActiveUntil = DateTime.Now.AddDays(3)
            };

            var productSpecification2 = new ProductSpecification
            {
                ActiveFrom = DateTime.Now.AddDays(-6),
                ActiveUntil = DateTime.Now.AddDays(-3)
            };

            var productSpecification3 = new ProductSpecification
            {
                ActiveFrom = DateTime.Now.AddDays(-9),
                ActiveUntil = DateTime.Now.AddDays(-6)
            };

            var product = new Product
            {
                ProductSpecifications =
                    new Collection<ProductSpecification>
                                  {
                                      productSpecification1,
                                      productSpecification2,
                                      productSpecification3
                                  }
            };

            var actual = product.ActiveAt(DateTime.Now.AddDays(-8));

            Assert.AreEqual(productSpecification3, actual);
        }
Exemplo n.º 25
0
 public void activeSelect(User _user, Product _product)
 {
     if (_product.Active == false)
     {
         throw new NonActiveProductException(_user, _product);
     }
 }
Exemplo n.º 26
0
 public void deleteProduct(Product p)
 {
     if (db.Products.Contains(p)&& p!=null)
     {
         db.Products.Remove(p);
     }
 }
		public virtual void EmbeddingOfInstanceOfCustomReferenceTypeWithFieldsIsCorrect()
		{
			// Arrange
			var product = new Product
			{
				Name = "Red T-shirt",
				Price = 995.00
			};

			const string updateCode = "product.Price *= 1.15;";

			const string input1 = "product.Name";
			const string targetOutput1 = "Red T-shirt";

			const string input2 = "product.Price";
			const double targetOutput2 = 1144.25;

			// Act
			string output1;
			double output2;

			using (var jsEngine = CreateJsEngine())
			{
				jsEngine.EmbedHostObject("product", product);
				jsEngine.Execute(updateCode);

				output1 = jsEngine.Evaluate<string>(input1);
				output2 = jsEngine.Evaluate<double>(input2);
			}

			// Assert
			Assert.AreEqual(targetOutput1, output1);
			Assert.AreEqual(targetOutput2, output2);
		}
Exemplo n.º 28
0
        internal static void ImportTags(Product product, List<string> tagsList, UploadConfig config)
        {
            TaxonomyManager taxonomyManager = TaxonomyManager.GetManager();
            CatalogManager catalogManager = CatalogManager.GetManager();

            FlatTaxonomy tagsTaxonomy = taxonomyManager.GetTaxonomies<FlatTaxonomy>().Where(t => t.Name == "Tags").SingleOrDefault();

            foreach (var tagString in tagsList)
            {
                try
                {
                    Taxon tag = GetTagIfItExsistsOrCreateOneIfItDoesnt(tagString, tagsTaxonomy, taxonomyManager);

                    SetTagProperties(tag, tagString);

                    taxonomyManager.SaveChanges();

                    if (product.Organizer.TaxonExists("Tags", tag.Id) == true)
                    {
                        continue;        // Product already linked to Tag
                    }

                    product.Organizer.AddTaxa("Tags", tag.Id);

                    catalogManager.SaveChanges();
                }
                catch
                {
                    //catching so even if one fails rest goes on
                }
            }
        }
Exemplo n.º 29
0
        public void CanStoreAProduct()
        {
            //Database.SetInitializer(new DropCreateDatabaseAlways<CoffeeShopContext>());
              long id;
              using (var session = sessionFactory.OpenSession())
              using (var tx = session.BeginTransaction())
              {
            var repository = new Repository<Product>(session);
            var product = new Product
                      {
                        Name = "Coffee 1",
                        Price = 10.4m
                      };

            repository.MakePersistent(product);
            id = product.Id;
            tx.Commit();
              }

              using (var session = sessionFactory.OpenSession())
              using (session.BeginTransaction())
              {
            var repository = new Repository<Product>(session);
            Product product = repository.GetById(id);

            product.Satisfy(p => p.Name == "Coffee 1" && p.Price == 10.4m);
              }
        }
Exemplo n.º 30
0
 public void Update(Product product)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 31
0
        public void Visit(MetadataInfo.DaxMetadata daxMetadata)
        {
            string  ssasVersion = GetSsasVersion();
            Product productInfo = GetProduct(ssasVersion);

            daxMetadata.Version = new MetadataInfo.SsasVersion {
                SSAS_VERSION = ssasVersion,
                CAPTURE_DATE = DateTime.Now,
                PRODUCT_TYPE = productInfo.Type,
                PRODUCT_NAME = productInfo.Name
            };
            AdomdDataReader result = _conn.ExecuteReader("SELECT * FROM $SYSTEM.MDSCHEMA_FUNCTIONS");

            while (result.Read())
            {
                // Filters only DAX functions
                int?origin = GetInt(result, result.GetOrdinal("ORIGIN"));
                if (origin == null)
                {
                    continue;
                }
                if (origin != 3 && origin != 4)
                {
                    continue;
                }

                var SSAS_VERSION         = ssasVersion;
                var FUNCTION_NAME        = GetString(result, result.GetOrdinal("FUNCTION_NAME"));
                var DESCRIPTION          = GetString(result, result.GetOrdinal("DESCRIPTION"));
                var PARAMETER_LIST       = GetString(result, result.GetOrdinal("PARAMETER_LIST"));
                var RETURN_TYPE          = GetInt(result, result.GetOrdinal("RETURN_TYPE"));
                var ORIGIN               = origin;
                var INTERFACE_NAME       = GetString(result, result.GetOrdinal("INTERFACE_NAME"));
                var LIBRARY_NAME         = GetString(result, result.GetOrdinal("LIBRARY_NAME"));
                var DLL_NAME             = GetString(result, result.GetOrdinal("DLL_NAME"));
                var HELP_FILE            = GetString(result, result.GetOrdinal("HELP_FILE"));
                var HELP_CONTEXT         = GetInt(result, result.GetOrdinal("HELP_CONTEXT"));
                var OBJECT               = GetString(result, result.GetOrdinal("OBJECT"));
                var CAPTION              = GetString(result, result.GetOrdinal("CAPTION"));
                var PARAMETERINFO        = GetXmlString(result, result.GetOrdinal("PARAMETERINFO"));
                var DIRECTQUERY_PUSHABLE = (result.FieldCount >= 14 ? GetInt(result, result.GetOrdinal("DIRECTQUERY_PUSHABLE")) : null);

                var function = new MetadataInfo.DaxFunction {
                    SSAS_VERSION         = ssasVersion,
                    FUNCTION_NAME        = GetString(result, result.GetOrdinal("FUNCTION_NAME")),
                    DESCRIPTION          = GetString(result, result.GetOrdinal("DESCRIPTION")),
                    PARAMETER_LIST       = GetString(result, result.GetOrdinal("PARAMETER_LIST")),
                    RETURN_TYPE          = GetInt(result, result.GetOrdinal("RETURN_TYPE")),
                    ORIGIN               = origin,
                    INTERFACE_NAME       = GetString(result, result.GetOrdinal("INTERFACE_NAME")),
                    LIBRARY_NAME         = GetString(result, result.GetOrdinal("LIBRARY_NAME")),
                    DLL_NAME             = GetString(result, result.GetOrdinal("DLL_NAME")),
                    HELP_FILE            = GetString(result, result.GetOrdinal("HELP_FILE")),
                    HELP_CONTEXT         = GetInt(result, result.GetOrdinal("HELP_CONTEXT")),
                    OBJECT               = GetString(result, result.GetOrdinal("OBJECT")),
                    CAPTION              = GetString(result, result.GetOrdinal("CAPTION")),
                    PARAMETERINFO        = GetXmlString(result, result.GetOrdinal("PARAMETERINFO")),
                    DIRECTQUERY_PUSHABLE = (result.FieldCount >= 14 ? GetInt(result, result.GetOrdinal("DIRECTQUERY_PUSHABLE")) : null)
                };
                daxMetadata.DaxFunctions.Add(function);
            }
        }
        public async Task <IActionResult> Post(ProductForm model)
        {
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(ModelState));
            }

            var currentUser = await _workContext.GetCurrentUser();

            var product = new Product
            {
                Name                  = model.Product.Name,
                SeoTitle              = model.Product.Slug,
                ShortDescription      = model.Product.ShortDescription,
                Description           = model.Product.Description,
                Specification         = model.Product.Specification,
                Price                 = model.Product.Price,
                OldPrice              = model.Product.OldPrice,
                SpecialPrice          = model.Product.SpecialPrice,
                SpecialPriceStart     = model.Product.SpecialPriceStart,
                SpecialPriceEnd       = model.Product.SpecialPriceEnd,
                IsPublished           = model.Product.IsPublished,
                IsFeatured            = model.Product.IsFeatured,
                IsCallForPricing      = model.Product.IsCallForPricing,
                IsAllowToOrder        = model.Product.IsAllowToOrder,
                BrandId               = model.Product.BrandId,
                TaxClassId            = model.Product.TaxClassId,
                HasOptions            = model.Product.Variations.Any() ? true : false,
                IsVisibleIndividually = true,
                CreatedBy             = currentUser
            };

            if (!User.IsInRole("admin"))
            {
                product.VendorId = currentUser.VendorId;
            }

            if (model.Product.IsOutOfStock)
            {
                product.StockQuantity = 0;
            }
            else
            {
                product.StockQuantity = null;
            }

            var optionIndex = 0;

            foreach (var option in model.Product.Options)
            {
                product.AddOptionValue(new ProductOptionValue
                {
                    OptionId    = option.Id,
                    DisplayType = option.DisplayType,
                    Value       = JsonConvert.SerializeObject(option.Values),
                    SortIndex   = optionIndex
                });

                optionIndex++;
            }

            foreach (var attribute in model.Product.Attributes)
            {
                var attributeValue = new ProductAttributeValue
                {
                    AttributeId = attribute.Id,
                    Value       = attribute.Value
                };

                product.AddAttributeValue(attributeValue);
            }

            foreach (var categoryId in model.Product.CategoryIds)
            {
                var productCategory = new ProductCategory
                {
                    CategoryId = categoryId
                };
                product.AddCategory(productCategory);
            }

            await SaveProductMedias(model, product);

            MapProductVariationVmToProduct(model, product);
            MapProductLinkVmToProduct(model, product);

            _productService.Create(product);
            return(CreatedAtAction(nameof(Get), new { id = product.Id }, null));
        }
Exemplo n.º 33
0
 public HoneyDecorator(Product product) : base(product)
 {
 }
Exemplo n.º 34
0
 public void Add(Product product)
 {
     _products.Add(product);
 }
 public IActionResult ActionEdit(int Id, Product requestProduct)
 {
     db.Entry(requestProduct).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
     db.SaveChanges();
     return(RedirectToAction("Index"));
 }
Exemplo n.º 36
0
 public int AddProduct(Product product)
 {
     context.Products.Add(product);
     context.SaveChanges();
     return(product.ProductId);
 }
Exemplo n.º 37
0
        public HttpResponseMessage AddOrder(JObject jsonBody)
        {
            JObject products = (JObject)jsonBody["ProductsInRetailOrder"]; // contains product in the order
            JObject account  = (JObject)jsonBody["Account"];               // contains information about  the account who is placin the order

            jsonBody.Remove("ProductsRetailOrder");                        // removing these information, will add the later back to send to IS
            jsonBody.Remove("Account");                                    // same as above


            OnlineOrder order = jsonBody.ToObject <OnlineOrder>(); // the online order

            HttpWebResponse response = null;                       // to store the response from the IS

            // startin the distributed transaction, will be commited only the distributed system transaction is success
            using (var dbTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    // write order
                    db.OnlineOrders.Add(order);

                    db.SaveChanges();

                    // get order id to FK
                    int OrderId = order.OnlineOrderId;     // the foregin key to be used for the -> product in..

                    JEnumerable <JToken> tokens = (JEnumerable <JToken>)products.Children <JToken>();

                    foreach (JToken token in tokens)
                    {
                        JToken productJson = token.Children().First();     // I think this can be changed if changed earlier part of code
                        ProductInOnlineOrder productInstance = productJson.ToObject <ProductInOnlineOrder>();
                        productInstance.OnlineOrderId = OrderId;
                        db.ProductsInOnlineOrders.Add(productInstance);

                        // update the stock
                        Product dbProduct   = db.Products.Find(productInstance.ProductId);
                        float   newQuantity = (float)dbProduct.StocksQuantity;
                        newQuantity = newQuantity - productInstance.Quantity;
                        if (newQuantity < 0)
                        {
                            dbTransaction.Rollback();
                            return(this.Request.CreateResponse(HttpStatusCode.Conflict, "Stock not sufficient."));
                        }
                        else
                        {
                            dbProduct.StocksQuantity  = newQuantity;
                            db.Entry(dbProduct).State = EntityState.Modified;
                        }
                    }

                    Integrator integrator = new Integrator();

                    // add routing information to the data and send it to the IS
                    Setting setting = db.Settings.Find(1);
                    jsonBody.Add("ServiceId", setting.SystemIdNumber);
                    //jsonBody.Add("EnterpriseId", jsonBody["EnterpriseId"].ToString());
                    //jsonBody.Add("AccountId", jsonBody["AccountId"].ToString());

                    // add payload information as promised earlier
                    jsonBody.Add("Account", account);
                    jsonBody.Add("ServiceOrderId", OrderId);
                    //jsonBody.Add("ProductsInRetailOrder", account);

                    response = integrator.sendJsonObject(jsonBody, "/api/Enterprises/AddRetailOrder");

                    db.SaveChanges();
                    // commit if distributed transaction is success
                    if (response != null && response.StatusCode != HttpStatusCode.Conflict)
                    {
                        dbTransaction.Commit();
                    }
                    else
                    {
                        dbTransaction.Rollback();
                    }
                }
                catch (Exception ex)
                {
                    dbTransaction.Rollback();
                    System.Diagnostics.Trace.WriteLine(ex);
                    return(this.Request.CreateResponse(HttpStatusCode.Conflict, response));
                }
            }

            return(this.Request.CreateResponse(HttpStatusCode.Created, response));
        }
        public virtual async Task <ProductVariantAttributeCombination> MergeWithCombinationAsync(Product product, ProductVariantAttributeSelection selection)
        {
            Guard.NotNull(product, nameof(product));

            var combination = await FindAttributeCombinationAsync(product.Id, selection);

            if (combination != null && combination.IsActive)
            {
                product.MergeWithCombination(combination);
            }
            else if (product.MergedDataValues != null)
            {
                product.MergedDataValues.Clear();
            }

            return(combination);
        }
Exemplo n.º 39
0
    protected void btnProductAddSubmit_Click(object sender, EventArgs e)
    {
        Product product = new Product();
        product.ProductName = txtProductName.Text;
        product.ProductDescription = txtDescription.Text;
        product.ProductPrice = Convert.ToDecimal(txtProductPrice.Text);
        product.ProductPriceTax = Convert.ToInt32(txtTax.Text);
        product.Quantity = Convert.ToInt32(txtQuantity.Text);

        //if (txtProductPrice.Text == string.Empty || txtProductPrice.Text.StartsWith("-") || txtProductPrice.Text == "0")
        //{
        //    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "Price value cannot be negative or empty or zero!" + "');", true);
        //    txtProductPrice.Focus();
        //}
        //else
        //{

        //}
        //if (txtTax.Text.StartsWith("-"))
        //{
        //    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "Tax value cannot be negative!" + "');", true);
        //    txtTax.Focus();
        //}
        //else
        //{

        //}

        //if (txtQuantity.Text == string.Empty || txtQuantity.Text.StartsWith("-") || txtQuantity.Text == "0")
        //{
        //    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "Quantity value cannot be negative or empty or zero!" + "');", true);
        //    txtQuantity.Focus();
        //}
        //else
        //{

        //}
        product.TotalPrice = Convert.ToInt32(txtTotalPrice.Text);
        if (ddlSize.SelectedIndex == 0)
        {
            product.SizeId = null;
            product.Size = null;
        }
        else
        {
            product.SizeId = Convert.ToInt32(ddlSize.SelectedValue);
            product.Size = ddlSize.SelectedItem.ToString();
        }
        if (ddlBrand.SelectedIndex == 0)
        {
            product.BrandId = null;
            product.Brand = null;
        }
        else
        {
            product.BrandId = Convert.ToInt32(ddlBrand.SelectedValue);
            product.Brand = ddlBrand.SelectedItem.ToString();
        }
        if (ddlCategory.SelectedIndex == 0)
        {
            product.CategoryId = null;
            product.Category = null;
        }
        else
        {
            product.CategoryId = Convert.ToInt32(ddlCategory.SelectedValue);
            product.Category = ddlCategory.SelectedItem.ToString();
        }
        if (ddlSupplier.SelectedIndex == 0)
        {
            product.SupplierId = null;
            product.Supplier = null;
        }
        else
        {
            product.SupplierId = Convert.ToInt32(ddlSupplier.SelectedValue);
            product.Supplier = ddlSupplier.SelectedItem.ToString();
        }
        if (ddlSupplier.SelectedIndex == 0)
        {
            product.StoreId = null;
            product.StoreName = null;
        }
        else
        {
            product.StoreId = Convert.ToInt32(ddlstore.SelectedValue);
            product.StoreName = ddlstore.SelectedItem.ToString();
        }
        product.Status = "Available";
        var timeZone = TimeZoneInfo.FindSystemTimeZoneById("Bangladesh Standard Time");
        var now = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, timeZone);
        string date = now.ToString("yyyy-MM-dd");
        //string date = now.ToString("yyyy-MM-dd hh:mm:ss tt");
        product.Date = Convert.ToDateTime(date);
        Session["getProductId"] = product.Id;
        if (fupProductPhoto.HasFile)
        {
            fupProductPhoto.SaveAs(Server.MapPath("../admin/productImages/" + fupProductPhoto.FileName));
            product.ProductPhoto = fupProductPhoto.FileName;
        }
        imsdb.Products.Add(product);
        imsdb.SaveChanges();
        ScriptManager.RegisterStartupScript(this, GetType(), "",
       "alert('Product added successfully!');location.href='ProductAdd.aspx'", true);

    }
 // POST: api/Product
 public void Post([FromBody] Product product)
 {
     var productRepository = new Models.ProductRepository();
     var newProduct        = productRepository.Save(product);
 }
        public virtual async Task <CombinationAvailabilityInfo> IsCombinationAvailableAsync(
            Product product,
            IEnumerable <ProductVariantAttribute> attributes,
            IEnumerable <ProductVariantAttributeValue> selectedValues,
            ProductVariantAttributeValue currentValue)
        {
            if (product == null ||
                _performanceSettings.MaxUnavailableAttributeCombinations <= 0 ||
                !(selectedValues?.Any() ?? false))
            {
                return(null);
            }

            // Get unavailable combinations.
            var unavailableCombinations = await _cache.GetAsync(UNAVAILABLE_COMBINATIONS_KEY.FormatInvariant(product.Id), async o =>
            {
                o.ExpiresIn(TimeSpan.FromMinutes(10));

                var data  = new Dictionary <string, CombinationAvailabilityInfo>();
                var query = _db.ProductVariantAttributeCombinations
                            .AsNoTracking()
                            .Where(x => x.ProductId == product.Id);

                if (product.ManageInventoryMethod == ManageInventoryMethod.ManageStockByAttributes)
                {
                    query = query.Where(x => !x.IsActive || (x.StockQuantity <= 0 && !x.AllowOutOfStockOrders));
                }
                else
                {
                    query = query.Where(x => !x.IsActive);
                }

                // Do not proceed if there are too many unavailable combinations.
                var unavailableCombinationsCount = await query.CountAsync();

                if (unavailableCombinationsCount <= _performanceSettings.MaxUnavailableAttributeCombinations)
                {
                    var pager = query.ToFastPager();

                    while ((await pager.ReadNextPageAsync <ProductVariantAttributeCombination>()).Out(out var combinations))
                    {
                        foreach (var combination in combinations)
                        {
                            if (combination.AttributeSelection.AttributesMap.Any())
                            {
                                // <ProductVariantAttribute.Id>:<ProductVariantAttributeValue.Id>[,...]
                                var valuesKeys = combination.AttributeSelection.AttributesMap
                                                 .OrderBy(x => x.Key)
                                                 .Select(x => $"{x.Key}:{string.Join(",", x.Value.OrderBy(y => y))}");

                                data[string.Join("-", valuesKeys)] = new CombinationAvailabilityInfo
                                {
                                    IsActive     = combination.IsActive,
                                    IsOutOfStock = combination.StockQuantity <= 0 && !combination.AllowOutOfStockOrders
                                };
                            }
                        }
                    }
                }

                return(data);
            });

            if (!unavailableCombinations.Any())
            {
                return(null);
            }

            using var pool = StringBuilderPool.Instance.Get(out var builder);
            var selectedValuesMap = selectedValues.ToMultimap(x => x.ProductVariantAttributeId, x => x);

            if (attributes == null || currentValue == null)
            {
                // Create key to test selectedValues.
                foreach (var kvp in selectedValuesMap.OrderBy(x => x.Key))
                {
                    Append(builder, kvp.Key, kvp.Value.Select(x => x.Id).Distinct());
                }
            }
            else
            {
                // Create key to test currentValue.
                foreach (var attribute in attributes.OrderBy(x => x.Id))
                {
                    IEnumerable <int> valueIds;

                    var selectedIds = selectedValuesMap.ContainsKey(attribute.Id)
                        ? selectedValuesMap[attribute.Id].Select(x => x.Id)
                        : null;

                    if (attribute.Id == currentValue.ProductVariantAttributeId)
                    {
                        // Attribute to be tested.
                        if (selectedIds != null && attribute.IsMultipleChoice)
                        {
                            // Take selected values and append current value.
                            valueIds = selectedIds.Append(currentValue.Id).Distinct();
                        }
                        else
                        {
                            // Single selection attribute -> take current value.
                            valueIds = new[] { currentValue.Id };
                        }
                    }
                    else
                    {
                        // Other attribute.
                        if (selectedIds != null)
                        {
                            // Take selected value(s).
                            valueIds = selectedIds;
                        }
                        else
                        {
                            // No selected value -> no unavailable combination.
                            return(null);
                        }
                    }

                    Append(builder, attribute.Id, valueIds);
                }
            }

            var key = builder.ToString();

            //$"{!unavailableCombinations.ContainsKey(key),-5} {currentValue.ProductVariantAttributeId}:{currentValue.Id} -> {key}".Dump();

            if (unavailableCombinations.TryGetValue(key, out var availability))
            {
                return(availability);
            }

            return(null);
 public bool Add(Product product)
 {
     return(_productRepository.Add(product));
 }
 // PUT: api/Product/5
 public void Put(int id, [FromBody] Product product)
 {
     var productRepository = new Models.ProductRepository();
     var updatedProduct    = productRepository.Save(id, product);
 }
Exemplo n.º 44
0
 public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
 {
     // A product purchase attempt did not succeed. Check failureReason for more detail. Consider sharing 
     // this reason with the user to guide their troubleshooting actions.
     Debug.Log(string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}", product.definition.storeSpecificId, failureReason));
 }
Exemplo n.º 45
0
 public void setProduct(Product product)
 {
     basket.addProduct(product);
 }
Exemplo n.º 46
0
 public async void Load(Product product)
 {
     this.product = product;
 }
 public bool Update(Product product)
 {
     return(_productRepository.Update(product));
 }
Exemplo n.º 48
0
 public int UpdateProduct(Product product)
 {
     return(db.Update(product));
 }
Exemplo n.º 49
0
        /* public bool verificaData()
         * {
         *   Invoice ivlast = _invoiceController.ListALLAsNoTracking().LastOrDefault();
         *   if(ivlast != null)
         *   {
         *       if(ivlast.DataCadastro > DateTime.Now)
         *       {
         *           MessageBox.Show("Verifique se a data do Sistema está correta..!");
         *           return false;
         *       }
         *   }
         *   return true;
         * }*/



        public void salvar()
        {
            //Series serie = _serieController.ListALLAsNoTracking()[cmbSerie.SelectedIndex];
            try
            {
                CalcCodigoFaturaAtual();
                obs = txtDescricao.Text;
                string   invoiceNo = getInvoiceTypeTipo() + " " + _serieController.ListALLAsNoTracking()[cmbSerie.SelectedIndex].Serie + "/" + _codigoFaturaAtual;
                DateTime dataAtual = DateTime.Now;

                //string GrossTotal = (TotalIva + totalIncidencia).ToString("F").Replace(',', '.');
                string GrossTotal = (totGeral).ToString("F3").Replace(',', '.');
                //   string dadosHash2 = dataAtual.ToString("yyyy-MM-dd") + ";" + dataAtual.ToString("yyyy-MM-ddTHH:mm") + ";" + invoiceNo + ";" + (TotalIva + totalIncidencia).ToString("N2").Replace(",", ".") + ";";
                string dadosHash = dataAtual.ToString("yyyy-MM-dd") + ";" + dataAtual.ToString("yyyy-MM-ddTHH:mm:ss") + ";" + invoiceNo + ";" + GrossTotal + ";";
                dadosHash += lastInvoice != null ? lastInvoice.Hash : "";
                //dadosHash = lastInvoice != null ? dadosHash + lastInvoice.Hash : dadosHash;

                string Hash = Methods.gerarHash(dadosHash, invoiceNo);

                Invoice invoice = new Invoice()
                {
                    InvoiceDate      = dataAtual.ToString("yyyy-MM-dd"),
                    Codigo           = _codigoFaturaAtual,
                    ClienteId        = ClienteID,
                    SeriesId         = idSerie,
                    InvoiceNo        = invoiceNo,
                    TipoDocumentoId  = idTipoDocumento,
                    Desconto         = totDescontoProducts,
                    Observacao       = obs,
                    TotalImposto     = TotalIva,
                    TotalIncidencia  = totalIncidencia,
                    TotalLiquidar    = cmbInvoiceType.Text == "FT" ? totalIncidencia + TotalIva : 0,
                    UserId           = UserCurrent.getCurrentUser().Id,
                    Troco            = troco,
                    ValorPago        = valorPago,
                    FormaPagamentoId = cmbInvoiceType.Text == "FT" ? "CD" : cmbInvoiceType.Text == "PP" || cmbInvoiceType.Text == "FP" ? null : _paymentWays.ListALLAsNoTracking()[cmbPaymentMechanism.SelectedIndex].Id,
                    DataCadastro     = dataAtual,
                    Hash             = Hash,
                    DataVencimento   = dtVencimento.Enabled ? dtVencimento.Value : DateTime.Now,
                };
                _invoiceController.insert(invoice);

                invoice = _invoiceController.getForInvoiceNo(invoiceNo);
                int idFatura = invoice != null ? invoice.Id : 0;

                if (idFatura == 0)
                {
                    MessageBox.Show("Fatura Nula");
                }
                _invoiceController.Dispose();
                _invoiceController = new InvoiceController();

                /*string dadosHash = invoice.InvoiceDate + ";" + invoice.DataCadastro.ToString("yyyy-MM-ddTHH:mm:ss") + ";" + invoice.InvoiceNo + ";" + invoice.TotalGeral.ToString("N2").Replace(",", ".") + ";";
                 * string dadosHash2 = invoice.InvoiceDate + ";" + invoice.DataCadastro.ToString("yyyy-MM-ddTHH:mm") + ";" + invoice.InvoiceNo + ";" + invoice.TotalGeral.ToString("N2").Replace(",", ".") + ";";
                 * dadosHash = lastInvoice != null ? dadosHash2 + lastInvoice.Hash : dadosHash;
                 * invoice.Hash = Methods.gerarHash(dadosHash);*/


                CurrentAccountSystem currentAccountSystem = _currentAcountSystemController.ListALL()[cmbConta.SelectedIndex];
                currentAccountSystem.Saldo += invoice.TotalGeral;
                _currentAcountSystemController.update(currentAccountSystem);



                foreach (var item in __listaSelected)
                {
                    Stock stock = _stock.getStockArmazemProduct(item.ProdutoId, item.Stock.ArmazemId);
                    stock.Quantidade -= item.Quantidade;
                    _stock.update(stock);

                    string  movitoISE = null;
                    Product product   = _products.getOne(item.ProdutoId);
                    if (product.MotivoISEId != null)
                    {
                        movitoISE = product.MotivoISE.MencaoFatura;
                    }


                    ProductSales productSale = new ProductSales()
                    {
                        Preco             = item.Preco,
                        FaturaId          = idFatura,
                        ProductId         = item.ProdutoId,
                        Desconto          = item.Desconto,
                        Descricao_Produto = product.Descricao,
                        Quantidade        = item.Quantidade,
                        StockId           = item.StockId,
                        Taxa          = product.CodigoTaxa.Taxa,
                        Unidade       = product.UnidadeBase.Simbolo,
                        MotivoISEId   = product.MotivoISEId,
                        MotivoIsencao = movitoISE,
                    };

                    _sales.insert(productSale);
                }

                __listaSelected.Clear();
                gdvControlProducts.DataSource = __listaSelected;
                gdvControlProducts.RefreshDataSource();
                CalcCodigoFaturaAtual();
                print(idFatura);
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }
        }
 public void DisplayInsufficientCash(User user, Product product)
 {
     _cliInfoMessage = $"Insufficient credit on {user.Username}'s account! Account balance: {user.Balance}DDK, Product {product.Name} price {product.Price}kr";
 }
Exemplo n.º 51
0
 public int DeleteProduct(Product product)
 {
     return(db.Delete(product));
 }
Exemplo n.º 52
0
 public void AddProd(Product product)
 {
     db.Product.InsertOnSubmit(product);
 }
Exemplo n.º 53
0
 public int AddProduct(Product product)
 {
     db.Insert(product);
     return(product.id);
 }
        public async Task<ActionResult<Product>> CreateProduct([FromBody] Product product)
        {
            await _repository.Create(product);

            return CreatedAtRoute("GetProduct", new { id = product.Id }, product);
        }
Exemplo n.º 55
0
 public void DeleteProd(Product product)
 {
     db.Product.DeleteOnSubmit(product);
 }
 public void Delete(Product model)
 {
     _prodRepository.Delete(model);
 }
Exemplo n.º 57
0
 public DetailsVM()
 {
     Product = new Product();
 }
Exemplo n.º 58
0
 public void AddSaleTransaction(Product product, int amount)
 {
     PlacerholderReceipt.AddTransaction(new SaleTransaction(product, amount, PlacerholderReceipt.ID));
 }
 public async Task<ActionResult> UpdateProduct([FromBody] Product product)
 {
     return Ok(await _repository.Update(product));
 }
Exemplo n.º 60
-1
        private async static void Process()
        {
            //获取当前联系人列表
            HttpClient httpClient = new HttpClient();
            HttpResponseMessage response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products");
            IEnumerable<Product> products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
            Console.WriteLine("当前联系人列表:");
            ListContacts(products);

            //添加新的联系人
            Product product = new Product { Name = "王五", PhoneNo = "0512-34567890", EmailAddress = "*****@*****.**" };
            await httpClient.PostAsJsonAsync<Product>("http://localhost/selfhost/tyz/api/products", product);
            Console.WriteLine("添加新联系人“王五”:");
            response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products");
            products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
            ListContacts(products);

            //修改现有的某个联系人
            response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products/001");
            product = (await response.Content.ReadAsAsync<IEnumerable<Product>>()).First();
            product.Name = "赵六";
            product.EmailAddress = "*****@*****.**";
            await httpClient.PutAsJsonAsync<Product>("http://localhost/selfhost/tyz/api/products/001", product);
            Console.WriteLine("修改联系人“001”信息:");
            response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products");
            products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
            ListContacts(products);

            //删除现有的某个联系人
            await httpClient.DeleteAsync("http://localhost/selfhost/tyz/api/products/002");
            Console.WriteLine("删除联系人“002”:");
            response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products");
            products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
            ListContacts(products);
        }