Beispiel #1
0
        private static Models.Product RemoveReference(this Models.Product item)
        {
            var obj = new Models.Product();

            if (item != null)
            {
                obj.Id                 = item.Id;
                obj.IsActive           = item.IsActive;
                obj.Barcode            = item.Barcode;
                obj.CostPrice          = item.CostPrice;
                obj.Description        = item.Description;
                obj.Discount           = item.Discount;
                obj.PriceAfterdiscount = item.PriceAfterdiscount;
                obj.ProductTags        = item.ProductTags;
                obj.SellingPrice       = item.SellingPrice;
                obj.UnitId             = item.UnitId;
                obj.Name               = item.Name;
                obj.ProductCategoryId  = item.ProductCategoryId;
                obj.VendorId           = item.VendorId;
                obj.IsEnable           = item.IsEnable;
                obj.ShipmentCost       = item.ShipmentCost;
                obj.ShipmentTime       = item.ShipmentTime;
                obj.ShipmentVendor     = item.ShipmentVendor;
            }
            return(obj);
        }
Beispiel #2
0
        public ActionResult Evaluate(string asin)
        {
            LookupProductRequest lookupProductRequest = new LookupProductRequest
            {
                ItemId        = asin,
                IdType        = IdType.ASIN,
                ResponseGroup = ResponseGroup.Medium
            };

            LookupProductResponse lookupProductResponse = m_productAdvertisingApi.LookupProduct(lookupProductRequest);

            ProductProfitabilityMetadata dimensions = null;

            if (lookupProductResponse != null)
            {
                Product product = lookupProductResponse.Product;

                ProductMetadata productMetadata = lookupProductResponse.ProductMetadata;

                dimensions = new ProductProfitabilityMetadata
                {
                    ASIN        = asin,
                    Length      = product.Length,
                    Width       = product.Width,
                    Height      = product.Height,
                    Weight      = product.Weight,
                    SellersRank = productMetadata.SalesRank
                };
            }

            return(View(dimensions));
        }
 /// <summary>
 /// Long running put request, service returns a 200 to the initial request,
 /// with an entity that contains ProvisioningState=’Succeeded’.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='product'>
 /// Product to put
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task<Product> Put200SucceededAsync(this ILROsOperations operations, Product product = default(Product), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.Put200SucceededWithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false))
     {
         return _result.Body;
     }
 }
        /// <summary>
        /// Makes deep copy of Product.
        /// Entity Framework cannot keep track of 1 item in 2 contexts, so in order to
        /// export something and import it in other database it needs deep copy of it.
        /// </summary>
        /// <param name="product">Product for copy.</param>
        /// <param name="vendor">Product's vendor.</param>
        /// <returns>Deep copy of the product</returns>
        private static Product DeepCopyProduct(Product product, Vendor vendor)
        {
            var incomes = product.Incomes
                .Select(income => new Income()
                {
                    Quantity = income.Quantity,
                    SalePrice = income.SalePrice
                })
                .ToList();

            var expenses = product.Vendor.Expenses
                .Select(expense => new Expense()
                {
                    Amount = expense.Amount,
                })
                .ToList();

            foreach (var expense in expenses)
            {
                vendor.Expenses.Add(expense);
            }

            var deepCopyProduct = new Product()
            {
                Name = product.Name,
                BuyingPrice = product.BuyingPrice,
                Incomes = incomes,
                Vendor = vendor
            };

            return deepCopyProduct;
        }
Beispiel #5
0
 public void Save(Models.Product product)
 {
     if (products.ContainsKey(product.Id))
     {
         products[product.Id] = product;
     }
 }
Beispiel #6
0
        void Istoreinventory.Updateinventory(string store_phonenumber, string product, int quantity)
        {
            Store storequery = _context.Stores.Where(x => x.StorePhoneNumber.Equals(store_phonenumber)).First();

            Models.Product newproduct = new Models.Product();


            Product productquery = _context.Products.Where(x => x.ProductName.Equals(product)).First();

            StoreInventory storeInventory = _context.StoreInventories.FirstOrDefault(x => x.StoreId.Equals(storequery.Id) && x.ProductId == productquery.Id);

            if (storeInventory == null)
            {
                StoreInventory storei = new StoreInventory();
                storei.ProductId       = productquery.Id;
                storei.ProductQuantity = quantity;
                storei.StoreId         = storequery.Id;

                _context.Add(storei);
                _context.SaveChanges();
            }
            else
            {
                storeInventory.ProductQuantity = quantity;
                _context.Update(storeInventory);
                _context.SaveChanges();
            }
        }
Beispiel #7
0
        public int InsertProduct(Models.Product product)
        {
            int IdUser = 0;
            List <SqlParameter> _Parametros = new List <SqlParameter>();

            try{
                _Parametros.Add(new SqlParameter("@Title", product.Title));
                _Parametros.Add(new SqlParameter("@SKU", product.Sku));
                _Parametros.Add(new SqlParameter("@Description", product.Description));
                _Parametros.Add(new SqlParameter("@Brand", product.Brand));
                _Parametros.Add(new SqlParameter("@Ranking", product.Ranking));
                _Parametros.Add(new SqlParameter("@Price", product.Price));
                _Parametros.Add(new SqlParameter("@SeelingPrice", product.SeelingPrice));
                _Parametros.Add(new SqlParameter("@Status", product.Status));
                _Parametros.Add(new SqlParameter("@Image", product.Imagen));
                _Parametros.Add(new SqlParameter("@IdCategory", product.IdCategory));

                SqlParameter valreg = new SqlParameter();
                valreg.ParameterName = "@Id";
                valreg.DbType        = DbType.Int32;
                valreg.Direction     = ParameterDirection.Output;
                _Parametros.Add(valreg);

                sql.PrepararProcedimiento("dbo.[Product.Insert]", _Parametros);
                IdUser = int.Parse(sql.EjecutarProcedimientoOutput().ToString());
                return(IdUser);
            }
            catch (SqlException sqlEx) {
                throw new Exception(sqlEx.Message, sqlEx);
            }
            catch (Exception ex) {
                throw new Exception(ex.Message, ex);
            }
        }
Beispiel #8
0
        public int Create(Models.Product product)
        {
            int id = ++currentId;

            products.Add(id, product);
            return(id);
        }
 /// <summary>
 /// Product Types
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='responseCode'>
 /// The desired returned status code
 /// </param>
 /// <param name='product'>
 /// The only parameter
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task<Product> GetProductAsync(this ISwaggerDataTypesClient operations, string responseCode = default(string), Product product = default(Product), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.GetProductWithHttpMessagesAsync(responseCode, product, null, cancellationToken).ConfigureAwait(false))
     {
         return _result.Body;
     }
 }
 /// <summary>
 /// Long running put request, service returns a 400 to the initial request
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='product'>
 /// Product to put
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task<Product> BeginPutNonRetry400Async(this ILROSADsOperations operations, Product product = default(Product), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.BeginPutNonRetry400WithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false))
     {
         return _result.Body;
     }
 }
 /// <summary>
 /// Products
 /// </summary>
 /// The Products endpoint returns information about the Uber products offered
 /// at a given location. The response includes the display name and other
 /// details about each product, and lists the products in the proper display
 /// order.
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='subscriptionId'>
 /// Subscription Id.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Resource Group Id.
 /// </param>
 /// <param name='apiVersion'>
 /// API Id.
 /// </param>
 /// <param name='body'>
 /// API body mody.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task<Product> PostAsync( this IRecursiveTypesAPI operations, string subscriptionId, string resourceGroupName, string apiVersion, Product body = default(Product), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.PostWithHttpMessagesAsync(subscriptionId, resourceGroupName, apiVersion, body, null, cancellationToken).ConfigureAwait(false))
     {
         return _result.Body;
     }
 }
 /// <summary>
 /// Long running put request, service returns a 500, then a 201 to the initial
 /// request, with an entity that contains ProvisioningState=’Creating’.
 /// Polls return this value until the last poll returns a ‘200’ with
 /// ProvisioningState=’Succeeded’
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='product'>
 /// Product to put
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async System.Threading.Tasks.Task<Product> Put201CreatingSucceeded200Async(this ILRORetrysOperations operations, Product product = default(Product), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
 {
     using (var _result = await operations.Put201CreatingSucceeded200WithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false))
     {
         return _result.Body;
     }
 }
        public List <ProductInCart> GetProductInBasketByCoockie()
        {
            List <ProductInCart> productInCarts = new List <ProductInCart>();

            string[] basketItems = GetCookie();

            if (basketItems != null)
            {
                for (int i = 0; i < basketItems.Length - 1; i++)
                {
                    string[] productItem = basketItems[i].Split('^');

                    int productCode = Convert.ToInt32(productItem[0]);

                    Product product = db.Products.Where(current => current.Code == productCode)
                                      .FirstOrDefault();

                    productInCarts.Add(new ProductInCart()
                    {
                        Product  = product,
                        Quantity = Convert.ToInt32(productItem[1]),
                    });
                }
            }

            return(productInCarts);
        }
 public void Delete(Product product)
 {
     var products = db.GetCollection<Product>("Products");
     var query = Query.And(Query.EQ("Price", product.Price), Query.EQ("Name", product.Name));
     var findAndRemoveArguments = new FindAndRemoveArgs();
     findAndRemoveArguments.Query = query;
     products.FindAndRemove(findAndRemoveArguments);
 }
Beispiel #15
0
        public static List <Models.Product> RemoveReferences(this List <Models.Product> list)
        {
            var newList = new List <Models.Product>();

            list.ForEach(item =>
            {
                var obj = new Models.Product();
                obj     = item.RemoveReferences();
                newList.Add(obj);
            });
            return(newList);
        }
 public ActionResult Create(Product model)
 {
     if (ModelState.IsValid)
     {
         model.Id = _models.Count == 0 ? 1 : _models.Select(x => x.Id).Max() + 1;
         _models.Add(model);
         Success("Your information was saved!");
         return RedirectToAction("Index");
     }
     Error("there were some errors in your form.");
     return View(model);
 }
Beispiel #17
0
 private void insert_Click(object sender, EventArgs e)
 {
     Product product = new Product
     {
         Id = Int32.Parse(insertId.Text),
         Name = insertName.Text,
         Price = Double.Parse(insertPrice.Text),
         Quantity = Int32.Parse(insertQuantity.Text)
     };
     DbAccessor accessor = DbAccessor.Instance;
     accessor.CreateProduct(product);
 }
 public ActionResult Edit(Product model, int id)
 {
     if (ModelState.IsValid)
     {
         _models.Remove(_models.Get(id));
         model.Id = id;
         _models.Add(model);
         Success("The model was updated!");
         return RedirectToAction("index");
     }
     return View("Create", model);
 }
 public ActionResult Create(Product product)
 {
     try
     {
         productRepository.Add(product);
         productRepository.Save();
         return RedirectToAction("Index");
     }
     catch
     {
         return View();
     }
 }
        void IProduct.AddProduct(Models.Product product)
        {
            var newproduct = new Product()
            {
                ProductName        = product.ProductName,
                ProductPrice       = product.ProductPrice,
                ProductDescription = product.ProductDescription
            };

            _context.Add(newproduct);

            _context.SaveChanges();
        }
 public ActionResult Insert()
 {
     using (var db = new NorthwindDataContext())
     {
         var product = new Product();
         if (TryUpdateModel(product))
         {
             db.Products.InsertOnSubmit(product);
             db.SubmitChanges();
         }
     }
     return GetView();
 }
        public ActionResult AddToCart(string code, string qty)
        {
            int     productCode     = Convert.ToInt32(code);
            int     productQuantity = Convert.ToInt32(qty);
            Product product         = db.Products.Where(current => current.Code == productCode).FirstOrDefault();

            if (product.IsAvailable && product.Quantity >= productQuantity)
            {
                SetCookie(code, qty);
                ViewBag.HeaderImage = db.Texts.Where(x => x.TextType.Name == "shoppingimage").FirstOrDefault().ImageUrl;
                return(Json("true", JsonRequestBehavior.AllowGet));
            }

            return(Json("false", JsonRequestBehavior.AllowGet));
        }
        public string InsertProduct(Product product)
        {
            try
            {
                GarageEntities db = new GarageEntities();
                db.Products.Add(product);
                db.SaveChanges();

                return product.Name + " was succesfully inserted";
            }
            catch (Exception e)
            {
                return "Error:" + e;
            }
        }
        /// <summary>
        /// Populates defaults and opens edit form to add new record
        /// GET: /Admin/Product/Create
        /// </summary>
        public ActionResult Create(int?categoryid, string catTitle)
        {
            Breadcrumbs.Current.AddBreadcrumb(3, "Add Product");
            var record = new Models.Product();

            if (categoryid.HasValue)
            {
                var category = new ProductCategory();
                category.ID              = categoryid.Value;
                category.Title           = catTitle;
                record.ProductCategory   = category;
                record.ProductCategoryID = categoryid;
            }
            record.Action = "AddNew";
            // any default values can be set here or in partial class Product.InitDefaults()
            return(View("ProductEdit", record));
        }
Beispiel #25
0
        public bool Update(Models.Product product)
        {
            var sqlCommand = new SqlCommand();

            sqlCommand.CommandText = string.Format("UPDATE {0} SET ProductName = @ProductName, QuantityPerUnit = @QuantityPerUnit,ReorderLevel=@ReorderLevel,SupplierID=@SupplierID,UnitsInStock=@UnitsInStock,CategoryID=@CategoryID,Discontinued=@Discontinued,UnitPrice=@UnitPrice,UnitsOnOrder=@UnitsOnOrder WHERE {1} = @ProductID", tableName, primaryColumn);
            sqlCommand.Parameters.AddWithValue("@ProductID", product.ProductID);
            sqlCommand.Parameters.AddWithValue("@ProductName", product.ProductName);
            sqlCommand.Parameters.AddWithValue("@QuantityPerUnit", product.QuantityPerUnit);
            sqlCommand.Parameters.AddWithValue("@ReorderLevel", product.ReorderLevel);
            sqlCommand.Parameters.AddWithValue("@SupplierID", product.SupplierID);
            sqlCommand.Parameters.AddWithValue("@UnitsInStock", product.UnitsInStock);
            sqlCommand.Parameters.AddWithValue("@CategoryID", product.CategoryID);
            sqlCommand.Parameters.AddWithValue("@Discontinued", product.Discontinued);
            sqlCommand.Parameters.AddWithValue("@UnitPrice", product.UnitPrice);
            sqlCommand.Parameters.AddWithValue("@UnitsOnOrder", product.UnitsOnOrder);
            sqlCommand.Connection = _conn;
            return(sqlCommand.ExecuteNonQuery() > 0);
        }
Beispiel #26
0
 public ActionResult Create(Product product,HttpPostedFileBase file,FormCollection values)
 {
     if (ModelState.IsValid)
     {
         if (file != null)
         {
             product.ProductStores = new List<ProductStore>();
             product.ProductStores.Add(new ProductStore { SellPrice = Convert.ToDecimal(values["SellPrice"]), TimeCreated = DateTime.Now, });
             product.Image = new byte[file.ContentLength];
             file.InputStream.Read(product.Image, 0, file.ContentLength);
             storeDB.Products.Add(product);
             storeDB.SaveChanges();
         }
         return RedirectToAction("");
     }
     ViewBag.CategorieID = new SelectList(storeDB.Caegories, "CategorieID", "Name");
     return View();
 }
Beispiel #27
0
        public int Add(Models.Product product)
        {
            var sqlCommand = new SqlCommand();

            sqlCommand.CommandText = string.Format("INSERT INTO {0} (ProductName, QuantityPerUnit,ReorderLevel,SupplierID,UnitsInStock,CategoryID,Discontinued,UnitPrice,UnitsOnOrder) OUTPUT INSERTED.{1} VALUES (@ProductName, @QuantityPerUnit,@ReorderLevel,@SupplierID,@UnitsInStock,@CategoryID,@Discontinued,@UnitPrice,@UnitsOnOrder)", tableName, primaryColumn);
            sqlCommand.Parameters.AddWithValue("@ProductName", product.ProductName);
            sqlCommand.Parameters.AddWithValue("@QuantityPerUnit", product.QuantityPerUnit);
            sqlCommand.Parameters.AddWithValue("@ReorderLevel", product.ReorderLevel);
            sqlCommand.Parameters.AddWithValue("@SupplierID", product.SupplierID);
            sqlCommand.Parameters.AddWithValue("@UnitsInStock", product.UnitsInStock);
            sqlCommand.Parameters.AddWithValue("@CategoryID", product.CategoryID);
            sqlCommand.Parameters.AddWithValue("@Discontinued", product.Discontinued);
            sqlCommand.Parameters.AddWithValue("@UnitPrice", product.UnitPrice);
            sqlCommand.Parameters.AddWithValue("@UnitsOnOrder", product.UnitsOnOrder);
            sqlCommand.Connection = _conn;
            var id = sqlCommand.ExecuteScalar();

            return(id != null ? (int)id : -1);
        }
        public List<Product> ListAll()
        {
            _products = new List<Product>();
            string[] reader = File.ReadAllLines(FilePath);

            for (int i = 1; i < reader.Length; i++)
            {
                var columns = reader[i].Split(',');

                var product = new Product
                {
                    ProductType = columns[0],
                    CostPerSquareFoot= decimal.Parse(columns[1]),
                    LaborCostPerSquareFoot = decimal.Parse(columns[2]),
                };

                _products.Add(product);
            }

            return _products;
        }
        Models.Product IProduct.FindProductByName(string name)
        {
            Models.Product newproduct = new Models.Product();


            Product storequery = _context.Products.Where(x => x.ProductName.Equals(name)).First();

            if (storequery == null)
            {
                newproduct = null;
            }
            else
            {
                newproduct.Id                 = storequery.Id;
                newproduct.ProductName        = storequery.ProductName;
                newproduct.ProductDescription = storequery.ProductDescription;
                newproduct.ProductPrice       = storequery.ProductPrice;
                newproduct.ImageUrl           = storequery.ImageUrl;
            }

            return(newproduct);
        }
Beispiel #30
0
 public void AddToCart(Product product,HttpContextBase context)
 {
     var cartItem = storeDB.Carts.SingleOrDefault(a => a.CartID == ShopingCartID && a.ProductID == product.ProductID);
     if (cartItem == null)
     {
         cartItem = new Carts
         {
             ProductID = product.ProductID,
             CartID = ShopingCartID,
             TimeCreated = DateTime.Now,
             Quantity = 1,
             Price = product.ProductStores.OrderBy(p => p.TimeCreated).Single().SellPrice
         };
         if (context.Request.IsAuthenticated && storeDB.AccessControls.SingleOrDefault(ac => ac.UserName == context.User.Identity.Name).Fellow)
             cartItem.Price = product.ProductStores.OrderBy(p => p.TimeCreated).Single().FellowPrice;
         storeDB.Carts.Add(cartItem);
     }
     else
     {
         cartItem.Quantity++;
     }
     storeDB.SaveChanges();
 }
        protected ActionResult ProcessForm(Models.Product record)
        {
            try {
                record.UpdateFromRequest();
                // read subform or related checkboxes here eg record.Lines.UpdateFromRequest();
                Validate(record);
                if (ModelState.IsValid)
                {
                    Save(record, record.IsNewRecord);
                    Web.InfoMessage = "Product " + record.GetName() + " saved.";
                }
            } catch (UserErrorException e) {
                ModelState.AddModelError("Record", e.Message);
            }

            if (!ModelState.IsValid)
            {
                // invalid so redisplay form with validation message(s)
                return(View("ProductEdit", record));
            }
            else if (Web.Request["SaveAndRefreshButton"] != null)
            {
                return(RedirectToEdit(record.ID));
            }
            else if (Web.Request["DuplicateButton"] != null)
            {
                var newRecord = new Models.Product();
                newRecord.UpdateFrom(record);
                newRecord.Save();
                Web.InfoMessage = "Copy of Product " + record.GetName() + " created. You are now editing the new copy.";
                return(RedirectToEdit(newRecord.ID));
            }
            else
            {
                return(RedirectToReturnPage());
            }
        }
Beispiel #32
0
        public CurrentPriceBreakdown GetPriceBreakdown(string asin, Product amazonProductDetails, Data.PriceHistory priceHistory, FeePreview feePreviewForAsin, decimal?itemPrice)
        {
            if (itemPrice == null || feePreviewForAsin == null || priceHistory == null || amazonProductDetails == null ||
                amazonProductDetails.Weight == null || amazonProductDetails.Length == null || amazonProductDetails.Width == null ||
                amazonProductDetails.Height == null)
            {
                return new CurrentPriceBreakdown
                       {
                           MissingInfo = string.Format(
                               "Missing Info: <br>{0}{1}{2}{3}",
                               itemPrice.HasValue ? "Item Price<br>" : string.Empty,
                               feePreviewForAsin == null ? "Amazon Fee Preview<br>" : string.Empty,
                               priceHistory == null ? "Price History<br>" : string.Empty,
                               amazonProductDetails == null ? "Amazon Product Details" : string.Empty)
                       }
            }
            ;

            CurrentPriceBreakdown priceBreakdown = new CurrentPriceBreakdown
            {
                NewestPrice = priceHistory.NewPrice,
                LastUpdatedPriceDateTime = priceHistory.TimeStamp,
                AmazonReferralFee        = priceHistory.NewPrice * 0.15m,
                PerOrderFeePreview       = feePreviewForAsin.EstimatedOrderHandlingFeePerOrder,
                PerUnitFeePreview        = feePreviewForAsin.EstimatedPickPackFeePerUnit,
                WeightFeePreview         = feePreviewForAsin.EstimatedWeightHandlingFeePerUnit,
                ItemCost            = itemPrice.Value,
                EstShippingToAmazon = amazonProductDetails.Weight.Value * 0.70m,
                EstStorageFee       = (1.2m / (12m * 12m * 12m)) * amazonProductDetails.Length.Value * amazonProductDetails.Width.Value * amazonProductDetails.Height.Value,
                EstReturns          = priceHistory.NewPrice * 0.03m,
            };

            priceBreakdown.EstimatedProfit = priceBreakdown.NewestPrice - priceBreakdown.AmazonReferralFee -
                                             priceBreakdown.PerOrderFeePreview - priceBreakdown.PerUnitFeePreview - priceBreakdown.WeightFeePreview - itemPrice.Value - amazonProductDetails.Weight.Value * 0.70m - (1.2m / (12m * 12m * 12m)) * amazonProductDetails.Length.Value * amazonProductDetails.Width.Value * amazonProductDetails.Height.Value;                                         //// finish
            return(priceBreakdown);
        }
        public async Task <ActionResult <ProductViewModel> > PostProduct([FromBody] ProductViewModel viewModel)
        {
            var product = new Models.Product()
            {
                Name             = viewModel.Name,
                Image            = viewModel.Image,
                CreateDate       = DateTime.Now,
                LongDescription  = viewModel.LongDescription,
                Price            = viewModel.Price,
                ShortDescription = viewModel.ShortDescription,
                IsExist          = viewModel.IsExist,
            };
            //var categiories = new List<Category>();
            //viewModel.CategoryViewModel.ForEach(cat => categiories.Add(
            //    new Category
            //    {
            //        Description = cat.Description,
            //        Id = cat.Id,
            //        Name = cat.Name,
            //    }
            //    ));
            //product.Categories = categiories;
            //var categories = await UnitOfWork.CategoryRepository.GetAllAsync();
            //product.Categories = categories.Where(cat => viewModel.CategoriesId.Contains(cat.Id)).ToList();

            var selectedCategory = await UnitOfWork.ProductSelectedCategoryRepository.GetAllAsync();

            product.ProductSelectedCategories = selectedCategory.Where(cat => viewModel.CategoriesId.Contains(cat.Id)).ToList();

            await UnitOfWork.ProductRepository.Insert(product);


            await UnitOfWork.SaveAsync();

            return(CreatedAtAction("GetProduct", new { id = viewModel.Id }, viewModel));
        }
        public void ImportProductsFromCSVFile(string filename)
        {
            StreamReader reader = new StreamReader(filename);

            while (!reader.EndOfStream)
            {
                string[] currentElements = reader.ReadLine().Split(',');
                int vendorId = int.Parse(currentElements[0]);
                string productName = currentElements[1];
                int measureId = int.Parse(currentElements[2]);
                decimal price = decimal.Parse(currentElements[3]);

                Product product = new Product();
                product.Name = productName;
                product.VendorId = vendorId;
                product.MeasureId = measureId;
                product.BuyingPrice = price;

                this.sqlServerContext.Products.Add(product);
                this.sqlServerContext.SaveChanges();
            }

            reader.Close();
        }
        public void SeedProducts(string categoryName, string productsAsString, HomeGrownBulgariaDbContext context)
        {
            var category = context.ProductCategories.FirstOrDefault(x => x.Name == categoryName);

            if(category == null)
            {
                return;
            }

            var productsAsList = productsAsString.Split(',').Select(x=> x.Trim()).ToList();

            foreach(var productName in productsAsList)
            {
                var product = new Product()
                {
                    CategoryId = category.Id,
                    Name = productName
                };

                context.Products.AddOrUpdate(product);
            }

            context.SaveChanges();
        }
 /// <summary>
 /// Test explicitly optional complex object. Please put null.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='bodyParameter'>
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task PostOptionalClassParameterAsync( this IExplicitModel operations, Product bodyParameter = default(Product), CancellationToken cancellationToken = default(CancellationToken))
 {
     await operations.PostOptionalClassParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false);
 }
 /// <summary>
 /// Test explicitly optional complex object. Please put null.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='bodyParameter'>
 /// </param>
 public static void PostOptionalClassParameter(this IExplicitModel operations, Product bodyParameter = default(Product))
 {
     Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalClassParameterAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
 /// <summary>
 /// Test explicitly required complex object. Please put null and the client
 /// library should throw before the request is sent.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='bodyParameter'>
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task<Error> PostRequiredClassParameterAsync( this IExplicitModel operations, Product bodyParameter, CancellationToken cancellationToken = default(CancellationToken))
 {
     HttpOperationResponse<Error> result = await operations.PostRequiredClassParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false);
     return result.Body;
 }
 /// <summary>
 /// Test explicitly required complex object. Please put null and the client
 /// library should throw before the request is sent.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='bodyParameter'>
 /// </param>
 public static Error PostRequiredClassParameter(this IExplicitModel operations, Product bodyParameter)
 {
     return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredClassParameterAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
 /// <summary>
 /// Long running put request, service returns a 202 to the initial request
 /// with Azure-AsyncOperation header. Subsequent calls to operation status do
 /// not contain Azure-AsyncOperation header.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='product'>
 /// Product to put
 /// </param>
 public static Product BeginPutAsyncNoHeaderInRetry(this ILROsOperations operations, Product product = default(Product))
 {
     return Task.Factory.StartNew(s => ((ILROsOperations)s).BeginPutAsyncNoHeaderInRetryAsync(product), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
        public ActionResult CallBack(string authority, string status)
        {
            String            Status   = status;
            CallBackViewModel callBack = new CallBackViewModel();

            if (Status != "OK")
            {
                callBack.IsSuccess  = false;
                callBack.RefrenceId = "414";
                Order order = GetOrderByAuthority(authority);
                if (order != null)
                {
                    callBack.Order        = order;
                    callBack.OrderDetails = db.OrderDetails
                                            .Where(c => c.OrderId == order.Id && c.IsDeleted == false).Include(c => c.Product).ToList();
                }
            }

            else
            {
                try
                {
                    var zarinpal = ZarinPal.ZarinPal.Get();
                    zarinpal.EnableSandboxMode();
                    String Authority = authority;
                    long   Amount    = GetAmountByAuthority(Authority);

                    var verificationRequest  = new ZarinPal.PaymentVerification(MerchantId, Amount, Authority);
                    var verificationResponse = zarinpal.InvokePaymentVerification(verificationRequest);
                    if (verificationResponse.Status == 100 || verificationResponse.Status == 101)
                    {
                        Order order = GetOrderByAuthority(authority);
                        if (order != null)
                        {
                            order.IsPaid      = true;
                            order.PaymentDate = DateTime.Now;
                            order.RefId       = verificationResponse.RefID;

                            db.SaveChanges();
                            callBack.Order      = order;
                            callBack.IsSuccess  = true;
                            callBack.OrderCode  = order.Code.ToString();
                            callBack.RefrenceId = verificationResponse.RefID;

                            callBack.OrderDetails = db.OrderDetails
                                                    .Where(c => c.OrderId == order.Id && c.IsDeleted == false).Include(c => c.Product).ToList();
                            foreach (OrderDetail orderDetail in callBack.OrderDetails)
                            {
                                Product product = orderDetail.Product;
                                product.Quantity = orderDetail.Product.Quantity - 1;

                                if (product.Quantity == 0)
                                {
                                    product.IsAvailable = false;
                                }
                                db.SaveChanges();
                            }
                        }
                        else
                        {
                            callBack.IsSuccess  = false;
                            callBack.RefrenceId = "سفارش پیدا نشد";
                        }
                    }
                    else
                    {
                        callBack.IsSuccess  = false;
                        callBack.RefrenceId = verificationResponse.Status.ToString();
                    }
                }
                catch (Exception e)
                {
                    callBack.IsSuccess  = false;
                    callBack.RefrenceId = "خطا سیستمی. لطفا با پشتیبانی سایت تماس بگیرید";
                }
            }
            ViewBag.HeaderImage = db.Texts.Where(x => x.TextType.Name == "returnfrombank").FirstOrDefault().ImageUrl;

            return(View(callBack));
        }
 /// <summary>
 /// Long running put request, service returns a 201 to the initial request,
 /// with an entity that contains ProvisioningState=’Creating’.  Polls return
 /// this value until the last poll returns a ‘200’ with
 /// ProvisioningState=’Canceled’
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='product'>
 /// Product to put
 /// </param>
 public static Product Put200Acceptedcanceled200(this ILROsOperations operations, Product product = default(Product))
 {
     return Task.Factory.StartNew(s => ((ILROsOperations)s).Put200Acceptedcanceled200Async(product), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
 /// <summary>
 /// Long running post request, service returns a 202 to the initial request,
 /// with an entity that contains ProvisioningState=’Creating’. Poll the
 /// endpoint indicated in the Azure-AsyncOperation header for operation status
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='product'>
 /// Product to put
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task<LROsPostAsyncRetrycanceledHeaders> BeginPostAsyncRetrycanceledAsync(this ILROsOperations operations, Product product = default(Product), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.BeginPostAsyncRetrycanceledWithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false))
     {
         return _result.Headers;
     }
 }
 /// <summary>
 /// Validates body parameters on the method. See swagger for details.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required string between 3 and 10 chars with pattern [a-zA-Z0-9]+.
 /// </param>
 /// <param name='id'>
 /// Required int multiple of 10 from 100 to 1000.
 /// </param>
 /// <param name='body'>
 /// </param>
 public static Product ValidationOfBody(this IAutoRestValidationTest operations, string resourceGroupName, int id, Product body = default(Product))
 {
     return System.Threading.Tasks.Task.Factory.StartNew(s => ((IAutoRestValidationTest)s).ValidationOfBodyAsync(resourceGroupName, id, body), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
Beispiel #45
0
        public void EvaluatePriceList(PriceListFile priceListFile)
        {
            DataTable dt = ExcelUtility.ConvertExcelFileToDataTable(priceListFile.File);

            List <ManufacturerPriceListRowInput> manufacturerPriceListRowsInputs = dt.FromDataTableToList <ManufacturerPriceListRowInput>();

            // Price is always required.
            if (manufacturerPriceListRowsInputs.Any(a => !a.Price.HasValue))
            {
                throw new ArgumentException("Price must be set for all rows.");
            }

            // Need either UPC or ASIN.
            if (manufacturerPriceListRowsInputs.Any(a => a.ASIN == null && a.UPC == null))
            {
                throw new ArgumentException("ASIN or UPC must be set for all rows.");
            }

            List <ManufacturerPriceListRowOutput> manufacturerPriceListRowsOutputs = new List <ManufacturerPriceListRowOutput>();

            // Only lookup rows where either ASIN or UPC is set.
            foreach (ManufacturerPriceListRowInput manufacturerPriceListRow in manufacturerPriceListRowsInputs
                     .Where(w => !w.ASIN.IsNullOrEmptyTrimmed() || !w.UPC.IsNullOrEmptyTrimmed()))
            {
                LookupProductRequest lookupProductRequest = new LookupProductRequest
                {
                    SearchIndex   = priceListFile.SearchIndex,
                    ResponseGroup = ResponseGroup.Medium
                };

                if (manufacturerPriceListRow.ASIN != null)
                {
                    lookupProductRequest.IdType = IdType.ASIN;
                    lookupProductRequest.ItemId = manufacturerPriceListRow.ASIN;
                }
                else
                {
                    lookupProductRequest.IdType = IdType.UPC;
                    lookupProductRequest.ItemId = manufacturerPriceListRow.UPC;
                }

                LookupProductResponse lookupProductResponse = m_productAdvertisingApi.LookupProduct(lookupProductRequest);

                if (lookupProductResponse != null)
                {
                    Product product = lookupProductResponse.Product;

                    Listing listing = m_amazonApiClient.GetAllListingsForAsin(new[] { product.ASIN }).FirstOrDefault();

                    decimal?breakEven           = null;
                    decimal?profitMargin        = null;
                    decimal?lowestPrice         = null;
                    string  sellersRankCategory = null;

                    if (listing != null)
                    {
                        lowestPrice         = listing.LowestPrice;
                        sellersRankCategory = listing.SellersRankCategory;
                    }

                    if (product.Length.HasValue && product.Width.HasValue && product.Height.HasValue && product.Weight.HasValue)
                    {
                        DimensionContainer dimensionContainer = new DimensionContainer(
                            product.Length.Value,
                            product.Width.Value,
                            product.Height.Value,
                            product.Weight.Value);

                        breakEven = FeeStructureUtility.CalculateBreakEven(
                            dimensionContainer,
                            priceListFile.FeeCategory,
                            manufacturerPriceListRow.Price.Value);

                        if (lowestPrice.HasValue && lowestPrice.Value > 0)
                        {
                            profitMargin = FeeStructureUtility.CalculateProfitMargin(
                                dimensionContainer,
                                priceListFile.FeeCategory,
                                lowestPrice.Value,
                                manufacturerPriceListRow.Price.Value);
                        }
                    }

                    ManufacturerPriceListRowOutput manufacturerPriceListRowOutput = new ManufacturerPriceListRowOutput
                    {
                        ASIN                = product.ASIN,
                        UPC                 = manufacturerPriceListRow.UPC,
                        ProductName         = product.Name,
                        SellersRank         = lookupProductResponse.ProductMetadata.SalesRank,
                        SellersRankCategory = sellersRankCategory,
                        Category            = lookupProductResponse.ProductMetadata.ProductGroup,
                        Price               = manufacturerPriceListRow.Price.Value,
                        BreakEven           = breakEven.HasValue
                                                        ? breakEven.Value.ToString("F", CultureInfo.InvariantCulture)
                                                        : null,
                        LowestPrice = lowestPrice.HasValue
                                                        ? lowestPrice.Value.ToString("F", CultureInfo.InvariantCulture)
                                                        : null,
                        ProfitMargin = profitMargin.HasValue
                                                        ? string.Format("{0:0.00%}", profitMargin.Value)
                                                        : null
                    };

                    manufacturerPriceListRowsOutputs.Add(manufacturerPriceListRowOutput);
                }
            }

            ExcelUtility.WriteExcelFileToResponse(Response, manufacturerPriceListRowsOutputs, c_worksheetName, priceListFile.File.FileName);
        }
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='body'>
 /// </param>
 public static Product PostWithConstantInBody(this IAutoRestValidationTest operations, Product body = default(Product))
 {
     return System.Threading.Tasks.Task.Factory.StartNew(s => ((IAutoRestValidationTest)s).PostWithConstantInBodyAsync(body), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
Beispiel #47
0
        public Models.Product EditProduct(Models.Product product)
        {
            DateTime modifiedDate = DateTime.UtcNow;

            Product dataProduct = product.MapProductToData();

            Product productToReturn;

            using (AmazonMWSdbDataContext dc = m_amazonMWSdbDataContext.CreateWriteInstance())
            {
                Product databaseProduct = null;

                // Don't look up the product if we are attempting to create it.
                if (product.ProductId.HasValue)
                {
                    databaseProduct = dc.Products.SingleOrDefault(f => f.ProductId == product.ProductId);
                }

                if (databaseProduct != null)
                {
                    // ModifiedDate is updated, CreatedDate is not changed.
                    databaseProduct.ModifiedDate = modifiedDate;
                    databaseProduct.UPC          = dataProduct.UPC != null?dataProduct.UPC.Trim() : dataProduct.UPC;

                    databaseProduct.Name = dataProduct.Name != null?dataProduct.Name.Trim() : dataProduct.Name;

                    databaseProduct.Cost           = dataProduct.Cost;
                    databaseProduct.PromotionCost  = dataProduct.PromotionCost;
                    databaseProduct.MAPPrice       = dataProduct.MAPPrice;
                    databaseProduct.MinPrice       = dataProduct.MinPrice;
                    databaseProduct.MaxPrice       = dataProduct.MaxPrice;
                    databaseProduct.BreakevenPrice = dataProduct.BreakevenPrice;
                    databaseProduct.OverrideCost   = dataProduct.OverrideCost;
                    databaseProduct.QuantityInCase = dataProduct.QuantityInCase;
                    databaseProduct.ASIN           = dataProduct.ASIN != null?dataProduct.ASIN.Trim() : dataProduct.ASIN;

                    databaseProduct.SKU = dataProduct.SKU != null?dataProduct.SKU.Trim() : dataProduct.SKU;

                    databaseProduct.ItemNumber = dataProduct.ItemNumber != null?dataProduct.ItemNumber.Trim() : dataProduct.ItemNumber;

                    databaseProduct.ManufacturerId = dataProduct.ManufacturerId;
                    databaseProduct.Length         = dataProduct.Length;
                    databaseProduct.Width          = dataProduct.Width;
                    databaseProduct.Height         = dataProduct.Height;
                    databaseProduct.Weight         = dataProduct.Weight;
                    databaseProduct.IsMAP          = dataProduct.IsMAP;
                    databaseProduct.IsDiscontinued = dataProduct.IsDiscontinued;
                    databaseProduct.Notes          = dataProduct.Notes;

                    productToReturn = databaseProduct;
                }
                else
                {
                    DateTime today = DateTime.UtcNow;

                    dataProduct.CreatedDate  = today;
                    dataProduct.ModifiedDate = today;

                    // If the product doesn't already exist in the database, create it.
                    dc.Products.InsertOnSubmit(dataProduct);

                    productToReturn = dataProduct;
                }

                dc.SubmitChanges();
            }

            return(productToReturn.MapProductToModel());
        }
 /// <summary>
 /// Product Types
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='responseCode'>
 /// The desired returned status code
 /// </param>
 /// <param name='product'>
 /// The only parameter
 /// </param>
 public static Product PutProduct(this ISwaggerDataTypesClient operations, string responseCode = default(string), Product product = default(Product))
 {
     return Task.Factory.StartNew(s => ((ISwaggerDataTypesClient)s).PutProductAsync(responseCode, product), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
 private void Validate(Models.Product record)
 {
     // add any code to check for validity
     //ModelState.AddModelError("Record", "Suchandsuch cannot be whatever.");
 }
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='body'>
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async System.Threading.Tasks.Task<Product> PostWithConstantInBodyAsync(this IAutoRestValidationTest operations, Product body = default(Product), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
 {
     using (var _result = await operations.PostWithConstantInBodyWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false))
     {
         return _result.Body;
     }
 }
 private void Save(Models.Product record, bool isNew)
 {
     // add any code to update other fields/tables here
     record.Save();
     // save subform or related checkboxes here eg record.Lines.Save();
 }
 /// <summary>
 /// Validates body parameters on the method. See swagger for details.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required string between 3 and 10 chars with pattern [a-zA-Z0-9]+.
 /// </param>
 /// <param name='id'>
 /// Required int multiple of 10 from 100 to 1000.
 /// </param>
 /// <param name='body'>
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async System.Threading.Tasks.Task<Product> ValidationOfBodyAsync(this IAutoRestValidationTest operations, string resourceGroupName, int id, Product body = default(Product), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
 {
     using (var _result = await operations.ValidationOfBodyWithHttpMessagesAsync(resourceGroupName, id, body, null, cancellationToken).ConfigureAwait(false))
     {
         return _result.Body;
     }
 }
        public async Task <IActionResult> GetReview(int Id, int variantId)
        {
            var prod        = new Models.Product();
            var reviews     = new productReview();
            var RatingCount = 0;
            var ReviewCount = 0;
            var ratingTotal = 0;
            var oneStar     = 0;
            var TwoStar     = 0;
            var ThreeStar   = 0;
            var FourStar    = 0;
            var FiveStar    = 0;
            var allrates    = await db.RatingReviews.Where(x => x.ProductId == Id && x.IsActive == true).ToListAsync();

            if (allrates.Count() > 0)
            {
                var Users = await db.Users.Where(x => x.IsActive == true).ToListAsync();

                foreach (var item in allrates)
                {
                    var userRating = new UserRating();
                    var name       = Users.Where(x => x.Id == item.UserId).FirstOrDefault();
                    userRating.Username    = name.FirstName;
                    userRating.UserReviews = item.Review;
                    userRating.UserRatings = item.Rating;
                    reviews.UserRatings.Add(userRating);
                    if (item.Rating > 0)
                    {
                        RatingCount++;
                        ratingTotal += item.Rating;
                    }
                    if (item.Review != null)
                    {
                        ReviewCount++;
                    }
                    if (item.Rating == 5)
                    {
                        FiveStar++;
                    }
                    else if (item.Rating == 4)
                    {
                        FourStar++;
                    }
                    else if (item.Rating == 3)
                    {
                        ThreeStar++;
                    }
                    else if (item.Rating == 2)
                    {
                        TwoStar++;
                    }
                    else if (item.Rating == 1)
                    {
                        oneStar++;
                    }
                }

                if (RatingCount > 0)
                {
                    if (FiveStar > 0)
                    {
                        reviews.Fivestarper = (FiveStar * 100) / RatingCount;
                    }
                    if (FourStar > 0)
                    {
                        reviews.Fourstarper = (FourStar * 100) / RatingCount;
                    }
                    if (ThreeStar > 0)
                    {
                        reviews.Threestarper = (ThreeStar * 100) / RatingCount;
                    }
                    if (TwoStar > 0)
                    {
                        reviews.Twostarper = (TwoStar * 100) / RatingCount;
                    }
                    if (oneStar > 0)
                    {
                        reviews.Onestarper = (oneStar * 100) / RatingCount;
                    }
                }
                if (ratingTotal > 0 && RatingCount > 0)
                {
                    reviews.RatingAvg = ratingTotal / RatingCount;
                }

                reviews.ReviewCount = ReviewCount;
                reviews.RatingCount = RatingCount;
                reviews.Onestar     = oneStar;
                reviews.Twostar     = TwoStar;
                reviews.Threestar   = ThreeStar;
                reviews.Fourstar    = FourStar;
                reviews.Fivestar    = FiveStar;
            }
            return(Ok(reviews));
        }