상속: MonoBehaviour
예제 #1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ProductInfo product = new ProductInfo();
            product.Ghs = "金至尊";
            product.Pm = "品名1";
          /*
           product.Bz = "备注1";
            product.Cplb = "产品类别1";
            product.Cz = "材质1";
            product.Fcz = 50.0;
            product.Gchz = 55.00;
            product.Jjz = 51.01;
            product.ImgPath = "/web/images/logo.gif";
            product.Js = 1;
            product.Kh = "款号1";
            product.Lsj = 5999.98;
            product.Sc = "手寸123";
            product.Sjgf = 501.11;
            product.Ybh = "原编号";
            product.Gf = 101.12;
           * */
            product.State = "在库";
           // StringBuilder sb = new StringBuilder();
            string json = JsonConvert.SerializeObject(product, Formatting.Indented);

            Console.WriteLine("Json格式化列表:" + json);
            Response.Write(json);
            Response.End();
        }
    }
    // Load product info
    public static ProductInfo GetProductInfo(string productId)
    {
        DbCommand comm = DataAccessClass.CreateCommand();
        comm.CommandText = "StoreGetProductDetails";
        DbParameter param = comm.CreateParameter();
        param.ParameterName = "@ProductID";
        param.Value = productId;
        param.DbType = DbType.Int32;
        comm.Parameters.Add(param);

        DataTable table = DataAccessClass.ExecuteSelectCommand(comm);
           ProductInfo info = new ProductInfo();
        if (table.Rows.Count > 0)
        {
           DataRow dr = table.Rows[0];
           info.ProductID = int.Parse(productId);
            info.ProductName = dr["ProductName"].ToString();
            info.ProductDescription = dr["ProductDescription"].ToString();
            info.ProductPrice = Decimal.Parse(dr["ProductPrice"].ToString());
            info.ProductThumb = dr["ProductThumb"].ToString();
            info.ProductImage = dr["ProductImage"].ToString();
            info.BestSellShop = bool.Parse(dr["BestSellShop"].ToString());
            info.BestSellCategory = bool.Parse(dr["BestSellCategory"].ToString());
        }
           return info;
    }
예제 #3
0
        public IList<ProductInfo> GetProductList(int pageIndex, int pageSize, out int Total)
        {
            using (MyContext db = new MyContext())
            {
                Total = (from c in db.Product
                         orderby c.ID
                         select c).Count();
                var items = (from c in db.Product
                             orderby c.ID
                             select c).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                IList<ProductInfo> ProductInfos = new List<ProductInfo>();
                foreach (var item in items)
                {
                    ProductInfo info = new ProductInfo();
                    info.ID = item.ID;
                    info.ProductTypeID = item.ProductTypeID;
                    info.ProductTypeName = item.ProductType.ProductTypeName;//导航属性的特点
                    info.Image = item.Image;
                    info.ProductName = item.ProductName;
                    info.MarketPrice = item.MarketPrice;
                    info.NewPrice = item.NewPrice;
                    info.GetDate = item.GetDate.ToShortDateString();
                    info.Enable = item.Enable;
                    ProductInfos.Add(info);
                }

                return ProductInfos;
            }
        }
예제 #4
0
		public Domain.OrderLine ToOrderLine(OrderInfo orderInfo)
		{
			var productInfo = new ProductInfo();
			productInfo.Id = OriginalProductId;
			productInfo.ItemCount = Quantity;
			productInfo.Title = Title;
			productInfo.SKU = SKU;
			productInfo.Tags = Tags ?? new string[0];
			productInfo.Weight = Weight;
			productInfo.Length = Length;
			productInfo.Height = Height;
			productInfo.Width = Width;
			productInfo.OriginalPriceInCents = OriginalPrice;
			productInfo.RangesString = RangesString;
			productInfo.Vat = Vat;
			productInfo.DiscountId = DiscountId;

			productInfo.ProductVariants = ProductVariants ?? new List<ProductVariantInfo>();
			productInfo.DiscountPercentage = DiscountPercentage;
			productInfo.DiscountAmountInCents = DiscountAmount;
			productInfo.DiscountExcludingVariants = ExcludingVariants;

			productInfo.DocTypeAlias = DocTypeAlias;

			return new Domain.OrderLine(productInfo, orderInfo) {OrderLineId = OrderLineId, _customData = _customData};
		}
예제 #5
0
 private void GetMaxSequence(HttpContext context)
 {
     ProductInfo info = new ProductInfo();
     JsonObject obj2 = new JsonObject();
     string categoryPath = context.Request.Form["CategoryPath"];
     obj2.Put("STATUS", "SUCCESS");
     obj2.Put("DATA", info.MaxSequence(categoryPath) + 1);
     context.Response.Write(obj2);
 }
예제 #6
0
        public ActionResult Index(string id)
        {
            var products = _unitOfWork.ProductRepository.Get().ToList();
            var product = _unitOfWork.ProductRepository.GetById(new Guid(id));

            if (product == null)
            {
                return View("Error");
            }

            var image800x640Paths = product.Image800x640Paths.ToList();
            var imageAdditional = GetImageAdditionalModels(image800x640Paths);

            var relatedProductIds = _unitOfWork.RelatedProductRepository.Get(i=>i.ProductId==new Guid(id)).Select(r=>r.RelatedProductId);

            var relatedProducts = _unitOfWork.ProductRepository.Get(p => relatedProductIds.Contains(p.Id)).ToList();
            var relatedProductBlocks = GetRelatedProductBlocks(relatedProducts);

            var categoryViewModels = GetCategories(product, products);

            var specialProduct = products.First(i => i.Id == new Guid("CD4879A0-C210-4DAA-A6DE-A59E9CC153BF"));
            var specialProductViewModel = new SpecialProductViewModel
            {
                Id = specialProduct.Id.ToString(),
                Name = specialProduct.Name,
                OldPrice = specialProduct.OldPrice.HasValue ? specialProduct.OldPrice.Value.ToString("C") : string.Empty,
                NewPrice = specialProduct.NewPrice.ToString("C"),
                RatingImagePath = specialProduct.RatingImagePath,
                Image240x192Path = specialProduct.Image240x192Path
            };

            var productInfo = new ProductInfo
            {
                Id = product.Id.ToString(),
                Name = product.Name,
                DefaultImage = image800x640Paths.First(i => i.IsActive).Path,
                OldPrice = product.OldPrice.HasValue ? product.OldPrice.Value.ToString("C") : string.Empty,
                NewPrice = product.NewPrice.ToString("C"),
                ExTax = (product.NewPrice - product.NewPrice*.15m).ToString("C"),
                Brand = product.Brand.Name,
                BrandId = product.Brand.Id.ToString(),
                Description = product.Description,
                ImageAdditionals = imageAdditional,
                Availability = "In Stock"
            };

            var productModel = new ProductModel
            {
                ProductInfo=productInfo,
                RelatedProductBlocks = relatedProductBlocks,
                RelatedProductCount=relatedProducts.Count,
                CategoryViewModels=categoryViewModels,
                SpecialProductViewModel=specialProductViewModel
            };
            return View(productModel);
        }
 // Fill the control with data
 private void PopulateControls(ProductInfo pi)
 {
     // Display product details
     titleLabel.Text = pi.ProductName;
     descriptionLabel.Text = pi.ProductDescription;
     priceLabel.Text = String.Format("{0:c}", pi.ProductPrice);
     productImage.ImageUrl = "Product_Images/" + pi.ProductImage;
     // Set the title of the page
     this.Title = WscWebPortalConfiguration.SiteName + pi.ProductName;
 }
예제 #8
0
파일: LinqTest.cs 프로젝트: joonhwan/study
 public static Array GetLinqVar(ProductInfo[] pi)
 {
     return (from p in pi
             where p.Weight > 13
             select new
                 {
                     p.Name,
                     p.Description
                 }).ToArray();
 }
예제 #9
0
파일: LinqTest.cs 프로젝트: joonhwan/study
    public static void Main()
    {
        ProductInfo[]  pi = new ProductInfo[] {
            new ProductInfo("��ǰ1", "ù��ǰ�̴�", 11),
            new ProductInfo("��ǰ2", "<��ǰ�̴�", 12),
            new ProductInfo("��ǰA", "OP��ǰ�̴�", 13),
            new ProductInfo("��ǰB", "LKJ��ǰ�̴�", 14),
            new ProductInfo("��ǰC", "jasdf��ǰ�̴�", 15),
        };

        foreach (var v in GetLinqVar(pi))
        {
            Console.WriteLine(v);
        }

        // LINQ Enumerable �� Ȯ��޼ҵ带 ����� ����

        // - Ȯ�� �޼ҵ� Reverse<T>()
        // �߰� ��뿹��
        //    - �ε����� �����Ͽ� select�ϱ�
        //    - ��������� Linq �� IEnumerable<T>.Select() �Լ� ����
        var result = (from p in pi where p.Weight <= 12
                      select p).ToArray();
        foreach (var prod in result.Select ((p, index) =>
                                            new {
                                                Index = index,
                                                Name = p.Name,
                                            }).Reverse())
        {
            Console.WriteLine(prod);
        }

        List<string> myCars = new List<String> { "Yugo", "Aztec", "BMW" };
        List<string> yourCars = new List<String> { "BMW", "Saab", "Aztec" };

        // - Ȯ�� �޼ҵ� Except(), Union(), Intersect(), Concat(), Distinct()
        //   --> �����̰� ��ǥ�� �� ���̾�׷� !!!!
        var allMyCar = (from car in myCars select car);
        var allYourCars = (from car in yourCars select car);

        var concatUniqueCar = allMyCar.Concat(allYourCars).Distinct();
        PrintAll("concatUnique", concatUniqueCar);

        var carUnion = allMyCar.Union(allYourCars);
        PrintAll("union", carUnion);

        var carIntersect = allMyCar.Intersect(allYourCars);
        PrintAll("intersect", carIntersect);

        var carExceptYours = allMyCar.Except(allYourCars);
        PrintAll("Mine except Yours", carExceptYours);
    }
예제 #10
0
    protected void btnSure_Click(object sender, EventArgs e)
    {
        ProductInfo entity = new ProductInfo();

        WebFormHelper.GetDataFromForm(this, entity);
        // entity.MachineMac = FT.Commons.Web.Tools.WebToolsHelper.GetMac(entity.MachineIp);
        //entity.StartDate = Convert.ToDateTime(this.txtBeginDate.Value.ToString());
        // entity.EndDate = Convert.ToDateTime(this.txtEndDate.Value.ToString());
         entity.Imgs=ViewState["imgstr"].ToString();
         entity.ImgMain = ViewState["imgmain"].ToString();
        entity.Production=System.Web.HttpUtility.HtmlEncode(this.CKEditorControl1.Text);

        //Server.HtmlEncode(this.i_content.Text);
        if (entity.Id < 0)
        {
            if (SimpleOrmOperator.Create(entity))
            {
                WebTools.Alert(this, "添加成功!");
            }
            else
            {
                WebTools.Alert("添加失败!");

            }
        }
        else
        {
            if (SimpleOrmOperator.Update(entity))
            {
                WebTools.Alert(this, "修改成功!");
            }
            else
            {
                WebTools.Alert("修改失败!");

            }

        }
    }
예제 #11
0
        public IList<ProductInfo> GetProductsBySerach(int pageIndex, int pageSize, out int Total, int typeId, int id, string name, int NewPrice, bool? b)
        {
            using (MyContext db = new MyContext())
            {
                Total = (from c in db.Product
                         where ((id != 0) ? c.ID == id : true) && ((typeId != 0) ? c.ProductTypeID == typeId : true) &&
                             (!string.IsNullOrEmpty(name) ? c.ProductName.Contains(name) : true) &&
                             ((NewPrice != 0) ? c.NewPrice == NewPrice : true) &&
                             ((b == null) ? true : c.Enable == b)//传值为NULL就是全部
                         orderby c.ProductTypeID
                         select c).Count();
                var items = (from c in db.Product
                             where ((id != 0) ? c.ID == id : true) && ((typeId != 0) ? c.ProductTypeID == typeId : true) &&
                            (!string.IsNullOrEmpty(name) ? c.ProductName.Contains(name) : true) &&
                            ((NewPrice != 0) ? c.NewPrice == NewPrice : true) &&
                            ((b == null) ? true : c.Enable == b)//传值为NULL就是全部
                             orderby c.ProductTypeID//必须在分页前排序
                             select c).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

                List<ProductInfo> ProductInfos = new List<ProductInfo>();
                foreach (var item in items)
                {
                    ProductInfo info = new ProductInfo();
                    info.ID = item.ID;
                    info.ProductTypeID = item.ProductTypeID;
                    info.ProductTypeName = item.ProductType.ProductTypeName;//导航属性的特点
                    info.Image = item.Image;
                    info.ProductName = item.ProductName;
                    info.MarketPrice = item.MarketPrice;
                    info.NewPrice = item.NewPrice;
                    info.GetDate = item.GetDate.ToShortDateString();
                    info.Enable = item.Enable;
                    ProductInfos.Add(info);
                }

                return ProductInfos;
            }
        }
예제 #12
0
		public override void  productInfo(ProductInfo tag)
		{
			frame.controlTags.Add(tag);
		}
예제 #13
0
        static public List<MO> GetAvailableMO(SqlConnection connect,
                                                                  Log log, 
                                                                  ProductInfo prodInfo, 
                                                                   int startDateoffset,
                                                                   int udtOffset )
        {
            List<MO> ret = new List<MO>();

            DateTime now = DateTime.Now;
            DateTime startDate = now.AddDays(startDateoffset);
            DateTime udtDate = now.AddDays(udtOffset);

            SqlCommand dbCmd = connect.CreateCommand();
            dbCmd.CommandType = CommandType.Text;
            dbCmd.CommandText = @"select MO, (Qty-Print_Qty) as qty  from MO 
                                                          where Model=@model and 
                                                                     StartDate>=@StartDate and
                                                                     Qty>Print_Qty and
                                                                      Status ='H'  and  
                                                                     Udt>=@UpdateTime
                                                         order by StartDate, Udt";
            SQLHelper.createInputSqlParameter(dbCmd, "@model", 15, prodInfo.Model);
            SQLHelper.createInputSqlParameter(dbCmd, "@StartDate", 1, startDate);
            SQLHelper.createInputSqlParameter(dbCmd, "@UpdateTime", udtDate);


            log.write(LogType.Info, 0, "SQL", "GetAvailableMO", dbCmd.CommandText);
            log.write(LogType.Info, 0, "SQL", "@model", prodInfo.Model);
            log.write(LogType.Info, 0, "SQL", "@StartDate", startDate.ToString());
            log.write(LogType.Info, 0, "SQL", "@UpdateTime", udtDate.ToString());

            SqlDataReader sdr = dbCmd.ExecuteReader();
            while (sdr.Read())
            {
                MO mo = new MO();
                mo.MOId = sdr.GetString(0).Trim();
                mo.Qty = sdr.GetInt32(1);

                ret.Add(mo);
            }
            sdr.Close();
            return ret;
        }
        public override ProductInfo GetProductById(long productid)
        {
            ProductInfo res = null;
            using (MySqlConnection conn = new MySqlConnection(GetConnectionString()))
            {
                using (MySqlCommand cmd = new MySqlCommand(QRY_GET_PRODUCT_BY_ID, conn))
                {
                    cmd.Parameters.Add("@product_id", MySqlDbType.Int64).Value = productid;

                    try
                    {
                        conn.Open();
                        using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
                        {
                            if (reader.HasRows)
                            {
                                if (reader.Read())
                                {
                                    long productId = reader.GetInt64(0);
                                    string name = reader.GetString(1);
                                    string desc = reader.GetString(2);
                                    int credits = reader.GetInt32(3);
                                    string extra = reader.GetString(4);
                                    res = new ProductInfo(productId, name, desc, credits, extra);
                                }
                            }
                        }
                    }
                    catch (MySqlException ex)
                    {
                        Logger.Instance.Write(LogLevel.Error, ex, "GetProductById<Exception>");
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            return res;
        }
예제 #15
0
 public static string AddProductNew(ProductInfo product, Dictionary<string, SKUItem> skus, Dictionary<int, IList<int>> attrs, IList<int> tagsId,string wid)
 {
     string str = string.Empty;
     if (product == null)
     {
         return "未知错误";
     }
     Globals.EntityCoding(product, true);
     int decimalLength = SettingsManager.GetMasterSettings(true,wid).DecimalLength;
     if (product.MarketPrice.HasValue)
     {
         product.MarketPrice = new decimal?(Math.Round(product.MarketPrice.Value, decimalLength));
     }
     ProductActionStatus unknowError = ProductActionStatus.UnknowError;
     using (DbConnection connection = DatabaseFactory.CreateDatabase().CreateConnection())
     {
         connection.Open();
         DbTransaction dbTran = connection.BeginTransaction();
         try
         {
             ProductDao dao = new ProductDao();
             int productId = dao.AddProduct(product, dbTran);
             if (productId == 0)
             {
                 dbTran.Rollback();
                 return "货号重复";
             }
             str = productId.ToString();
             product.ProductId = productId;
             if (((skus != null) && (skus.Count > 0)) && !dao.AddProductSKUs(productId, skus, dbTran,wid))
             {
                 dbTran.Rollback();
                 return "添加SUK出错";
             }
             if (((attrs != null) && (attrs.Count > 0)) && !dao.AddProductAttributes(productId, attrs, dbTran))
             {
                 dbTran.Rollback();
                 return "添加商品属性出错";
             }
             if (((tagsId != null) && (tagsId.Count > 0)) && !new TagDao().AddProductTags(productId, tagsId, dbTran))
             {
                 dbTran.Rollback();
                 return "添加商品标签出错";
             }
             dbTran.Commit();
             unknowError = ProductActionStatus.Success;
         }
         catch (Exception)
         {
             dbTran.Rollback();
         }
         finally
         {
             connection.Close();
         }
     }
     if (unknowError == ProductActionStatus.Success)
     {
         EventLogs.WriteOperationLog(Privilege.AddProducts, string.Format(CultureInfo.InvariantCulture, "上架了一个新商品:”{0}”", new object[] { product.ProductName }));
     }
     return str;
 }
예제 #16
0
        protected void ImportProducts(object sender, EventArgs e)
        {
            string categoryId    = ProductClass.ClassID;
            int    saleStatus    = Convert.ToInt32(IsSale.SelectedValue);
            string selectedValue = dropFiles.SelectedValue;

            selectedValue = Path.Combine(_dataPath, selectedValue);

            if (!File.Exists(selectedValue))
            {
                ScriptHelper.Alert("选择的数据包文件有问题!");
            }
            else
            {
                PrepareDataFiles(new object[] { selectedValue });
                string    path        = Path.Combine(_dataPath, Path.GetFileNameWithoutExtension(selectedValue));
                DataTable productData = (DataTable)ProductBLL.ParseProductData(new object[] { path })[0];
                if ((productData != null) && (productData.Rows.Count > 0))
                {
                    foreach (DataRow row in productData.Rows)
                    {
                        ProductInfo product = new ProductInfo
                        {
                            ClassId       = categoryId,
                            Name          = (string)row["ProductName"],
                            ProductNumber = (string)row["SKU"],
                            BrandId       = 0
                        };
                        if (row["Description"] != DBNull.Value)
                        {
                            product.Introduction1 = (string)row["Description"];
                        }
                        product.AddDate           = DateTime.Now;
                        product.IsSale            = saleStatus;
                        product.MarketPrice       = (decimal)row["SalePrice"];
                        product.TotalStorageCount = (int)row["Stock"];

                        product.Spelling  = ChineseCharacterHelper.GetFirstLetter((string)row["ProductName"]);
                        product.SendPoint = 0;
                        product.Weight    = 0;
                        product.IsSpecial = 0;
                        product.IsNew     = 0;
                        product.IsHot     = 0;
                        if (row["Has_ShowCase"] != DBNull.Value)
                        {
                            product.IsTop = Convert.ToInt32(row["Has_ShowCase"]);
                        }
                        product.AllowComment = 0;
                        product.LowerCount   = 0;
                        product.UpperCount   = 0;
                        product.StandardType = 0;
                        product.AddDate      = RequestHelper.DateNow;

                        product.OrderId   = 0;
                        product.SalePrice = (decimal)row["SalePrice"];

                        if (row["ImageUrl1"] != DBNull.Value)
                        {
                            product.Photo = (string)row["ImageUrl1"];
                        }

                        int proID = ProductBLL.Add(product);
                        #region 生成缩略图和产品相册图
                        if (!(string.IsNullOrEmpty(product.Photo) || (product.Photo.Length <= 0)))
                        {
                            UploadImage(product.Photo, PhotoType.Product);
                        }

                        if (row["ImageUrl2"] != DBNull.Value)
                        {
                            ProductPhotoInfo tempPhoto = new ProductPhotoInfo()
                            {
                                ProductId = proID,
                                Name      = "ImageUrl2",
                                ImageUrl  = (string)row["ImageUrl2"],
                                AddDate   = DateTime.Now
                            };
                            ProductPhotoBLL.Add(tempPhoto);
                            UploadImage(tempPhoto.ImageUrl, PhotoType.ProductPhoto);
                        }
                        if (row["ImageUrl3"] != DBNull.Value)
                        {
                            ProductPhotoInfo tempPhoto = new ProductPhotoInfo()
                            {
                                ProductId = proID,
                                Name      = "ImageUrl3",
                                ImageUrl  = (string)row["ImageUrl3"],
                                AddDate   = DateTime.Now
                            };
                            ProductPhotoBLL.Add(tempPhoto);
                            UploadImage(tempPhoto.ImageUrl, PhotoType.ProductPhoto);
                        }
                        if (row["ImageUrl4"] != DBNull.Value)
                        {
                            ProductPhotoInfo tempPhoto = new ProductPhotoInfo()
                            {
                                ProductId = proID,
                                Name      = "ImageUrl4",
                                ImageUrl  = (string)row["ImageUrl4"],
                                AddDate   = DateTime.Now
                            };
                            ProductPhotoBLL.Add(tempPhoto);
                            UploadImage(tempPhoto.ImageUrl, PhotoType.ProductPhoto);
                        }
                        if (row["ImageUrl5"] != DBNull.Value)
                        {
                            ProductPhotoInfo tempPhoto = new ProductPhotoInfo()
                            {
                                ProductId = proID,
                                Name      = "ImageUrl5",
                                ImageUrl  = (string)row["ImageUrl5"],
                                AddDate   = DateTime.Now
                            };
                            ProductPhotoBLL.Add(tempPhoto);
                            UploadImage(tempPhoto.ImageUrl, PhotoType.ProductPhoto);
                        }
                        #endregion
                    }

                    File.Delete(selectedValue);
                    Directory.Delete(path, true);
                    BindFiles();
                    ScriptHelper.Alert("此次商品批量导入操作已成功!", RequestHelper.RawUrl);
                }
            }
        }
예제 #17
0
        public async Task <NotificationResult> InsertAsync(InsertProductCommand insertProductCommand)
        {
            var product = new ProductInfo(insertProductCommand);

            return(await _repository.InsertAsync(product));
        }
예제 #18
0
        protected virtual IReadOnlyList <IRelationalCommand> GenerateUpSql([NotNull] Migration migration)
        {
            Check.NotNull(migration, nameof(migration));

            var commands = new List <IRelationalCommand>();

            commands.AddRange(_migrationsSqlGenerator.Generate(migration.UpOperations, migration.TargetModel));
            commands.Add(
                _sqlCommandBuilder.Build(_historyRepository.GetInsertScript(new HistoryRow(migration.GetId(), ProductInfo.GetVersion()))));

            return(commands);
        }
예제 #19
0
        /// <summary>
        /// 更新商品
        /// </summary>
        /// <param name="goods">商品信息</param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static ErrorEntity UpdateGoods(ProductInfo goods, string accessToken)
        {
            var url = String.Format("https://api.weixin.qq.com/merchant/update?access_token={0}", accessToken);

            return(Utils.PostResult <ProductId>(goods, url));
        }
예제 #20
0
 public void UpdateProductInfo(ProductInfo productInfo)
 {
     ProductRepository.UpdateProductData(productInfo.ToProduct());
 }
예제 #21
0
        public ActionResult ThemeControl(string id)
        {
            var product = _unitOfWork.ProductRepository.GetById(new Guid(id));

            if (product == null)
            {
                return View("Error");
            }

            var image800x640Paths = product.Image800x640Paths.ToList();
            var imageAdditional = GetImageAdditionalModels(image800x640Paths);

            var productInfo = new ProductInfo
            {
                Id = product.Id.ToString(),
                Name = product.Name,
                DefaultImage = image800x640Paths.First(i => i.IsActive).Path,
                OldPrice = product.OldPrice.HasValue ? product.OldPrice.Value.ToString("C") : string.Empty,
                NewPrice = product.NewPrice.ToString("C"),
                ExTax = (product.NewPrice - product.NewPrice*.15m).ToString("C"),
                Brand = product.Brand.Name,
                BrandId = product.Brand.Id.ToString(),
                Description = product.Description,
                ImageAdditionals = imageAdditional,
                Availability = "In Stock"
            };
            return View(productInfo);
        }
예제 #22
0
        private void btnUpdate_Click(object sender, System.EventArgs e)
        {
            if (this.categoryId == 0)
            {
                this.categoryId = (int)this.ViewState["ProductCategoryId"];
            }
            if (this.categoryId == 0)
            {
                this.ShowMsg("请选择商品分类", false);
                return;
            }
            ProductInfo productInfo = new ProductInfo();

            productInfo.ProductId  = this.productId;
            productInfo.CategoryId = this.categoryId;
            CategoryInfo category = SubsiteCatalogHelper.GetCategory(productInfo.CategoryId);

            if (category != null)
            {
                productInfo.MainCategoryPath = category.Path + "|";
            }
            productInfo.ProductName      = this.txtProductName.Text;
            productInfo.ShortDescription = this.txtShortDescription.Text;
            productInfo.Description      = this.fckDescription.Text;
            productInfo.Title            = this.txtTitle.Text;
            productInfo.MetaDescription  = this.txtMetaDescription.Text;
            productInfo.MetaKeywords     = this.txtMetaKeywords.Text;
            if (!string.IsNullOrEmpty(this.txtMarketPrice.Text))
            {
                productInfo.MarketPrice = new decimal?(decimal.Parse(this.txtMarketPrice.Text));
            }
            System.Collections.Generic.Dictionary <string, decimal> skuSalePrice = null;
            if (!string.IsNullOrEmpty(this.txtSkuPrice.Text))
            {
                skuSalePrice = this.GetSkuPrices();
            }
            ProductSaleStatus productSaleStatus = ProductSaleStatus.OnStock;

            if (this.radInStock.Checked)
            {
                productSaleStatus = ProductSaleStatus.OnStock;
            }
            if (this.radUnSales.Checked)
            {
                productSaleStatus = ProductSaleStatus.UnSale;
            }
            if (this.radOnSales.Checked)
            {
                productSaleStatus = ProductSaleStatus.OnSale;
            }
            if (productSaleStatus == ProductSaleStatus.OnSale)
            {
                bool flag = false;
                System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
                try
                {
                    xmlDocument.LoadXml(this.txtSkuPrice.Text);
                    System.Xml.XmlNodeList xmlNodeList = xmlDocument.SelectNodes("//item");
                    if (xmlNodeList != null && xmlNodeList.Count > 0)
                    {
                        foreach (System.Xml.XmlNode xmlNode in xmlNodeList)
                        {
                            decimal d = decimal.Parse(xmlNode.Attributes["price"].Value);
                            if (d < decimal.Parse(this.litLowestSalePrice.Text))
                            {
                                flag = true;
                                break;
                            }
                        }
                    }
                }
                catch
                {
                }
                if (flag)
                {
                    this.ShowMsg("此商品的一口价已经低于了最低零售价,不允许上架", false);
                    return;
                }
            }
            System.Collections.Generic.IList <int> list = new System.Collections.Generic.List <int>();
            if (!string.IsNullOrEmpty(this.txtProductTag.Text.Trim()))
            {
                string   text = this.txtProductTag.Text.Trim();
                string[] array;
                if (text.Contains(","))
                {
                    array = text.Split(new char[]
                    {
                        ','
                    });
                }
                else
                {
                    array = new string[]
                    {
                        text
                    };
                }
                string[] array2 = array;
                for (int i = 0; i < array2.Length; i++)
                {
                    string value = array2[i];
                    list.Add(System.Convert.ToInt32(value));
                }
            }
            productInfo.SaleStatus = productSaleStatus;
            int displaySequence = 0;

            int.TryParse(this.txtDisplaySequence.Text, out displaySequence);
            productInfo.DisplaySequence = displaySequence;
            if (SubSiteProducthelper.UpdateProduct(productInfo, skuSalePrice, list))
            {
                this.litralProductTag.SelectedValue = list;
                this.ShowMsg("修改商品成功", true);
            }
        }
예제 #23
0
 public async Task UpdateAsync(string userId, ProductInfo productInfo)
 {
     productInfo.RowKey       = productInfo.Id.ToString();
     productInfo.PartitionKey = userId;
     await _repository.Update(productInfo);
 }
예제 #24
0
 public virtual void BeforeTest()
 {
     this.productInfo  = new ProductInfo("pdfProduct", 1, 0, 0, true);
     this.productInfo2 = new ProductInfo("pdfProduct2", 1, 0, 0, true);
 }
예제 #25
0
        static public bool  AssignMO(SqlConnection connect,
                                                       Log log,
                                                        AppConfig config,
                                                        ProductInfo prodInfo, 
                                                       CDSIPO poInfo)
        {
            bool selectedMo = false;

            List<MO> moList=  GetAvailableMO(connect,
                                                                           log,
                                                                           prodInfo,
                                                                            config.MOStartDateOffSetDay,
                                                                            config.MOUdtOffSetDay);
            if (moList.Count == 0) return selectedMo;
            
            int availableQty=0;
           
            foreach (MO mo in moList)
            {
                availableQty = mo.Qty- GetAssignMOQty(connect, log, mo.MOId);
                if (availableQty > 0)
                {
                   
                    poInfo.MOId = mo.MOId;
                    selectedMo = true;
                    break;
                }
            }

            return selectedMo;

        }
예제 #26
0
        /// <summary>
        /// 获取赠品所有信息
        /// </summary>
        /// <param name="sysNo"></param>
        /// <returns></returns>
        public virtual SaleGiftInfo Load(int?sysNo)
        {
            SaleGiftInfo info = _processor.Load(sysNo);

            if (info.ProductCondition != null)
            {
                foreach (SaleGift_RuleSetting setting in info.ProductCondition)
                {
                    if (setting.RelBrand != null && setting.RelBrand.SysNo.HasValue)
                    {
                        var brandName = ExternalDomainBroker.GetBrandInfoBySysNo(setting.RelBrand.SysNo.Value);
                        if (brandName != null && brandName.BrandNameLocal != null)
                        {
                            setting.RelBrand.Name = brandName.BrandNameLocal.Content;
                        }
                    }
                    if (setting.RelC3 != null && setting.RelC3.SysNo.HasValue)
                    {
                        var categoryName = ExternalDomainBroker.GetCategory3Info(setting.RelC3.SysNo.Value);
                        if (categoryName != null && categoryName.CategoryName != null)
                        {
                            setting.RelC3.Name = categoryName.CategoryName.Content;
                        }
                    }
                    if (setting.RelProduct != null && setting.RelProduct.ProductSysNo.HasValue)
                    {
                        ProductInfo product = ExternalDomainBroker.GetProductInfo(setting.RelProduct.ProductSysNo.Value);
                        if (product != null)
                        {
                            setting.RelProduct.ProductName = product.ProductName;
                            setting.RelProduct.ProductID   = product.ProductID;
                            //获取商品可用库存,代销库存,毛利率等接口
                            ProductInventoryInfo inventory = ExternalDomainBroker.GetProductTotalInventoryInfo(product.SysNo);
                            setting.RelProduct.AvailableQty = inventory.AvailableQty;
                            setting.RelProduct.ConsignQty   = inventory.ConsignQty;
                            setting.RelProduct.VirtualQty   = inventory.VirtualQty;

                            setting.RelProduct.UnitCost     = product.ProductPriceInfo.UnitCost;
                            setting.RelProduct.CurrentPrice = product.ProductPriceInfo.CurrentPrice;
                        }
                    }
                }

                foreach (SaleGift_RuleSetting setting in info.ProductCondition)
                {
                    if (setting.RelProduct.ProductSysNo.HasValue)
                    {
                        ProductInfo product = ExternalDomainBroker.GetProductInfo(setting.RelProduct.ProductSysNo.Value);
                        if (product != null)
                        {
                            int minBuyQty = setting.RelProduct.MinQty.HasValue ? (setting.RelProduct.MinQty.Value == 0 ? 1 : setting.RelProduct.MinQty.Value) : 1;
                            setting.RelProduct.GrossMarginRate = ObjectFactory <GrossMarginProcessor> .Instance.GetSaleGift_SaleItemGrossMarginRate(product,
                                                                                                                                                    minBuyQty, sysNo.Value, info);
                        }
                    }
                }
            }

            if (info.GiftItemList != null)
            {
                foreach (RelProductAndQty giftItem in info.GiftItemList)
                {
                    ProductInfo product = ExternalDomainBroker.GetProductInfo(giftItem.ProductSysNo.Value);
                    if (product == null)
                    {
                        continue;
                    }
                    giftItem.ProductName = product.ProductName;;
                    giftItem.ProductID   = product.ProductID;
                    //获取商品可用库存,代销库存,毛利率等接口
                    ProductInventoryInfo inventory = ExternalDomainBroker.GetProductTotalInventoryInfo(product.SysNo);
                    if (inventory == null)
                    {
                        continue;
                    }
                    giftItem.AvailableQty    = inventory.AvailableQty;
                    giftItem.ConsignQty      = inventory.ConsignQty;
                    giftItem.VirtualQty      = inventory.VirtualQty;
                    giftItem.GrossMarginRate = ObjectFactory <GrossMarginProcessor> .Instance.GetSaleGift_GiftItemGrossMarginRate(product, info.DisCountType.Value);

                    giftItem.UnitCost     = product.ProductPriceInfo.UnitCost;
                    giftItem.CurrentPrice = product.ProductPriceInfo.CurrentPrice;
                }
            }
            return(info);
        }
예제 #27
0
        public JsonResult GetBranchCartProducts(long shopBranchId)
        {
            BranchCartHelper helper   = new BranchCartHelper();
            long             memberId = 0L;
            decimal          discount = 1.0M;

            if (base.CurrentUser != null)
            {
                memberId = base.CurrentUser.Id;
                discount = base.CurrentUser.MemberDiscount;
            }
            ShoppingCartInfo       cart           = helper.GetCart(memberId, shopBranchId);
            ShopBranchInfo         shopBranchById = this._iShopBranchService.GetShopBranchById(shopBranchId);
            Dictionary <long, int> buyedCounts    = null;

            if (memberId > 0L)
            {
                buyedCounts = new Dictionary <long, int>();
                buyedCounts = OrderApplication.GetProductBuyCount(memberId, from x in cart.Items select x.ProductId);
            }
            decimal prodPrice = 0.0M;
            List <ShopBranchSkusInfo> shopBranchSkuList = this._iShopBranchService.GetSkusByIds(shopBranchId, from x in cart.Items select x.SkuId);
            var enumerable = from s in cart.Items.Select(delegate(ShoppingCartItem item)
            {
                ProductInfo product      = this._iProductService.GetProduct(item.ProductId);
                ShopBranchSkusInfo info2 = shopBranchSkuList.FirstOrDefault <ShopBranchSkusInfo>(x => x.SkuId == item.SkuId);
                long maxBuyCount         = (info2 == null) ? ((long)0) : ((long)info2.Stock);
                if ((maxBuyCount > product.MaxBuyCount) && (product.MaxBuyCount != 0))
                {
                    maxBuyCount = product.MaxBuyCount;
                }
                if (((product.MaxBuyCount > 0) && (buyedCounts != null)) && buyedCounts.ContainsKey(item.ProductId))
                {
                    int num2     = buyedCounts[item.ProductId];
                    maxBuyCount -= num2;
                }
                ShopInfo shop = this._iShopService.GetShop(product.ShopId, false);
                SKUInfo sku   = null;
                string str    = "";
                if (null != shop)
                {
                    VShopInfo vShopByShopId = this._iVShopService.GetVShopByShopId(shop.Id);
                    sku = this._iProductService.GetSku(item.SkuId);
                    if (sku == null)
                    {
                        return(null);
                    }
                    prodPrice = sku.SalePrice;
                    if (shop.IsSelf)
                    {
                        prodPrice = sku.SalePrice * discount;
                    }
                    ProductType type = TypeApplication.GetType(product.TypeId);
                    str = "";
                    if (!string.IsNullOrWhiteSpace(sku.Size))
                    {
                        str = str + sku.Size + "&nbsp;&nbsp;";
                    }
                    if (!string.IsNullOrWhiteSpace(sku.Color))
                    {
                        str = str + sku.Color + "&nbsp;&nbsp;";
                    }
                    if (!string.IsNullOrWhiteSpace(sku.Version))
                    {
                        str = str + sku.Version + "&nbsp;&nbsp;";
                    }
                    return(new { bId = shopBranchId, cartItemId = item.Id, skuId = item.SkuId, id = product.Id, name = product.ProductName, price = prodPrice, count = item.Quantity, stock = (info2 == null) ? 0L : maxBuyCount, status = (info2 == null) ? 1 : ((info2.Status == ShopBranchSkuStatus.Normal) ? ((item.Quantity > maxBuyCount) ? 2 : 0) : 1), skuDetails = str, AddTime = item.AddTime });
                }
                return(null);
            })
                             where s != null
                             orderby s.status, s.AddTime descending
            select s;
            var data = new
            {
                products         = enumerable,
                amount           = Enumerable.Sum(Enumerable.Where(enumerable, x => x.status == 0), item => item.price * (Decimal)item.count),
                totalCount       = Enumerable.Sum(Enumerable.Where(enumerable, x => x.status == 0), item => item.count),
                DeliveFee        = shopBranchById.DeliveFee,
                DeliveTotalFee   = shopBranchById.DeliveTotalFee,
                FreeMailFee      = shopBranchById.FreeMailFee,
                shopBranchStatus = shopBranchById.Status
            };

            return(base.Json(data));
        }
예제 #28
0
 /// <summary>
 /// Builds <see cref="IServiceManager"/> instances.
 /// </summary>
 /// <returns>The instance of the <see cref="IServiceManager"/>.</returns>
 public IServiceManager Build()
 {
     _options.ValidateOptions();
     return(new ServiceManager(_options, ProductInfo.GetProductInfo(_assembly)));
 }
예제 #29
0
 public static ProductActionStatus UpdateProduct(ProductInfo product, Dictionary<string, SKUItem> skus, Dictionary<int, IList<int>> attrs, IList<int> tagIds,string wid)
 {
     if (product == null)
     {
         return ProductActionStatus.UnknowError;
     }
     Globals.EntityCoding(product, true);
     int decimalLength = SettingsManager.GetMasterSettings(true,wid).DecimalLength;
     if (product.MarketPrice.HasValue)
     {
         product.MarketPrice = new decimal?(Math.Round(product.MarketPrice.Value, decimalLength));
     }
     ProductActionStatus unknowError = ProductActionStatus.UnknowError;
     using (DbConnection connection = DatabaseFactory.CreateDatabase().CreateConnection())
     {
         connection.Open();
         DbTransaction dbTran = connection.BeginTransaction();
         try
         {
             ProductDao dao = new ProductDao();
             if (!dao.UpdateProduct(product, dbTran))
             {
                 dbTran.Rollback();
                 return ProductActionStatus.DuplicateSKU;
             }
             if (!dao.DeleteProductSKUS(product.ProductId, dbTran))
             {
                 dbTran.Rollback();
                 return ProductActionStatus.SKUError;
             }
             if (((skus != null) && (skus.Count > 0)) && !dao.AddProductSKUs(product.ProductId, skus, dbTran,wid))
             {
                 dbTran.Rollback();
                 return ProductActionStatus.SKUError;
             }
             if (!dao.AddProductAttributes(product.ProductId, attrs, dbTran))
             {
                 dbTran.Rollback();
                 return ProductActionStatus.AttributeError;
             }
             if (!new TagDao().DeleteProductTags(product.ProductId, dbTran))
             {
                 dbTran.Rollback();
                 return ProductActionStatus.ProductTagEroor;
             }
             if ((tagIds.Count > 0) && !new TagDao().AddProductTags(product.ProductId, tagIds, dbTran))
             {
                 dbTran.Rollback();
                 return ProductActionStatus.ProductTagEroor;
             }
             dbTran.Commit();
             unknowError = ProductActionStatus.Success;
         }
         catch (Exception)
         {
             dbTran.Rollback();
         }
         finally
         {
             connection.Close();
         }
     }
     if (unknowError == ProductActionStatus.Success)
     {
         EventLogs.WriteOperationLog(Privilege.EditProducts, string.Format(CultureInfo.InvariantCulture, "修改了编号为 “{0}” 的商品", new object[] { product.ProductId }));
     }
     return unknowError;
 }
예제 #30
0
        public JsonResult GetCartProducts()
        {
            ShoppingCartInfo cart           = new CartHelper().GetCart(base.CurrentUser.Id);
            IProductService  productService = this._iProductService;
            IShopService     shopService    = this._iShopService;
            IVShopService    vshopService   = this._iVShopService;
            decimal          discount       = 1.0M;

            if (base.CurrentUser != null)
            {
                discount = base.CurrentUser.MemberDiscount;
            }
            List <long>           list          = new List <long>();
            decimal               prodPrice     = 0.0M;
            List <FlashSalePrice> limitProducts = LimitTimeApplication.GetPriceByProducrIds((from e in cart.Items select e.ProductId).ToList <long>());
            var source = from s in cart.Items.Where <ShoppingCartItem>(delegate(ShoppingCartItem d)
            {
                long?nullable;
                return(!d.ShopBranchId.HasValue || (((nullable = d.ShopBranchId).GetValueOrDefault() == 0L) && nullable.HasValue));
            }).Select(delegate(ShoppingCartItem item)
            {
                Func <FlashSalePrice, bool> predicate = null;
                ProductInfo product = productService.GetProduct(item.ProductId);
                ShopInfo shop       = shopService.GetShop(product.ShopId, false);
                SKUInfo sku         = null;
                string str          = "";
                string str2         = "";
                string str3         = "";
                string str4         = "";
                if (null != shop)
                {
                    string str5;
                    VShopInfo vShopByShopId = vshopService.GetVShopByShopId(shop.Id);
                    sku = productService.GetSku(item.SkuId);
                    if (sku == null)
                    {
                        return(null);
                    }
                    if (predicate == null)
                    {
                        predicate = e => e.ProductId == item.ProductId;
                    }
                    FlashSalePrice price = limitProducts.FirstOrDefault <FlashSalePrice>(predicate);
                    prodPrice            = sku.SalePrice;
                    if (price != null)
                    {
                        prodPrice = price.MinPrice;
                    }
                    else if (shop.IsSelf)
                    {
                        prodPrice = sku.SalePrice * discount;
                    }
                    ProductType type = TypeApplication.GetType(product.TypeId);
                    str  = ((type == null) || string.IsNullOrEmpty(type.ColorAlias)) ? SpecificationType.Color.ToDescription() : type.ColorAlias;
                    str2 = ((type == null) || string.IsNullOrEmpty(type.SizeAlias)) ? SpecificationType.Size.ToDescription() : type.SizeAlias;
                    str3 = ((type == null) || string.IsNullOrEmpty(type.VersionAlias)) ? SpecificationType.Version.ToDescription() : type.VersionAlias;
                    str4 = "";
                    if (!string.IsNullOrWhiteSpace(sku.Size))
                    {
                        str5 = str4;
                        str4 = str5 + str2 + ":" + sku.Size + "&nbsp;&nbsp;";
                    }
                    if (!string.IsNullOrWhiteSpace(sku.Color))
                    {
                        str5 = str4;
                        str4 = str5 + str + ":" + sku.Color + "&nbsp;&nbsp;";
                    }
                    if (!string.IsNullOrWhiteSpace(sku.Version))
                    {
                        str5 = str4;
                        str4 = str5 + str3 + ":" + sku.Version + "&nbsp;&nbsp;";
                    }
                    return(new
                    {
                        cartItemId = item.Id,
                        skuId = item.SkuId,
                        id = product.Id,
                        imgUrl = HimallIO.GetProductSizeImage(product.RelativePath, 1, 150),
                        name = product.ProductName,
                        price = prodPrice,
                        count = item.Quantity,
                        shopId = shop.Id,
                        vshopId = (vShopByShopId == null) ? 0L : vShopByShopId.Id,
                        shopName = shop.ShopName,
                        shopLogo = (vShopByShopId == null) ? "" : vShopByShopId.Logo,
                        status = ((product.AuditStatus == ProductInfo.ProductAuditStatus.Audited) && (product.SaleStatus == ProductInfo.ProductSaleStatus.OnSale)) ? 1 : 0,
                        Size = sku.Size,
                        Color = sku.Color,
                        Version = sku.Version,
                        ColorAlias = str,
                        SizeAlias = str2,
                        VersionAlias = str3,
                        skuDetails = str4,
                        AddTime = item.AddTime
                    });
                }
                return(null);
            })
                         where s != null
                         orderby s.vshopId, s.AddTime descending
            select s;
            BranchCartHelper helper2  = new BranchCartHelper();
            long             memberId = 0L;

            if (base.CurrentUser != null)
            {
                memberId = base.CurrentUser.Id;
            }
            ShoppingCartInfo cartNoCache = helper2.GetCartNoCache(memberId, 0L);
            List <long>      list2       = (from x in
                                            (from x in cartNoCache.Items
                                             where x.ShopBranchId.HasValue
                                             select x.ShopBranchId.Value).ToList <long>()
                                            group x by x into x
                                            select x.First <long>()).ToList <long>();
            Dictionary <long, int> buyedCounts = null;

            if (memberId > 0L)
            {
                cart        = helper2.GetCart(memberId, 0L);
                buyedCounts = new Dictionary <long, int>();
                buyedCounts = OrderApplication.GetProductBuyCount(memberId, from x in cart.Items select x.ProductId);
            }
            List <object> list3 = new List <object>();

            using (List <long> .Enumerator enumerator = list2.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    Func <ShoppingCartItem, bool> func = null;
                    long shopBranchId = enumerator.Current;
                    prodPrice = 0.0M;
                    List <ShopBranchSkusInfo> shopBranchSkuList = this._iShopBranchService.GetSkusByIds(shopBranchId, from x in cartNoCache.Items select x.SkuId);
                    if (func == null)
                    {
                        func = delegate(ShoppingCartItem x)
                        {
                            long?nullable1 = x.ShopBranchId;
                            long num       = shopBranchId;
                            return((nullable1.GetValueOrDefault() == num) && nullable1.HasValue);
                        };
                    }
                    var enumerable2 = from s in cartNoCache.Items.Where <ShoppingCartItem>(func).Select(delegate(ShoppingCartItem item)
                    {
                        Func <ShopBranchSkusInfo, bool> predicate = null;
                        if (shopBranchId == 0x63L)
                        {
                        }
                        ShopBranchInfo shopBranchById = this._iShopBranchService.GetShopBranchById(shopBranchId);
                        ProductInfo product           = this._iProductService.GetProduct(item.ProductId);
                        ShopInfo shop = this._iShopService.GetShop(product.ShopId, false);
                        SKUInfo sku   = null;
                        if ((shop != null) && (shopBranchById != null))
                        {
                            VShopInfo vShopByShopId = this._iVShopService.GetVShopByShopId(shop.Id);
                            sku = this._iProductService.GetSku(item.SkuId);
                            if (sku == null)
                            {
                                return(null);
                            }
                            prodPrice = sku.SalePrice;
                            if (shop.IsSelf)
                            {
                                prodPrice = sku.SalePrice * discount;
                            }
                            if (predicate == null)
                            {
                                predicate = x => x.SkuId == item.SkuId;
                            }
                            ShopBranchSkusInfo info6 = shopBranchSkuList.FirstOrDefault <ShopBranchSkusInfo>(predicate);
                            long maxBuyCount         = (info6 == null) ? ((long)0) : ((long)info6.Stock);
                            if ((maxBuyCount > product.MaxBuyCount) && (product.MaxBuyCount > 0))
                            {
                                maxBuyCount = product.MaxBuyCount;
                            }
                            if (((product.MaxBuyCount > 0) && (buyedCounts != null)) && buyedCounts.ContainsKey(item.ProductId))
                            {
                                int num3     = buyedCounts[item.ProductId];
                                maxBuyCount -= num3;
                            }
                            return(new { cartItemId = item.Id, skuId = item.SkuId, id = product.Id, imgUrl = HimallIO.GetProductSizeImage(product.RelativePath, 1, 150), name = product.ProductName, price = prodPrice, count = item.Quantity, status = (info6 == null) ? 1 : ((info6.Status == ShopBranchSkuStatus.Normal) ? ((item.Quantity > maxBuyCount) ? 2 : 0) : 1), AddTime = item.AddTime, shopBranchId = shopBranchById.Id, shopBranchName = shopBranchById.ShopBranchName });
                        }
                        return(null);
                    })
                                      where s != null
                                      orderby s.AddTime descending
                                      select s;
                    list3.Add(enumerable2);
                }
            }
            var data = new
            {
                products       = source,
                amount         = Enumerable.Sum(source, item => item.price * (Decimal)item.count),
                totalCount     = Enumerable.Sum(source, item => item.count),
                shopBranchCart = list3
            };

            return(base.Json(data));
        }
예제 #31
0
        /// <summary>
        ///
        /// </summary>
        new public void Start()
        {
            getPreferences();
            long testStart = DateTime.Now.Ticks;
            long tStart    = DateTime.Now.Ticks;

            HomeDocument home = client.Get <HomeDocument>(RestHomeUri, null);

            if (home == null)
            {
                WriteOutput("\nUnable to get Rest Service at: " + RestHomeUri + " check to see if the service is available.");
                return;
            }
            WriteOutput("Took " + ((DateTime.Now.Ticks - testStart) / TimeSpan.TicksPerMillisecond) + "ms to get RestService");
            //Feed<Repository> repositories = home.GetRepositories<Repository>(new FeedGetOptions { Inline = true, Links = true });
            //Repository CurrentRepository = repositories.GetRepository(repositoryName);
            CurrentRepository = home.GetRepository <D2Repository>(repositoryName);
            ProductInfo productInfo = home.GetProductInfo();

            if (CurrentRepository == null)
            {
                throw new Exception("Unable to login to the CurrentRepository, please see server logs for more details.");
            }
            // Set our default folder and document types.
            CurrentRepository.DocumentType = "dm_document";
            CurrentRepository.FolderType   = "dm_folder";
            NameValueCollection restTests = ConfigurationManager.GetSection("resttests") as NameValueCollection;

            if (!(Boolean.Parse(restTests["CreateTempDocs"].ToString()) || Boolean.Parse(restTests["CreateTempDocs"].ToString())))
            {
                throw new System.Exception("One of the tests that create Documents is required for other tests to run. "
                                           + "You must enable either the CreateTempDocs test and/or the CreateTempDocs test in order to create "
                                           + "documents that can be used in subsequent tests.");
            }

            C2ViewDocument(@"C:\SamplesToImport", "09000001800d180f", true);

            //todo: return or not
            // return;

            MoveDocs = new List <DocumentTracker>();
            foreach (String key in restTests)
            {
                bool preCheckOk = true;
                // This test is not available in versions earlier than 7.2
                double restVersion = Double.Parse((productInfo.Properties.Major.Equals("NA") ? "7.2" : productInfo.Properties.Major));

                if (key.Equals("Search"))
                {
                    if (!(restVersion >= 7.2d))
                    {
                        preCheckOk = false;
                        Console.WriteLine("Documentum Rest Version 7.2 or higher is required to use Search, your version is: "
                                          + restVersion + " Skipping...");
                    }
                }

                // These features do not work on Mono yet, should be fine when .NetCore is released though
                if (key.Equals("ExportParent") || key.Equals("ExportListOfFiles"))
                {
                    if (Type.GetType("Mono.Runtime") != null)
                    {
                        preCheckOk = false;
                        Console.WriteLine("The zip libraries required for [" + key + " ] have failed under Mono, skipping this  test. If you "
                                          + "want to test for yourself, you will have to modify the source to allow it udner (UseCaseTests");
                    }
                }

                if (preCheckOk)
                {
                    if (Boolean.Parse(restTests[key].ToString()))
                    {
                        runTestByName(key);
                    }
                }
            }

            WriteOutput("#####################################");
            WriteOutput("COMPLETED TESTS IN: " + ((DateTime.Now.Ticks - testStart) / TimeSpan.TicksPerMillisecond) / 1000 / 60 + "minutes");
            WriteOutput("#####################################");
            System.Diagnostics.Process.Start(testDirectory);

            if (loggerForm != null)
            {
                while (loggerForm.Visible)
                {
                    Application.DoEvents();
                }
            }
        }
예제 #32
0
        private void btnAdd_Click(object sender, EventArgs e)
        {
            int     num;
            int     num2;
            int     num3;
            decimal num4;
            decimal num5;
            decimal num6;
            decimal?nullable;
            decimal?nullable2;
            int?    nullable3;
            decimal nullable4;

            if (this.ValidateConverts(out num4, out num5, out num6, out nullable,
                                      out nullable2, out num, out num2, out nullable3, out num3, out nullable4))
            {
                string text = this.editDescription.Text;
                text = base.DownRemotePic(text);


                ProductInfo target = new ProductInfo
                {
                    CategoryId  = this.categoryId,
                    ProductName = this.txtProductName.Text,
                    ProductCode = this.txtProductCode.Text,
                    //15.09.20
                    ProductSubName   = this.txtSubhead.Text,
                    ProductShortName = this.txtProductShortName.Text,
                    ProductBarCode   = this.txtProBarCode.Text,

                    LineId           = num3,
                    LowestSalePrice  = num5,
                    MarketPrice      = nullable2,
                    OriginalPrice    = nullable4,
                    ImageUrl1        = this.uploader1.UploadedImageUrl,
                    ImageUrl2        = this.uploader2.UploadedImageUrl,
                    ImageUrl3        = this.uploader3.UploadedImageUrl,
                    ImageUrl4        = this.uploader4.UploadedImageUrl,
                    ImageUrl5        = this.uploader5.UploadedImageUrl,
                    ThumbnailUrl40   = this.uploader1.ThumbnailUrl40,
                    ThumbnailUrl60   = this.uploader1.ThumbnailUrl60,
                    ThumbnailUrl100  = this.uploader1.ThumbnailUrl100,
                    ThumbnailUrl160  = this.uploader1.ThumbnailUrl160,
                    ThumbnailUrl180  = this.uploader1.ThumbnailUrl180,
                    ThumbnailUrl220  = this.uploader1.ThumbnailUrl220,
                    ThumbnailUrl310  = this.uploader1.ThumbnailUrl310,
                    ThumbnailUrl410  = this.uploader1.ThumbnailUrl410,
                    ShortDescription = this.txtShortDescription.Text,
                    Description      = (!string.IsNullOrEmpty(text) && (text.Length > 0)) ? text : null,

                    AddedDate        = DateTime.Now,
                    MainCategoryPath = ProductHelper.GetCategory(this.categoryId).Path + "|",
                };

                ProductSaleStatus onSale = ProductSaleStatus.OnStock;
                if (this.radInStock.Checked)
                {
                    onSale = ProductSaleStatus.OnStock;
                }
                if (this.radUnSales.Checked)
                {
                    onSale = ProductSaleStatus.UnSale;
                }

                target.SaleStatus = onSale;

                ValidationResults validateResults = ExhibFlat.Components.Validation.Validation.Validate <ProductInfo>(
                    target, new string[] { "AddProduct" });
                if (!validateResults.IsValid)
                {
                    this.ShowMsg(validateResults);
                }
                else
                {
                    switch (ProductHelper.AddProduct(target))
                    {
                    case ProductActionStatus.Success:
                        this.ShowMsg("添加商品成功", true);
                        base.Response.Redirect(
                            Globals.GetAdminAbsolutePath(
                                string.Format("/product/AddProductComplete.aspx?categoryId={0}&productId={1}",
                                              this.categoryId, target.ProductId)), true);
                        return;

                    case ProductActionStatus.AttributeError:
                        this.ShowMsg("添加商品失败,保存商品属性时出错", false);
                        return;

                    case ProductActionStatus.DuplicateName:
                        this.ShowMsg("添加商品失败,商品名称或商家编码不能重复", false);
                        return;

                    case ProductActionStatus.DuplicateSKU:
                        this.ShowMsg("添加商品失败,SKU编码不能重复", false);
                        return;

                    case ProductActionStatus.SKUError:
                        this.ShowMsg("添加商品失败,SKU编码不能重复", false);
                        return;

                    case ProductActionStatus.ProductTagEroor:
                        this.ShowMsg("添加商品失败,保存商品标签时出错", false);
                        return;
                    }
                    this.ShowMsg("添加商品失败,未知错误", false);
                }
            }
        }
예제 #33
0
        protected void btStart_Click(object sender, EventArgs e)
        {
            LoginInfo       user = (Session["UserInfo"] as LoginInfo) as LoginInfo;
            ProduceTrack    info = new ProduceTrack();
            ProduceTrackBLL bll  = null;

            try
            {
                UIBindHelper.BindModelByControls(this.Page, info);

                bll = BLLFactory.CreateBLL <ProduceTrackBLL>();
                info.PRODUCTIONID = this.PRODUCTIONID.Value;
                if (this.hiID.Value == "")
                {
                    info.PID              = Guid.NewGuid().ToString();
                    info.STATUS           = "0";
                    info.WPID             = this.hiGX.Value;
                    info.EQUID            = this.hiCB.Value;
                    info.WSID             = this.hiGW.Value;
                    info.FACTORYPID       = user.OrgaID;
                    info.WORKINGSTARTTIME = DateTime.Now;
                    //校验是否跳序
                    string result = new ProcessCheckBLL().CheckSkipProcess(info.BATCHNUMBER, info.PRODUCTIONID, info.WPID);
                    if (result != "")
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "myjs", "alert('" + result + "');", true);
                        return;
                    }

                    bll.Insert(info);
                    this.HiCREATEUSER.Value = info.CREATEUSER;
                    this.HiCREATETIME.Value = info.CREATETIME.ToString();
                }
                else
                {
                    info.PID = this.hiID.Value;
                    info.WORKINGSTARTTIME = DateTime.Now;
                    info.STATUS           = "0";
                    info.WPID             = this.hiGX.Value;
                    info.EQUID            = this.hiCB.Value;
                    info.WSID             = this.hiGW.Value;
                    info.CREATETIME       = DateTime.Parse(this.HiCREATETIME.Value);
                    info.CREATEUSER       = this.HiCREATEUSER.Value;
                    bll.Update(info);
                }
                BindData(info.PID);
                //获取产品信息
                if (string.IsNullOrEmpty(this.BatchNumber.SelectedValue) == false)
                {
                    ProducePlanBLL ppbll  = BLLFactory.CreateBLL <ProducePlanBLL>();
                    ProductInfo    result = ppbll.GetPNameByIDBatchNumber(this.BatchNumber.SelectedValue);
                    this.PRODUCTIONID.Value = result.PID;
                    this.PNAME.Text         = result.PNAME;
                }
                this.hiID.Value = info.PID;
                //ClientScript.RegisterStartupScript(this.GetType(), "myjs", "window.location.href='MaterialTrace.aspx';", true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #34
0
        public override Messages Action(object act)
        {
            Messages msg = new Messages();

            BenQGuru.eMES.Common.DomainDataProvider.SQLDomainDataProvider domainProvider = null;

            if (act == null)
            {
                return(msg);
            }

            DataCollect.Action.ActionEventArgs args;
            if (ObjectState == null)
            {
                args = new BenQGuru.eMES.DataCollect.Action.ActionEventArgs();
            }
            else
            {
                args = ObjectState as DataCollect.Action.ActionEventArgs;
            }

            string data = act.ToString().ToUpper().Trim();            //Errorcode

            //Laws Lu,2006/06/03	添加	获取已有连接
            if ((act as IDCTClient).DBConnection != null)
            {
                domainProvider = (act as IDCTClient).DBConnection as BenQGuru.eMES.Common.DomainDataProvider.SQLDomainDataProvider;
            }
            else
            {
                domainProvider = Common.DomainDataProvider.DomainDataProviderManager.DomainDataProvider()
                                 as BenQGuru.eMES.Common.DomainDataProvider.SQLDomainDataProvider;
                (act as IDCTClient).DBConnection = domainProvider;
            }


            if (string.Compare(data, BaseDCTDriver.FINERROR, true) != 0)           //结束的标志
            {
                msg = CheckData(data, domainProvider);

                if (msg.IsSuccess())
                {
                    if (errorCodesHT == null)
                    {
                        errorCodesHT = new Hashtable();
                    }

                    if (!errorCodesHT.ContainsKey(data))
                    {
                        errorCodesHT.Add(data, data);
                    }

                    base.Action(act);
                    ActionCollectOutlineNG actionCollectOutlineNG = this;

                    actionCollectOutlineNG.IsTopAction = false;
                    this.NextAction = actionCollectOutlineNG;
                    this.Status     = ActionStatus.PrepareData;
                    //Laws Lu,2006/07/11 write back error code
                    msg.Add(new UserControl.Message(MessageType.Success, data));

                    return(msg);
                }
            }

            if (msg.IsSuccess())
            {
                //检查序列号

                ActionOnLineHelper _helper = new ActionOnLineHelper(domainProvider);

                msg = _helper.GetIDInfo(args.RunningCard);

                if (msg.IsSuccess())
                {
                    ProductInfo product = (ProductInfo)msg.GetData().Values[0];

                    TSModelFacade tsmodelFacade = new TSModelFacade(domainProvider);

                    if (errorCodesHT == null)
                    {
                        msg.Add(new UserControl.Message(UserControl.MessageType.Error, "$ErrorCode_Not_Exist"));
                    }

                    if (msg.IsSuccess())
                    {
                        string[] errorcs = new string[errorCodesHT.Count];
                        int      i       = 0;
                        foreach (DictionaryEntry dic in errorCodesHT)
                        {
                            errorcs[i] = dic.Key.ToString();
                            i++;
                        }
                        //Laws Lu,2006/06/22 modify fix the bug that system alert object not set an instance when the product.LastSimulation is null
                        if (product.LastSimulation == null)
                        {
                            msg.Add(new UserControl.Message(UserControl.MessageType.Error, "$NoSimulation"));
                        }
                        object[] errorcodes = null;
                        if (msg.IsSuccess())
                        {
                            errorcodes = tsmodelFacade.QueryECG2ECByECAndModelCode(errorcs, product.LastSimulation.ModelCode);

                            if (errorcodes == null || errorcodes.Length == 0)
                            {
                                msg.Add(new UserControl.Message(UserControl.MessageType.Error, "$ErrorCode_Not_BelongTo_ModelCode"));
                            }
                        }

                        object[] oplist = null;
                        if (msg.IsSuccess())
                        {
                            oplist = GetOutLineOP(domainProvider, (act as IDCTClient).ResourceCode);

                            if (oplist == null || oplist.Length == 0)
                            {
                                msg.Add(new UserControl.Message(MessageType.Error, "$CSError_Res_Cannot_Collect_OUtlineGood"));
                            }
                        }

                        string opcode = string.Empty;
                        if (msg.IsSuccess())
                        {
                            opcode = (oplist[0] as Operation).OPCode;
                            if (CheckOutlineOPInRoute(domainProvider, product.LastSimulation.RouteCode, opcode))
                            {
                                msg.Add(new UserControl.Message(MessageType.Error, "$CS_OutLineOP_In_ThisRoute"));
                            }
                        }

                        if (msg.IsSuccess())
                        {
                            if (IsLastOP(domainProvider, product.LastSimulation.MOCode, product.LastSimulation.RouteCode, product.LastSimulation.OPCode))
                            {
                                msg.Add(new UserControl.Message(MessageType.Error, "$CS_Op_IsLast_OutLineOP_Cannot_Collect"));
                            }
                        }

                        if (msg.IsSuccess())
                        {
                            IAction dataCollectModule
                                = new BenQGuru.eMES.DataCollect.Action.ActionFactory(domainProvider).CreateAction(ActionType.DataCollectAction_OutLineNG);

                            domainProvider.BeginTransaction();
                            try
                            {
                                IDCTClient client = act as IDCTClient;

                                msg.AddMessages((dataCollectModule).Execute(new OutLineActionEventArgs(
                                                                                ActionType.DataCollectAction_OutLineNG,
                                                                                args.RunningCard,
                                                                                client.LoginedUser,
                                                                                client.ResourceCode,
                                                                                product,
                                                                                opcode,
                                                                                errorcodes,
                                                                                "")));

                                if (msg.IsSuccess())
                                {
                                    domainProvider.CommitTransaction();
                                    msg.Add(new UserControl.Message(MessageType.Success, string.Format("$CS_NGSUCCESS")));

                                    //msg.Add( new UserControl.Message(MessageType.Succes ,string.Format("$CS_NGSUCCESS,$CS_Param_ID: {0}", args.RunningCard)));
                                }
                                else
                                {
                                    domainProvider.RollbackTransaction();
                                }
                            }
                            catch (Exception ex)
                            {
                                domainProvider.RollbackTransaction();

                                msg.Add(new UserControl.Message(ex));
                            }
                            finally
                            {
                                ((BenQGuru.eMES.Common.DomainDataProvider.SQLDomainDataProvider)domainProvider).PersistBroker.CloseConnection();
                            }
                        }
                    }
                }
            }

            if ((act as IDCTClient).CachedAction is ActionCollectOutlineNG)
            {
                if (this.Status == BenQGuru.eMES.Common.DCT.Core.ActionStatus.Working)
                {
                    this.ObjectState = null;
                    if (this.errorCodesHT != null)
                    {
                        this.errorCodesHT.Clear();
                    }
                }

                this.Status = BenQGuru.eMES.Common.DCT.Core.ActionStatus.PrepareData;


                (act as IDCTClient).CachedAction = this;
            }

            base.Action(act);

            ActionRCard actRcard = new ActionRCard();

            this.NextAction = actRcard;


            return(msg);
        }
예제 #35
0
        internal DeviceIdentity(IotHubConnectionString iotHubConnectionString, AmqpTransportSettings amqpTransportSettings, ProductInfo productInfo, ClientOptions options)
        {
            IotHubConnectionString = iotHubConnectionString;
            AmqpTransportSettings  = amqpTransportSettings;
            ProductInfo            = productInfo;
            Options = options;

            if (amqpTransportSettings.ClientCertificate == null)
            {
                Audience = CreateAudience(IotHubConnectionString);
                if (iotHubConnectionString.SharedAccessKeyName == null)
                {
                    AuthenticationModel = AuthenticationModel.SasIndividual;
                }
                else
                {
                    AuthenticationModel = AuthenticationModel.SasGrouped;
                }
            }
            else
            {
                AuthenticationModel = AuthenticationModel.X509;
            }
        }
예제 #36
0
 private void SetSql(string value) => Sql = value.Replace(ProductInfo.GetVersion(), "7.0.0-test");
        public override long CreateTransaction(long userId, decimal total, long productId, string description, ProductInfo[] products)
        {
            int totalcredits = 0;
            long res = 0;
            bool subscription = false;
            CultureInfo culture = HttpContext.Current.Session["culture"] as CultureInfo ?? new CultureInfo("nl-NL");

            List<decimal> prices = new List<decimal>();
            foreach (ProductInfo product in products)
            {
                totalcredits += product.Credits;
                if (!string.IsNullOrEmpty(product.Extra) && product.Extra.ToLower().StartsWith("subscription"))
                    subscription = true;

                ProductPriceInfoList ppil = GetProductPrices(product.ProductId, culture.ToString());
                if (ppil != null && ppil.Count > 0)
                {
                    prices.Add(ppil[0].Price);
                }
                else
                {
                    // Check whether an alternative price is given in the "Extra" field
                    decimal price = 0m;
                    string[] parts = product.Extra.Split('\x01');
                    if (parts.Length > 0)
                    {
                        decimal tmp;
                        if (decimal.TryParse(parts[parts.Length - 1], out tmp))
                            price = tmp;

                        if (product.Extra == "subscription" && tmp == 0)
                            price = 1;
                    }
                    prices.Add(price);
                }
            }

            using (MySqlConnection conn = new MySqlConnection(GetConnectionString()))
            {
                using (MySqlCommand cmd = new MySqlCommand(QRY_CREATE_TRANSACTION, conn))
                {
                    string statCode = string.Empty;
                    if (subscription)
                        statCode = string.Format("SUB(credits:{0})", totalcredits);
                    cmd.Parameters.Add("@user_id", MySqlDbType.Int64).Value = userId;
                    cmd.Parameters.Add("@amount", MySqlDbType.Decimal).Value = total;
                    cmd.Parameters.Add("@statuscode", MySqlDbType.VarChar, 100).Value = statCode;
                    cmd.Parameters.Add("@description", MySqlDbType.VarChar, 100).Value = description;
                    cmd.Parameters.Add("@product_id", MySqlDbType.Int64).Value = productId;

                    try
                    {
                        conn.Open();
                        cmd.ExecuteNonQuery();
                        res = GetLastInsertId(conn);

                        int i = 0;
                        foreach (ProductInfo product in products)
                        {
                            cmd.CommandText = QRY_INSERT_TRANSACTION_LINE;
                            cmd.Parameters.Clear();
                            cmd.Parameters.Add("@transaction_id", MySqlDbType.Int64).Value = res;
                            cmd.Parameters.Add("@item_line", MySqlDbType.Int32).Value = 1;
                            cmd.Parameters.Add("@description", MySqlDbType.VarChar, 100).Value = product.Name;
                            cmd.Parameters.Add("@quantity", MySqlDbType.Int32).Value = product.ProductId == 0 ? product.Credits : 1;
                            cmd.Parameters.Add("@price", MySqlDbType.Decimal).Value = prices[i];
                            cmd.Parameters.Add("@vat_percentage", MySqlDbType.Decimal).Value = 21m;
                            cmd.Parameters.Add("@vat_amount", MySqlDbType.Decimal).Value = 0;

                            cmd.ExecuteNonQuery();
                            ++i;
                        }
                    }
                    catch (MySqlException ex)
                    {
                        Logger.Instance.Write(LogLevel.Error, ex, "CreateTransaction<MySqlException>");
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.Write(LogLevel.Error, ex, "CreateTransaction<Exception>");
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            return res;
        }
예제 #38
0
	void _IALUGenerator.SaveProduct(ref ProductInfo ProdInfo)
	{
		IALUGenerator_SaveProduct(ProdInfo);
	}
        public override TransactionResult UpdateTransaction(string orderId, string result, string status, string statusCode,
                                               string merchant, string paymentid, string reference, string transid,
                                               string paymentmethod, decimal amount, ProductInfo productInfo,
                                               string currencyIso, string countryIso2)
        {
            long userId = -1;
            ProductPriceInfo ppi = null;
            string oldStatusCode = string.Empty;
            using (MySqlConnection conn = new MySqlConnection(GetConnectionString()))
            {
                using (MySqlCommand cmd = new MySqlCommand(QRY_GET_PRODUCTPRICE_BY_PRODUCT_ID_CURRENCY_COUNTRY_WILD, conn))
                {
                    cmd.Parameters.Add("@product_id", MySqlDbType.Int64).Value = productInfo.ProductId;
                    cmd.Parameters.Add("@iso_currency", MySqlDbType.VarChar, 10).Value = currencyIso;
                    cmd.Parameters.Add("@iso2_country", MySqlDbType.VarChar, 2).Value = countryIso2;

                    try
                    {
                        conn.Open();
                        using (MySqlDataReader rdr = cmd.ExecuteReader())
                        {
                            if (rdr.HasRows)
                            {
                                while (rdr.Read())
                                {
                                    long productPriceId = rdr.GetInt64(0);
                                    decimal price = rdr.GetDecimal(1);
                                    string isoCurrency = rdr.GetString(2);
                                    string iso2Country = rdr.GetString(3);
                                    ppi = new ProductPriceInfo(productPriceId, price, isoCurrency, iso2Country,
                                                               productInfo.ProductId);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.Write(
                            LogLevel.Error, ex,
                            "UpdateTransaction<Exception:Get ProductPriceInfo>");
                        conn.Close();
                        return TransactionResult.NotFound;
                    }
                }

                long transactionId;
                if (!long.TryParse(orderId, out transactionId))
                    transactionId = 0;
                using (MySqlCommand cmd = new MySqlCommand(QRY_GET_TRANSACTION_STATUS, conn))
                {
                    cmd.Parameters.Add("@transaction_id", MySqlDbType.Int64).Value = transactionId;
                    try
                    {
                        object obj = cmd.ExecuteScalar();
                        if (obj != null)
                        {
                            string currStatus = Convert.ToString(obj);
                            if (currStatus.ToLower() == "ok" || currStatus.ToLower() == "err")
                                return TransactionResult.AlreadyCompleted;
                        }
                        else
                        {
                            return TransactionResult.NotFound;
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.Write(LogLevel.Error, ex, "UpdateTransaction<exception>[check status]");
                        return TransactionResult.NotFound;
                    }
                }

                using (MySqlCommand cmd = new MySqlCommand(QRY_GET_TRANSACTION_STATUSCODE, conn))
                {
                    cmd.Parameters.Add("@transaction_id", MySqlDbType.Int64).Value = transactionId;
                    try
                    {
                        object obj = cmd.ExecuteScalar();
                        if (obj != null)
                        {
                            oldStatusCode = Convert.ToString(obj);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.Write(LogLevel.Error, ex, "UpdateTransaction<exception>[check status]");
                        return TransactionResult.NotFound;
                    }
                }

                using (MySqlCommand cmd = new MySqlCommand(QRY_UPDATE_TRANSACTION, conn))
                {
                    //cmd.Parameters.Add("@result", MySqlDbType.VarChar, 100).Value			= result;
                    cmd.Parameters.Add("@status", MySqlDbType.VarChar, 100).Value = status;
                    cmd.Parameters.Add("@statuscode", MySqlDbType.VarChar, 100).Value = statusCode;
                    cmd.Parameters.Add("@merchant", MySqlDbType.VarChar, 50).Value = merchant;
                    cmd.Parameters.Add("@paymentid", MySqlDbType.VarChar, 100).Value = paymentid;
                    cmd.Parameters.Add("@transid", MySqlDbType.VarChar, 100).Value = transid;
                    cmd.Parameters.Add("@paymentmethod", MySqlDbType.VarChar, 100).Value = paymentmethod;
                    cmd.Parameters.Add("@transaction_id", MySqlDbType.Int64).Value = transactionId;

                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (MySqlException ex)
                    {
                        Logger.Instance.Write(LogLevel.Error, ex, "UpdateTransaction<MySqlException>");
                        return TransactionResult.NotFound;
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.Write(LogLevel.Error, ex, "UpdateTransaction<Exception>");
                        return TransactionResult.NotFound;
                    }
                }

                if (status == "OK" && paymentmethod.ToUpper() != "COUPON")	// Valid, completed transaction
                {
                    Util.CreateInvoice(Util.UserId, status, transid, paymentmethod, productInfo, ppi);
                    if (string.Compare(productInfo.Extra, "subscription", true) == 0)
                    {
                        // Customer bought a subscription, check whether we have to update
                        // his management rights.
                        using (MySqlCommand cmd = new MySqlCommand(QRY_GET_TRANSACTION_USERID, conn))
                        {
                            cmd.Parameters.Add("@transaction_id", MySqlDbType.Int64).Value = transactionId;
                            try
                            {
                                object obj = cmd.ExecuteScalar();
                                if (obj != null)
                                    userId = (long)obj;
                            }
                            catch (Exception ex)
                            {
                                Logger.Instance.Write(LogLevel.Error, ex, "UpdateTransaction<exception>[check user id]");
                            }
                        }
                        if (!string.IsNullOrEmpty(oldStatusCode))
                        {
                            if (oldStatusCode.StartsWith("SUB"))
                            {
                                int credits;
                                oldStatusCode = oldStatusCode.Substring(3);
                                oldStatusCode = oldStatusCode.Trim('(', ')');
                                string[] parts = oldStatusCode.Split(':');
                                if (parts.Length > 1)
                                {
                                    if (int.TryParse(parts[1], out credits))
                                        productInfo.Credits = credits;
                                }
                            }
                        }
                    }
                }
            }
            if (userId > -1)
                RegisterUserRights(userId, 100, 100);

            return TransactionResult.Success;
        }
예제 #40
0
	//===============================================================================
	// Name: Function IALUGenerator_GenKey
	// Input:
	//   ByRef Lic As ActiveLock3.ProductLicense - Product license
	//   ByVal InstCode As String - Installation Code sent by the user
	//   ByVal RegisteredLevel As String - Registration Level for the license. Default is "0"
	// Output:
	//   String - Liberation key for the license
	// Purpose: Given the Installation Code, generates an Activelock license liberation key.
	// Remarks: None
	//===============================================================================
	private string IALUGenerator_GenKey(ref ActiveLock3_6NET.ProductLicense Lic, string InstCode, [System.Runtime.InteropServices.OptionalAttribute, System.Runtime.InteropServices.DefaultParameterValueAttribute("0")]  // ERROR: Optional parameters aren't supported in C#
string RegisteredLevel)
	{
		// Take request code and decrypt it.
		string strReq = null;

		// 05.13.05 - ialkan Modified to merge DLLs into one
		strReq = modBase64.Base64_Decode(ref InstCode);

		// strReq now contains the {LockCode + vbLf + User} string
		string strLock = string.Empty;
		string strUser = string.Empty;
		GetLockAndUserFromInstallCode(strReq, ref strLock, ref strUser);

		Lic.Licensee = strUser;
		// registration date
		string strRegDate = null;
		// registered level
		Lic.RegisteredLevel = RegisteredLevel;
		strRegDate = Lic.RegisteredDate;

		string strEncrypted = null;
		// @todo Rethink this bit about encrypting the dates.
		// We need to keep in mind that the app does not have access to the private key, so and any decryption that requires private key
		// would not be possible.
		// Perhaps instead of encrypting, we could do MD5 hash of (regdate+lockcode)?
		//ActiveLockEventSink_ValidateValue strRegDate, strEncrypted
		// hash it
		//strEncrypted = ActiveLock3.MD5Hash(strEncrypted)
		strEncrypted = strRegDate;

		// get software codes
		ProductInfo ProdInfo = null;
		ProdInfo = IALUGenerator_RetrieveProduct(Lic.ProductName, Lic.ProductVer);
		Lic.ProductKey = ProdInfo.VCode;

		string strLic = null;
		strLic = Lic.ToString_Renamed() + Constants.vbLf + strLock;
		System.Diagnostics.Debug.WriteLine("strLic: " + Constants.vbCrLf + strLic);

		if (modALUGEN.strLeft(ProdInfo.VCode, 3) != "RSA") {
			// sign it
			string strSig = null;
			strSig = new string(Strings.Chr(0), 1024);
			// 05.13.05 - ialkan Modified to merge DLLs into one. Moved RSASign into a module
			strSig = modActiveLock.RSASign(ProdInfo.VCode, ProdInfo.GCode, strLic);

			// Create liberation key.  This will be a base-64 encoded string of the whole license.
			string strLicKey = null;
			// 05.13.05 - ialkan Modified to merge DLLs into one
			strLicKey = modBase64.Base64_Encode(ref strSig);
			// update Lic with license key
			Lic.LicenseKey = strLicKey;
			// Print some info for debugging purposes
			System.Diagnostics.Debug.WriteLine("VCode: " + ProdInfo.VCode);
			System.Diagnostics.Debug.WriteLine("Lic: " + strLic);
			System.Diagnostics.Debug.WriteLine("Lic hash: " + modMD5.Hash(ref strLic));
			System.Diagnostics.Debug.WriteLine("LicKey: " + strLicKey);
			System.Diagnostics.Debug.WriteLine("Sig: " + strSig);
			System.Diagnostics.Debug.WriteLine("Verify: " + modActiveLock.RSAVerify(ProdInfo.VCode, strLic, modBase64.Base64_Decode(ref strLicKey)));
			System.Diagnostics.Debug.WriteLine("====================================================");
		}

		else {
			try {
				System.Security.Cryptography.RSACryptoServiceProvider rsaCSP = new System.Security.Cryptography.RSACryptoServiceProvider();
				string strPublicBlob = null;
				string strPrivateBlob = null;

				strPublicBlob = ProdInfo.VCode;
				strPrivateBlob = ProdInfo.GCode;

				if (modALUGEN.strLeft(ProdInfo.GCode, 6) == "RSA512") {
					strPrivateBlob = modALUGEN.strRight(ProdInfo.GCode, Strings.Len(ProdInfo.GCode) - 6);
				}
				else {
					strPrivateBlob = modALUGEN.strRight(ProdInfo.GCode, Strings.Len(ProdInfo.GCode) - 7);
				}
				// import private key params into instance of RSACryptoServiceProvider
				rsaCSP.FromXmlString(strPrivateBlob);
				RSAParameters rsaPrivateParams = default(RSAParameters);
				//stores private key
				rsaPrivateParams = rsaCSP.ExportParameters(true);
				rsaCSP.ImportParameters(rsaPrivateParams);

				byte[] userData = Encoding.UTF8.GetBytes(strLic);

				AsymmetricSignatureFormatter asf = new RSAPKCS1SignatureFormatter(rsaCSP);
				HashAlgorithm algorithm = new SHA1Managed();
				asf.SetHashAlgorithm(algorithm.ToString());
				byte[] myhashedData = null;
				// a byte array to store hash value
				string myhashedDataString = null;
				myhashedData = algorithm.ComputeHash(userData);
				myhashedDataString = BitConverter.ToString(myhashedData).Replace("-", string.Empty);
				byte[] mysignature = null;
				// holds signatures
				mysignature = asf.CreateSignature(algorithm);
				string mySignatureBlock = null;
				mySignatureBlock = Convert.ToBase64String(mysignature);
				Lic.LicenseKey = mySignatureBlock;
			}
			catch (Exception ex) {
				modActiveLock.Set_Locale(modActiveLock.regionalSymbol);
				Err().Raise(AlugenGlobals.alugenErrCodeConstants.alugenProdInvalid, modTrial.ACTIVELOCKSTRING, ex.Message);
			}

		}

		// Serialize it into a formatted string
		string strLibKey = string.Empty;
		Lic.Save(ref strLibKey);
		return strLibKey;
	}
예제 #41
0
 private bool Parse()
 {
     String jsonSliderData = ParseByPattern(_html, PATTERN_SLIDER_DATA);
     if (!jsonSliderData.Equals(""))
     {
         try
         {
             // тарифы
             dynamic sliderData = JsonConvert.DeserializeObject(jsonSliderData);
             IEnumerable<JProperty> properties = sliderData.Properties();
             String[] productIds = properties.Select(p => p.Name).ToArray();
             _productInfos = new ProductInfo[productIds.Length];
             for (int i = 0; i < productIds.Length; ++i)
             {
                 String productId = productIds[i];
                 dynamic productData = sliderData[productId];
                 var product = new ProductInfo();
                 product.productId = productId;
                 product.currentRateCode = productData["offerCode"];
                 JArray steps = productData["steps"];
                 product.rateInfos = new RateInfo[steps.Count];
                 for (int j = 0; j < steps.Count; ++j)
                 {
                     var rate = new RateInfo();
                     dynamic step = steps[j];
                     rate.code = step["code"];
                     rate.amountNumber = step["amountNumber"];
                     rate.amountString = NameImprover.ImproveAmountString(step["amountString"].ToString());
                     rate.remainNumber = step["remainNumber"];
                     rate.remainString = step["remainString"];
                     rate.speedNumber = NameImprover.ImproveSpeedNumber(step["speedNumber"].ToString());
                     rate.speedString = NameImprover.ImproveSpeedString(step["speedString"].ToString());
                     product.rateInfos[j] = rate;
                 }
                 _productInfos[i] = product;
             }
             // устройства
             String[] datas = _html.Split(new string[] { PATTERN_DEVICE }, StringSplitOptions.None);
             for (int i = 0; i < datas.Length; ++i)
             {
                 String productId = ParseByPattern(datas[i], PATTERN_PRODUCT_ID);
                 int index = Array.IndexOf(productIds, productId);
                 if (index != -1)
                 {
                     _productInfos[index].deviceId = ParseByPattern(datas[i], PATTERN_DEVICE_ID);
                     _productInfos[index].deviceName = ParseByPattern(datas[i], PATTERN_DEVICE_NAME);
                     _productInfos[index].days = ParseByPattern(datas[i], PATTERN_DAYS);
                 }
             }
             // баланс
             _balance = ParseByPattern(_html, PATTERN_MONEY);
             _balance = NameImprover.ImproveMoneyString(_balance);
             return true;
         }
         catch (Exception e)
         {
             Console.WriteLine(e.Message);
             _productInfos = null;
             return false;
         }
     }
     return false;
 }
예제 #42
0
 public void AddProductToSalesOrder(ProductInfo productInfo) => CurrentSalesOrder.AddProduct(productInfo, 1);
예제 #43
0
        static public ProductInfo GetProductInfo(SqlConnection connect,
                                                                           Log log,
                                                                            string prodID)
        {
            ProductInfo Prod = null;

            SqlCommand dbCmd = connect.CreateCommand();
            dbCmd.CommandType = CommandType.Text;
            dbCmd.CommandText = @"select a.CUSTSN, 
                                                                   a.Model, 
                                                                   a.MAC, 
                                                                   isnull(b.Value,'') as CNRS , 
                                                                   isnull(c.Value,'') as  OP,                                                                    
                                                                   a.MO
                                                             from Product a
                                                             left join ModelInfo b on a.Model =b.Model  and b.Name='CNRS'
                                                             left join ModelInfo c on a.Model =c.Model  and c.Name='PO'                                                               
                                                             where ProductID=@ProductID";
            SQLHelper.createInputSqlParameter(dbCmd, "@ProductID", 15, prodID);


            log.write(LogType.Info, 0, "SQL", "GetProductInfo", dbCmd.CommandText);
            log.write(LogType.Info, 0, "SQL", "@ProductID", prodID);
           

            SqlDataReader sdr = dbCmd.ExecuteReader();
            while (sdr.Read())
            {
                Prod = new ProductInfo();
                Prod.ProductID = prodID;
                Prod.CUSTSN = sdr.GetString(0).Trim();
                Prod.Model = sdr.GetString(1).Trim();
                Prod.MAC =sdr.GetString(2).Trim();
                Prod.IsCNRS = sdr.GetString(3).Trim();
                Prod.IsPO = sdr.GetString(4).Trim();              
                Prod.MOId=  sdr.GetString(5).Trim();
                Prod.PO = "";

            }
            sdr.Close();
            return Prod;
        }
예제 #44
0
 public void ReduceProductFromSalesOrder(ProductInfo productInfo) => CurrentSalesOrder.DecreaseProduct(productInfo, 1);
예제 #45
0
        static public List<Delivery> GetAvailableDeliveryByCustPo(SqlConnection connect,
                                                                                                Log log,
                                                                                                ProductInfo prodInfo,
                                                                                                 int shipDateoffset)
        {
            List<Delivery> ret = new List<Delivery>();

            DateTime now = DateTime.Now;
            DateTime shipDate = new DateTime(now.Year, now.Month, now.Day);  //now.AddDays(shipDateoffset);
            DateTime shipDateEnd = shipDate.AddDays(shipDateoffset);

            SqlCommand dbCmd = connect.CreateCommand();
            dbCmd.CommandType = CommandType.Text;
            //            dbCmd.CommandText = @"select DeliveryNo, PoNo,Qty from Delivery 
            //                                                          where Model=@model and 
            //                                                                     ShipDate between @ShipDate and @ShipDateEnd and
            //                                                                     Qty> 0 and
            //                                                                     Status ='00'  
            //                                                         order by ShipDate";
            dbCmd.CommandText = @"select a.DeliveryNo, b.FactoryPO, a.Qty , a.PoNo 
                                                          from Delivery a,
                                                               DeliveryInfo c,  
                                                                SpecialOrder b 
                                                          where a.DeliveryNo =c.DeliveryNo and
                                                                c.InfoType='CustPo'        and   
                                                                c.InfoValue= b.FactoryPO and
                                                                b.Status in ('Created','Active') and
                                                                a.Model=@model and 
                                                                a.ShipDate between @ShipDate and @ShipDateEnd and
                                                                   a.Qty> 0 and
                                                                  a.Status ='00'  
                                                         order by ShipDate";

            SQLHelper.createInputSqlParameter(dbCmd, "@model", 15, prodInfo.Model);
            SQLHelper.createInputSqlParameter(dbCmd, "@ShipDate", shipDate);
            SQLHelper.createInputSqlParameter(dbCmd, "@ShipDateEnd", shipDateEnd);


            log.write(LogType.Info, 0, "SQL", "GetAvailableDelivery", dbCmd.CommandText);
            log.write(LogType.Info, 0, "SQL", "@model", prodInfo.Model);
            log.write(LogType.Info, 0, "SQL", "@ShipDate", shipDate.ToString());
            log.write(LogType.Info, 0, "SQL", "@ShipDateEnd", shipDateEnd.ToString());



            SqlDataReader sdr = dbCmd.ExecuteReader();
            while (sdr.Read())
            {
                Delivery delivery = new Delivery();
                delivery.DeliveryNo = sdr.GetString(0).Trim();
                delivery.PO = sdr.GetString(1).Trim();
                delivery.Qty = sdr.GetInt32(2);
                delivery.CustPo = delivery.PO;
                delivery.HpPo = sdr.GetString(3).Trim();
                delivery.isCustPo = true;
                ret.Add(delivery);
            }
            sdr.Close();
            return ret;
        }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        ProductInfo info = new ProductInfo();
        info.CategoryID = Convert.ToInt32(this.ddlCategory.SelectedValue.ToString());
        info.HatName = this.txtName.Text.Trim();
        info.Quantity = Convert.ToInt32(this.txtQuantity.Text.Trim());
        info.ColourID = Convert.ToInt32(this.ddlColour.SelectedValue.ToString());
        info.SupplierID = Convert.ToInt32(this.ddlSupplier.SelectedValue.ToString());
        info.Price = decimal.Parse(this.txtPrice.Text.Trim());
        info.Path = ImageMapPhoto.ImageUrl;
        info.Description = this.txtDesc.Text.Trim();
        info.LoadDate = DateTime.Now;
        info.IsHot = false;
        AddProductInfo(info);
        ImageMapPhoto.ImageUrl = info.Path;

    }
예제 #47
0
        static public bool AssignPO(SqlConnection connect,
                                                      Log log,
                                                      AppConfig config,
                                                      ProductInfo prodInfo, 
                                                      CDSIPO poInfo)
        {

            bool selectedPo = false;

            List<Delivery> poList = GetAvailableDelivery(connect,
                                                                                     log,
                                                                                     prodInfo,
                                                                                      config.ShipDateOffSetDay);
            if (poList.Count == 0)
            {
                poList = GetAvailableDeliveryByCustPo(connect,
                                                                                                     log,
                                                                                                     prodInfo,
                                                                                                      config.ShipDateOffSetDay);
            }

            if (poList.Count == 0)    return selectedPo;

            int availableQty = 0;

            foreach (Delivery po in poList)
            {
                availableQty = po.Qty - GetAssignPOQty(connect, log, po.DeliveryNo, po.PO);
                if (availableQty > 0)
                {                    
                    poInfo.PO= po.PO;
                    poInfo.DeliveryNo = po.DeliveryNo;
                    poInfo.DeliveryQty = po.Qty;
                    poInfo.RemainQty = availableQty;
                    poInfo.CustPo = po.CustPo;
                    poInfo.HpPo = po.HpPo;
                    poInfo.isCustPo = po.isCustPo;
                    selectedPo = true;
                    break;
                }
            }

            return selectedPo;
        }
 public void ProductDetailsFill(int inRowIndex, string strFillMode)
 {
     try
     {
         ProductInfo infoProduct = new ProductInfo();
         BatchBll BllBatch = new BatchBll();
         StockPostingBll BllStockPosting = new StockPostingBll();
         //StockPostingSP spStockPosting = new StockPostingSP();
         string strPrdCode = string.Empty;
         string strProductName = string.Empty;
         if (strFillMode == "ProductCode")
         {
             if (dgvProduct.Rows[inRowIndex].Cells["dgvtxtProductCode"].Value != null && dgvProduct.Rows[inRowIndex].Cells["dgvtxtProductCode"].Value as string != string.Empty)
             {
                 strPrdCode = dgvProduct.Rows[inRowIndex].Cells["dgvtxtProductCode"].Value.ToString();
             }
             infoProduct = new ProductCreationBll().ProductViewByCode(strPrdCode);
         }
         if (strFillMode == "ProductName")
         {
             if (dgvProduct.Rows[inRowIndex].Cells["dgvtxtProductName"].Value != null && dgvProduct.Rows[inRowIndex].Cells["dgvtxtProductName"].Value.ToString() != string.Empty)
             {
                 strProductName = dgvProduct.Rows[inRowIndex].Cells["dgvtxtProductName"].Value.ToString();
             }
             infoProduct = new ProductCreationBll().ProductViewByName(strProductName);
         }
         if (infoProduct.ProductId != 0)
         {
             dgvProduct.Rows[inRowIndex].Cells["dgvtxtProductCode"].Value = infoProduct.ProductCode;
             dgvProduct.Rows[inRowIndex].Cells["dgvtxtProductName"].Value = infoProduct.ProductName;
             string strproductId = Convert.ToString(infoProduct.ProductId);
             dgvProduct.Rows[inRowIndex].Cells["dgvtxtProductId"].Value = infoProduct.ProductId;
             UnitComboFill1(Convert.ToDecimal(dgvProduct.CurrentRow.Cells["dgvtxtProductId"].Value), inRowIndex, dgvProduct.Rows[inRowIndex].Cells["dgvcmbUnit"].ColumnIndex);
             dgvProduct.Rows[inRowIndex].Cells["dgvcmbUnit"].Value = infoProduct.UnitId;
             BatchComboFill(Convert.ToDecimal(dgvProduct.CurrentRow.Cells["dgvtxtProductId"].Value), inRowIndex, dgvProduct.Rows[inRowIndex].Cells["dgvcmbBatch"].ColumnIndex);
             dgvProduct.Rows[inRowIndex].Cells["dgvcmbBatch"].Value = BllStockPosting.BatchViewByProductId(Convert.ToDecimal(dgvProduct.Rows[inRowIndex].Cells["dgvtxtProductId"].Value));
             string strBarcode = BllBatch.ProductBatchBarcodeViewByBatchId(Convert.ToDecimal(dgvProduct.Rows[inRowIndex].Cells["dgvcmbBatch"].Value.ToString()));
             dgvProduct.Rows[inRowIndex].Cells["dgvtxtBarcode"].Value = strBarcode;
             GridGodownComboFill(Convert.ToDecimal(dgvProduct.CurrentRow.Cells["dgvtxtProductId"].Value), inRowIndex, dgvProduct.Rows[inRowIndex].Cells["dgvcmbGodown"].ColumnIndex);
             dgvProduct.Rows[inRowIndex].Cells["dgvcmbGodown"].Value = infoProduct.GodownId;
             RackComboFill1(Convert.ToDecimal(dgvProduct.CurrentRow.Cells["dgvcmbGodown"].Value), inRowIndex, dgvProduct.Rows[inRowIndex].Cells["dgvcmbRack"].ColumnIndex);
             dgvProduct.Rows[inRowIndex].Cells["dgvcmbRack"].Value = infoProduct.RackId;
             UnitConvertionBll bllUnitConvertion = new UnitConvertionBll();
             List<DataTable> ListObj = new List<DataTable>();
             ListObj = bllUnitConvertion.UnitConversionIdAndConRateViewallByProductId(strproductId);
             foreach (DataRow drUnitByProduct in ListObj[0].Rows)
             {
                 if (dgvProduct.Rows[inRowIndex].Cells["dgvcmbUnit"].Value.ToString() == drUnitByProduct.ItemArray[0].ToString())
                 {
                     dgvProduct.Rows[inRowIndex].Cells["dgvtxtUnitConversionId"].Value = Convert.ToDecimal(drUnitByProduct.ItemArray[2].ToString());
                     dgvProduct.Rows[inRowIndex].Cells["dgvtxtConversionRate"].Value = Convert.ToDecimal(drUnitByProduct.ItemArray[3].ToString());
                 }
             }
             dgvProduct.Rows[inRowIndex].Cells["dgvtxtRate"].Value = Math.Round(infoProduct.SalesRate, PublicVariables._inNoOfDecimalPlaces);
             decCurrentConversionRate = Convert.ToDecimal(dgvProduct.Rows[inRowIndex].Cells["dgvtxtConversionRate"].Value.ToString());
             decCurrentRate = Convert.ToDecimal(dgvProduct.Rows[inRowIndex].Cells["dgvtxtRate"].Value.ToString());
             decimal decProductId = Convert.ToDecimal(dgvProduct.Rows[inRowIndex].Cells["dgvtxtProductId"].Value.ToString());
             decimal decBatchId = Convert.ToDecimal(dgvProduct.Rows[inRowIndex].Cells["dgvcmbBatch"].Value.ToString());
             getProductRate(inRowIndex, decProductId, decBatchId);
         }
         else
         {
             dgvProduct.Rows[inRowIndex].Cells["dgvtxtProductName"].Value = string.Empty;
             dgvProduct.Rows[inRowIndex].Cells["dgvtxtRate"].Value = string.Empty;
             dgvProduct.Rows[inRowIndex].Cells["dgvtxtProductCode"].Value = string.Empty;
             dgvProduct.Rows[inRowIndex].Cells["dgvtxtBarcode"].Value = string.Empty;
             dgvProduct.Rows[inRowIndex].Cells["dgvcmbGodown"].Value = string.Empty;
             dgvProduct.Rows[inRowIndex].Cells["dgvcmbRack"].Value = string.Empty;
             dgvProduct.Rows[inRowIndex].Cells["dgvcmbUnit"].Value = string.Empty;
             dgvProduct.Rows[inRowIndex].Cells["dgvcmbBatch"].Value = string.Empty;
             dgvProduct.Rows[inRowIndex].Cells["dgvtxtProductId"].Value = string.Empty;
             dgvProduct.Rows[inRowIndex].Cells["dgvtxtUnitConversionId"].Value = string.Empty;
             dgvProduct.Rows[inRowIndex].Cells["dgvtxtConversionRate"].Value = string.Empty;
             dgvProduct.Rows[inRowIndex].Cells["dgvtxtRate"].Value = string.Empty;
             dgvProduct.Rows[inRowIndex].Cells["dgvtxtAmount"].Value = string.Empty;
             dgvProduct.Rows[inRowIndex].Cells["dgvtxtQty"].Value = string.Empty;
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("DN47:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
 /// <summary>
 /// Function to call frmProductSearchPopup form to select and view Product created 
 /// </summary>
 /// <param name="frmProductSearchPopup"></param>
 /// <param name="decproductId"></param>
 /// <param name="decCurrentRowIndex"></param>
 public void CallFromProductSearchPopup(frmProductSearchPopup frmProductSearchPopup, decimal decproductId, decimal decCurrentRowIndex)
 {
     try
     {
         base.Show();
         this.frmProductSearchPopupObj = frmProductSearchPopup;
         List<DataTable> list = new List<DataTable>();
         UnitConvertionBll bllUnitConvertion = new UnitConvertionBll();
         ProductInfo infoProduct = new ProductInfo();
         BatchBll BllBatch = new BatchBll();
         infoProduct = new ProductCreationBll().ProductView(decproductId);
         dgvProduct.Rows.Add();
         dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Cells["dgvtxtProductCode"].Value = infoProduct.ProductCode;
         dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Cells["dgvtxtProductId"].Value = decproductId.ToString();
         dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Cells["dgvtxtProductName"].Value = infoProduct.ProductName;
         UnitComboFill1(decproductId, dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Index, dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Cells["dgvcmbUnit"].ColumnIndex);
         dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Cells["dgvcmbUnit"].Value = infoProduct.UnitId;
         GridGodownComboFill(decproductId, dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Index, dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Cells["dgvcmbGodown"].ColumnIndex);
         dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Cells["dgvcmbGodown"].Value = infoProduct.GodownId;
         RackComboFill1(infoProduct.GodownId, dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Index, dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Cells["dgvcmbRack"].ColumnIndex);
         dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Cells["dgvcmbRack"].Value = infoProduct.RackId;
         BatchComboFill(decproductId, dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Index, dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Cells["dgvcmbBatch"].ColumnIndex);
         dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Cells["dgvcmbBatch"].Value = BllBatch.BatchIdViewByProductId(decproductId);
         dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Cells["dgvtxtBarcode"].Value = BllBatch.ProductBatchBarcodeViewByBatchId(Convert.ToDecimal(dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Cells["dgvcmbBatch"].Value.ToString()));
         list = bllUnitConvertion.DGVUnitConvertionRateByUnitId(infoProduct.UnitId, infoProduct.ProductName);
         dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Cells["dgvtxtUnitConversionId"].Value = list[0].Rows[0]["unitconversionId"].ToString();
         dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Cells["dgvtxtConversionRate"].Value = list[0].Rows[0]["conversionRate"].ToString();
         decCurrentConversionRate = Convert.ToDecimal(dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Cells["dgvtxtConversionRate"].Value.ToString());
         AmountCalculation("dgvtxtQty", dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Index);
         dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].Cells["dgvtxtRate"].Value = infoProduct.SalesRate.ToString();
         dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].HeaderCell.Value = "X";
         dgvProduct.Rows[Convert.ToInt32(decCurrentRowIndex.ToString())].HeaderCell.Style.ForeColor = Color.Red;
         TotalAmountCalculation();
         frmProductSearchPopupObj.Close();
         frmProductSearchPopupObj = null;
     }
     catch (Exception ex)
     {
         MessageBox.Show("DN12:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
        /// <summary>
        /// Function to get the Details
        /// </summary>
        public void DeliveryNoteDetails()
        {
            try
            {
                ProductInfo infoProduct = new ProductInfo();
                ProductCreationBll BllProductCreation = new ProductCreationBll();
                DeliveryNoteDetailsInfo infoDeliveryNoteDetails = new DeliveryNoteDetailsInfo();
                StockPostingInfo infoStockPosting = new StockPostingInfo();
                StockPostingBll BllStockPosting = new StockPostingBll();
                // StockPostingSP spStockPosting = new StockPostingSP();
                //DeliveryNoteDetailsSP spDeliveryNoteDetails = new DeliveryNoteDetailsSP();
                DeliveryNoteBll bllDeliveryNote = new DeliveryNoteBll();
                UnitBll bllUnit = new UnitBll();

                for (int inI = 0; inI < dgvProduct.Rows.Count - 1; inI++)
                {
                    if (dgvProduct.Rows[inI].Cells["dgvtxtDetailsId"].Value == null)
                    {
                        if (cmbDeliveryMode.Text == "Against Order")
                        {
                            if (dgvProduct.Rows[inI].Cells["dgvtxtOrderDetailsId"].Value != null)
                            {
                                infoDeliveryNoteDetails.OrderDetails1Id = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvtxtOrderDetailsId"].Value == null ? string.Empty : dgvProduct.Rows[inI].Cells["dgvtxtOrderDetailsId"].Value.ToString());
                            }
                            else
                            {
                                infoDeliveryNoteDetails.OrderDetails1Id = 0;
                                infoDeliveryNoteDetails.QuotationDetails1Id = 0;
                            }
                        }
                        else if (cmbDeliveryMode.Text == "Against Quotation")
                        {
                            if (dgvProduct.Rows[inI].Cells["dgvtxtOrderDetailsId"].Value != null)
                            {
                                infoDeliveryNoteDetails.QuotationDetails1Id = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvtxtOrderDetailsId"].Value == null ? string.Empty : dgvProduct.Rows[inI].Cells["dgvtxtOrderDetailsId"].Value.ToString());
                            }
                            else
                            {
                                infoDeliveryNoteDetails.OrderDetails1Id = 0;
                                infoDeliveryNoteDetails.QuotationDetails1Id = 0;
                            }
                        }
                        else if (cmbDeliveryMode.Text == "NA")
                        {
                            infoDeliveryNoteDetails.OrderDetails1Id = 0;
                            infoDeliveryNoteDetails.QuotationDetails1Id = 0;
                        }
                    }
                    else
                    {
                        if (dgvProduct.Rows[inI].Cells["dgvtxtDetailsId"].Value != null)
                        {
                            if (cmbDeliveryMode.Text == "Against Order")
                            {
                                infoDeliveryNoteDetails.OrderDetails1Id = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvtxtOrderDetailsId"].Value.ToString());
                            }
                            else if (cmbDeliveryMode.Text == "Against Quotation")
                            {
                                infoDeliveryNoteDetails.QuotationDetails1Id = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvtxtOrderDetailsId"].Value.ToString());
                            }
                            else if (cmbDeliveryMode.Text == "NA")
                            {
                                infoDeliveryNoteDetails.OrderDetails1Id = 0;
                                infoDeliveryNoteDetails.QuotationDetails1Id = 0;
                            }
                        }
                        else
                        {
                            infoDeliveryNoteDetails.OrderDetails1Id = 0;
                            infoDeliveryNoteDetails.QuotationDetails1Id = 0;
                        }
                    }
                    if (dgvProduct.Rows[inI].Cells["dgvtxtDetailsId"].Value == null || dgvProduct.Rows[inI].Cells["dgvtxtDetailsId"].Value.ToString() == string.Empty || Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvtxtDetailsId"].Value) == 0)
                    {
                        infoDeliveryNoteDetails.DeliveryNoteMasterId = decDelivryNoteIdToEdit;
                        infoProduct = BllProductCreation.ProductViewByCode(dgvProduct.Rows[inI].Cells["dgvtxtProductCode"].Value.ToString());
                        infoDeliveryNoteDetails.ProductId = infoProduct.ProductId;
                        infoDeliveryNoteDetails.Qty = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvtxtQty"].Value.ToString());
                        infoDeliveryNoteDetails.UnitId = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvcmbUnit"].Value);
                        infoDeliveryNoteDetails.BatchId = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvcmbBatch"].Value.ToString());
                        infoDeliveryNoteDetails.GodownId = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvcmbGodown"].Value.ToString());
                        infoDeliveryNoteDetails.RackId = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvcmbRack"].Value.ToString());
                        infoDeliveryNoteDetails.UnitConversionId = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvtxtUnitConversionId"].Value.ToString());
                        infoDeliveryNoteDetails.Rate = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvtxtRate"].Value.ToString());
                        infoDeliveryNoteDetails.Amount = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvtxtAmount"].Value.ToString());
                        infoDeliveryNoteDetails.SlNo = Convert.ToInt32(dgvProduct.Rows[inI].Cells["Col"].Value.ToString());
                        infoDeliveryNoteDetails.Extra1 = string.Empty;
                        infoDeliveryNoteDetails.Extra2 = string.Empty;
                        bllDeliveryNote.DeliveryNoteDetailsAdd(infoDeliveryNoteDetails);
                    }
                    else
                    {
                        infoDeliveryNoteDetails.DeliveryNoteMasterId = decDelivryNoteIdToEdit;
                        infoDeliveryNoteDetails.DeliveryNoteDetails1Id = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvtxtDetailsId"].Value);
                        infoProduct = BllProductCreation.ProductViewByCode(dgvProduct.Rows[inI].Cells["dgvtxtProductCode"].Value.ToString());
                        infoDeliveryNoteDetails.ProductId = infoProduct.ProductId;
                        infoDeliveryNoteDetails.Qty = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvtxtQty"].Value.ToString());

                        if (Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvtxtDetailsId"].Value) == 0)
                        {
                            infoDeliveryNoteDetails.UnitId = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvcmbUnit"].Value.ToString());
                        }
                        else
                        {
                            infoDeliveryNoteDetails.UnitId = Convert.ToDecimal(bllUnit.UnitIdByUnitName(dgvProduct.Rows[inI].Cells["dgvcmbUnit"].FormattedValue.ToString()));
                        }
                        infoDeliveryNoteDetails.BatchId = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvcmbBatch"].Value.ToString());
                        infoDeliveryNoteDetails.GodownId = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvcmbGodown"].Value.ToString());
                        infoDeliveryNoteDetails.RackId = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvcmbRack"].Value.ToString());
                        infoDeliveryNoteDetails.UnitConversionId = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvtxtUnitConversionId"].Value.ToString());
                        infoDeliveryNoteDetails.Rate = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvtxtRate"].Value.ToString());
                        infoDeliveryNoteDetails.Amount = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvtxtAmount"].Value.ToString());
                        infoDeliveryNoteDetails.SlNo = Convert.ToInt32(dgvProduct.Rows[inI].Cells["Col"].Value.ToString());
                        bllDeliveryNote.DeliveryNoteDetailsEdit(infoDeliveryNoteDetails);
                    }
                    infoStockPosting.Date = Convert.ToDateTime(txtDate.Text);
                    if (Convert.ToInt32(dgvProduct.Rows[inI].Cells["dgvtxtVoucherTypeId"].Value) != 0)
                    {
                        if (cmbDeliveryMode.SelectedItem.ToString() != "NA")
                        {
                            if (dgvProduct.Rows[inI].Cells["dgvtxtVoucherTypeId"].Value != null)
                            {
                                infoStockPosting.VoucherTypeId = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvtxtVoucherTypeId"].Value);
                            }
                            else
                            {
                                infoStockPosting.VoucherTypeId = 0;
                            }
                            if (dgvProduct.Rows[inI].Cells["dgvtxtVoucherNo"].Value != null)
                            {
                                infoStockPosting.VoucherNo = dgvProduct.Rows[inI].Cells["dgvtxtVoucherNo"].Value.ToString();
                            }
                            else
                            {
                                infoStockPosting.VoucherNo = string.Empty;
                            }
                            if (dgvProduct.Rows[inI].Cells["dgvtxtInvoiceNo"].Value != null)
                            {
                                infoStockPosting.InvoiceNo = dgvProduct.Rows[inI].Cells["dgvtxtInvoiceNo"].Value.ToString();
                            }
                            else
                            {
                                infoStockPosting.InvoiceNo = string.Empty;
                            }
                            if (decDeliveryNoteVoucherTypeId != 0)
                            {
                                infoStockPosting.AgainstVoucherTypeId = decDeliveryNoteVoucherTypeId;
                            }
                            else
                            {
                                infoStockPosting.AgainstVoucherTypeId = 0;
                            }
                            if (strVoucherNo != string.Empty)
                            {
                                infoStockPosting.AgainstVoucherNo = strVoucherNo;
                            }
                            else
                            {
                                infoStockPosting.AgainstVoucherNo = string.Empty;
                            }
                            if (txtDeliveryNoteNo.Text != string.Empty)
                            {
                                infoStockPosting.AgainstInvoiceNo = txtDeliveryNoteNo.Text;
                            }
                            else
                            {
                                infoStockPosting.AgainstInvoiceNo = string.Empty;
                            }
                        }
                    }
                    else
                    {
                        infoStockPosting.InvoiceNo = txtDeliveryNoteNo.Text;
                        infoStockPosting.VoucherNo = strVoucherNo;
                        infoStockPosting.VoucherTypeId = decDeliveryNoteVoucherTypeId;
                        infoStockPosting.AgainstVoucherTypeId = 0;
                        infoStockPosting.AgainstVoucherNo = "NA";
                        infoStockPosting.AgainstInvoiceNo = "NA";
                    }
                    infoStockPosting.ProductId = infoDeliveryNoteDetails.ProductId;
                    infoStockPosting.BatchId = infoDeliveryNoteDetails.BatchId;
                    infoStockPosting.UnitId = infoDeliveryNoteDetails.UnitId;
                    infoStockPosting.GodownId = infoDeliveryNoteDetails.GodownId;
                    infoStockPosting.RackId = infoDeliveryNoteDetails.RackId;
                    infoStockPosting.OutwardQty = infoDeliveryNoteDetails.Qty;
                    infoStockPosting.Rate = infoDeliveryNoteDetails.Rate;
                    infoStockPosting.FinancialYearId = PublicVariables._decCurrentFinancialYearId;
                    infoStockPosting.Extra1 = string.Empty;
                    infoStockPosting.Extra2 = string.Empty;
                    BllStockPosting.StockPostingAdd(infoStockPosting);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("DN36:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        ///// <summary>
        ///// 获取限时抢购诊疗项目详情
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        public object GetLimitBuyProduct(string openId, long countDownId)
        {
            CheckUserLogin();
            ProductDetailModelForMobie model = new ProductDetailModelForMobie()
            {
                Product = new ProductInfoModel(),
                Shop    = new ShopInfoModel(),
                Color   = new CollectionSKU(),
                Size    = new CollectionSKU(),
                Version = new CollectionSKU()
            };
            ProductInfo    product = null;
            ShopInfo       shop    = null;
            FlashSaleModel market  = null;

            market = ServiceProvider.Instance <ILimitTimeBuyService> .Create.Get(countDownId);


            if (market == null || market.Status != FlashSaleInfo.FlashSaleStatus.Ongoing)
            {
                //可能参数是诊疗项目ID
                market = market == null ? ServiceProvider.Instance <ILimitTimeBuyService> .Create.GetFlaseSaleByProductId(countDownId) : market;

                if (market == null || market.Status != FlashSaleInfo.FlashSaleStatus.Ongoing)
                {
                    //跳转到404页面
                    return(Json(new { Success = "false", ErrorMsg = "你所请求的限时购或者诊疗项目不存在!" }));
                }
            }

            if (market != null && (market.Status != FlashSaleInfo.FlashSaleStatus.Ongoing || DateTime.Parse(market.EndDate) < DateTime.Now))
            {
                return(Json(new { Success = "true", IsValidLimitBuy = "false" }));
            }

            model.MaxSaleCount = market.LimitCountOfThePeople;
            model.Title        = market.Title;

            product = ServiceProvider.Instance <IProductService> .Create.GetProduct(market.ProductId);

            bool hasSku = false;

            #region 诊疗项目SKU
            ProductTypeInfo typeInfo = ServiceProvider.Instance <ITypeService> .Create.GetType(product.TypeId);

            string colorAlias   = (typeInfo == null || string.IsNullOrEmpty(typeInfo.ColorAlias)) ? SpecificationType.Color.ToDescription() : typeInfo.ColorAlias;
            string sizeAlias    = (typeInfo == null || string.IsNullOrEmpty(typeInfo.SizeAlias)) ? SpecificationType.Size.ToDescription() : typeInfo.SizeAlias;
            string versionAlias = (typeInfo == null || string.IsNullOrEmpty(typeInfo.VersionAlias)) ? SpecificationType.Version.ToDescription() : typeInfo.VersionAlias;


            List <object> SkuItemList = new List <object>();
            List <object> Skus        = new List <object>();
            if (product.SKUInfo != null && product.SKUInfo.Count() > 0)
            {
                hasSku = true;
                #region 颜色
                long          colorId = 0, sizeId = 0, versionId = 0;
                List <object> colorAttributeValue = new List <object>();
                List <string> listcolor           = new List <string>();
                foreach (var sku in product.SKUInfo)
                {
                    var specs = sku.Id.Split('_');
                    if (specs.Count() > 0)
                    {
                        if (long.TryParse(specs[1], out colorId))
                        {
                        }                                            //相同颜色规格累加对应值
                        if (colorId != 0)
                        {
                            if (!listcolor.Contains(sku.Color))
                            {
                                var c          = product.SKUInfo.Where(s => s.Color.Equals(sku.Color)).Sum(s => s.Stock);
                                var colorvalue = new
                                {
                                    ValueId           = colorId,
                                    UseAttributeImage = "False",
                                    Value             = sku.Color,
                                    ImageUrl          = Himall.Core.HimallIO.GetRomoteImagePath(sku.ShowPic)
                                };
                                listcolor.Add(sku.Color);
                                colorAttributeValue.Add(colorvalue);
                            }
                        }
                    }
                }
                var color = new
                {
                    AttributeName  = colorAlias,
                    AttributeId    = product.TypeId,
                    AttributeValue = colorAttributeValue
                };
                if (colorId > 0)
                {
                    SkuItemList.Add(color);
                }
                #endregion

                #region 容量
                List <object> sizeAttributeValue = new List <object>();
                List <string> listsize           = new List <string>();
                foreach (var sku in product.SKUInfo)
                {
                    var specs = sku.Id.Split('_');
                    if (specs.Count() > 1)
                    {
                        if (long.TryParse(specs[2], out sizeId))
                        {
                        }
                        if (sizeId != 0)
                        {
                            if (!listsize.Contains(sku.Size))
                            {
                                var ss        = product.SKUInfo.Where(s => s.Size.Equals(sku.Size)).Sum(s1 => s1.Stock);
                                var sizeValue = new
                                {
                                    ValueId           = sizeId,
                                    UseAttributeImage = false,
                                    Value             = sku.Size,
                                    ImageUrl          = Himall.Core.HimallIO.GetRomoteImagePath(sku.ShowPic)
                                };
                                listsize.Add(sku.Size);
                                sizeAttributeValue.Add(sizeValue);
                            }
                        }
                    }
                }
                var size = new
                {
                    AttributeName  = sizeAlias,
                    AttributeId    = product.TypeId,
                    AttributeValue = sizeAttributeValue
                };
                if (sizeId > 0)
                {
                    SkuItemList.Add(size);
                }
                #endregion

                #region 规格
                List <object> versionAttributeValue = new List <object>();
                List <string> listversion           = new List <string>();
                foreach (var sku in product.SKUInfo)
                {
                    var specs = sku.Id.Split('_');
                    if (specs.Count() > 2)
                    {
                        if (long.TryParse(specs[3], out versionId))
                        {
                        }
                        if (versionId != 0)
                        {
                            if (!listversion.Contains(sku.Version))
                            {
                                var v            = product.SKUInfo.Where(s => s.Version.Equals(sku.Version));
                                var versionValue = new
                                {
                                    ValueId           = versionId,
                                    UseAttributeImage = false,
                                    Value             = sku.Version,
                                    ImageUrl          = Himall.Core.HimallIO.GetRomoteImagePath(sku.ShowPic)
                                };
                                listversion.Add(sku.Version);
                                versionAttributeValue.Add(versionValue);
                            }
                        }
                    }
                }
                var version = new
                {
                    AttributeName  = versionAlias,
                    AttributeId    = product.TypeId,
                    AttributeValue = versionAttributeValue
                };
                if (versionId > 0)
                {
                    SkuItemList.Add(version);
                }
                #endregion

                #region Sku值
                foreach (var sku in product.SKUInfo)
                {
                    FlashSaleDetailInfo detailInfo = ServiceProvider.Instance <ILimitTimeBuyService> .Create.GetDetail(sku.Id);

                    var prosku = new
                    {
                        SkuItems        = "",
                        MemberPrices    = "",
                        SkuId           = sku.Id,
                        ProductId       = product.Id,
                        SKU             = sku.Sku,
                        Weight          = 0,
                        Stock           = sku.Stock,
                        WarningStock    = sku.SafeStock,
                        CostPrice       = sku.CostPrice,
                        SalePrice       = sku.SalePrice,//限时抢购价格
                        StoreStock      = 0,
                        StoreSalePrice  = 0,
                        OldSalePrice    = 0,
                        ImageUrl        = "",
                        ThumbnailUrl40  = "",
                        ThumbnailUrl410 = "",
                        MaxStock        = 15,
                        FreezeStock     = 0,
                        ActivityStock   = sku.Stock,       //限时抢购库存
                        ActivityPrice   = detailInfo.Price //限时抢购价格
                    };
                    Skus.Add(prosku);
                }
                #endregion
            }
            #endregion

            #region 诊所
            shop = ServiceProvider.Instance <IShopService> .Create.GetShop(product.ShopId);

            var mark = ShopServiceMark.GetShopComprehensiveMark(shop.Id);
            model.Shop.PackMark          = mark.PackMark;
            model.Shop.ServiceMark       = mark.ServiceMark;
            model.Shop.ComprehensiveMark = mark.ComprehensiveMark;
            var comm = ServiceProvider.Instance <ICommentService> .Create.GetCommentsByProductId(product.Id);

            model.Shop.Name        = shop.ShopName;
            model.Shop.ProductMark = (comm == null || comm.Count() == 0) ? 0 : comm.Average(p => (decimal)p.ReviewMark);
            model.Shop.Id          = product.ShopId;
            model.Shop.FreeFreight = shop.FreeFreight;
            model.Shop.ProductNum  = ServiceProvider.Instance <IProductService> .Create.GetShopOnsaleProducts(product.ShopId);

            var shopStatisticOrderComments = ServiceProvider.Instance <IShopService> .Create.GetShopStatisticOrderComments(product.ShopId);

            var productAndDescription = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.ProductAndDescription).FirstOrDefault();
            var sellerServiceAttitude = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.SellerServiceAttitude).FirstOrDefault();
            var sellerDeliverySpeed   = shopStatisticOrderComments.Where(c => c.CommentKey ==
                                                                         StatisticOrderCommentsInfo.EnumCommentKey.SellerDeliverySpeed).FirstOrDefault();

            var productAndDescriptionPeer = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.ProductAndDescriptionPeer).FirstOrDefault();
            var sellerServiceAttitudePeer = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.SellerServiceAttitudePeer).FirstOrDefault();
            var sellerDeliverySpeedPeer   = shopStatisticOrderComments.Where(c => c.CommentKey ==
                                                                             StatisticOrderCommentsInfo.EnumCommentKey.SellerDeliverySpeedPeer).FirstOrDefault();

            var productAndDescriptionMax = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.ProductAndDescriptionMax).FirstOrDefault();
            var productAndDescriptionMin = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.ProductAndDescriptionMin).FirstOrDefault();

            var sellerServiceAttitudeMax = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.SellerServiceAttitudeMax).FirstOrDefault();
            var sellerServiceAttitudeMin = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.SellerServiceAttitudeMin).FirstOrDefault();

            var sellerDeliverySpeedMax = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.SellerDeliverySpeedMax).FirstOrDefault();
            var sellerDeliverySpeedMin = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.SellerDeliverySpeedMin).FirstOrDefault();

            decimal defaultValue = 5;
            //宝贝与描述
            if (productAndDescription != null && productAndDescriptionPeer != null)
            {
                model.Shop.ProductAndDescription = productAndDescription.CommentValue;
            }
            else
            {
                model.Shop.ProductAndDescription = defaultValue;
            }
            //诊所服务态度
            if (sellerServiceAttitude != null && sellerServiceAttitudePeer != null)
            {
                model.Shop.SellerServiceAttitude = sellerServiceAttitude.CommentValue;
            }
            else
            {
                model.Shop.SellerServiceAttitude = defaultValue;
            }
            //诊所发货速度
            if (sellerDeliverySpeedPeer != null && sellerDeliverySpeed != null)
            {
                model.Shop.SellerDeliverySpeed = sellerDeliverySpeed.CommentValue;
            }
            else
            {
                model.Shop.SellerDeliverySpeed = defaultValue;
            }
            if (ServiceProvider.Instance <IVShopService> .Create.GetVShopByShopId(shop.Id) == null)
            {
                model.Shop.VShopId = -1;
            }
            else
            {
                model.Shop.VShopId = ServiceProvider.Instance <IVShopService> .Create.GetVShopByShopId(shop.Id).Id;
            }


            List <object> coupons = new List <object>();
            //优惠券
            var result = GetCouponList(shop.Id);//取设置的优惠券
            if (result != null)
            {
                var couponCount = result.Count();
                model.Shop.CouponCount = couponCount;
                if (result.ToList().Count > 0)
                {
                    foreach (var item in result.ToList())
                    {
                        var couponInfo = new
                        {
                            CouponId           = item.Id,
                            CouponName         = item.CouponName,
                            Price              = item.Price,
                            SendCount          = item.Num,
                            UserLimitCount     = item.PerMax,
                            OrderUseLimit      = item.OrderAmount,
                            StartTime          = item.StartTime.ToString("yyyy-MM-dd HH:mm:ss"),
                            ClosingTime        = item.EndTime.ToString("yyyy-MM-dd HH:mm:ss"),
                            CanUseProducts     = "",
                            ObtainWay          = item.ReceiveType,
                            NeedPoint          = item.NeedIntegral,
                            UseWithGroup       = false,
                            UseWithPanicBuying = false,
                            UseWithFireGroup   = false,
                            LimitText          = item.CouponName,
                            CanUseProduct      = "诊所通用",
                            StartTimeText      = item.StartTime.ToString("yyyy.MM.dd"),
                            ClosingTimeText    = item.EndTime.ToString("yyyy.MM.dd")
                        };
                        coupons.Add(couponInfo);
                    }
                }
            }


            #endregion

            #region 诊疗项目
            var consultations = ServiceProvider.Instance <IConsultationService> .Create.GetConsultations(product.Id);

            double total      = product.Himall_ProductComments.Count();
            double niceTotal  = product.Himall_ProductComments.Count(item => item.ReviewMark >= 4);
            bool   isFavorite = false;
            if (CurrentUser == null)
            {
                isFavorite = false;
            }
            else
            {
                isFavorite = ServiceProvider.Instance <IProductService> .Create.IsFavorite(product.Id, CurrentUser.Id);
            }
            var limitBuy = ServiceProvider.Instance <ILimitTimeBuyService> .Create.GetLimitTimeMarketItemByProductId(product.Id);

            var productImage = new List <string>();
            for (int i = 1; i < 6; i++)
            {
                if (File.Exists(HttpContext.Current.Server.MapPath(product.RelativePath + string.Format("/{0}.png", i))))
                {
                    productImage.Add(Core.HimallIO.GetRomoteImagePath(product.RelativePath + string.Format("/{0}.png", i)));
                }
            }
            model.Product = new ProductInfoModel()
            {
                ProductId          = product.Id,
                CommentCount       = product.Himall_ProductComments.Count(),
                Consultations      = consultations.Count(),
                ImagePath          = productImage,
                IsFavorite         = isFavorite,
                MarketPrice        = product.MarketPrice,
                MinSalePrice       = product.MinSalePrice,
                NicePercent        = model.Shop.ProductMark == 0 ? 100 : (int)((niceTotal / total) * 100),
                ProductName        = product.ProductName,
                ProductSaleStatus  = product.SaleStatus,
                AuditStatus        = product.AuditStatus,
                ShortDescription   = product.ShortDescription,
                ProductDescription = product.ProductDescriptionInfo.ShowMobileDescription,
                IsOnLimitBuy       = limitBuy != null
            };
            #endregion

            //LogProduct(market.ProductId);
            //统计诊疗项目浏览量、诊所浏览人数
            StatisticApplication.StatisticVisitCount(product.Id, product.ShopId);

            TimeSpan end    = new TimeSpan(DateTime.Parse(market.EndDate).Ticks);
            TimeSpan start  = new TimeSpan(DateTime.Now.Ticks);
            TimeSpan ts     = end.Subtract(start);
            var      second = ts.TotalSeconds < 0 ? 0 : ts.TotalSeconds;

            List <object> ProductImgs = new List <object>();
            for (int i = 1; i < 5; i++)
            {
                ProductImgs.Add(Core.HimallIO.GetRomoteProductSizeImage(product.ImagePath, i, (int)ImageSize.Size_350));
            }

            var countDownStatus = 0;

            if (market.Status == FlashSaleInfo.FlashSaleStatus.Ended)
            {
                countDownStatus = 4;//"PullOff";  //已下架
            }
            else if (market.Status == FlashSaleInfo.FlashSaleStatus.Cancelled || market.Status == FlashSaleInfo.FlashSaleStatus.AuditFailed || market.Status == FlashSaleInfo.FlashSaleStatus.WaitForAuditing)
            {
                countDownStatus = 4;//"NoJoin";  //未参与
            }
            else if (DateTime.Parse(market.BeginDate) > DateTime.Now)
            {
                countDownStatus = 6; // "AboutToBegin";  //即将开始   6
            }
            else if (DateTime.Parse(market.EndDate) < DateTime.Now)
            {
                countDownStatus = 4;// "ActivityEnd";   //已结束  4
            }
            else if (market.Status == FlashSaleInfo.FlashSaleStatus.Ended)
            {
                countDownStatus = 6;// "SoldOut";  //已抢完
            }
            else
            {
                countDownStatus = 2;//"Normal";  //正常  2
            }

            //Normal:正常
            //PullOff:已下架
            //NoJoin:未参与
            //AboutToBegin:即将开始
            //ActivityEnd:已结束
            //SoldOut:已抢完

            var json = new
            {
                Status = "OK",
                Data   = new
                {
                    CountDownId      = market.Id,//.CountDownId,
                    MaxCount         = market.LimitCountOfThePeople,
                    CountDownStatus  = countDownStatus,
                    StartDate        = DateTime.Parse(market.BeginDate).ToString("yyyy/MM/dd HH:mm:ss"),
                    EndDate          = DateTime.Parse(market.EndDate).ToString("yyyy/MM/dd HH:mm:ss"),
                    NowTime          = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo),
                    ProductId        = product.Id,
                    ProductName      = product.ProductName,
                    MetaDescription  = model.Product.ProductDescription,
                    ShortDescription = product.ShortDescription,
                    ShowSaleCounts   = product.SaleCounts.ToString(),
                    Weight           = product.Weight.ToString(),
                    MinSalePrice     = market.MinPrice.ToString("0.##"), //product.SKUInfo.Min(c => c.SalePrice).ToString("0.##"),//限时抢购价格
                    MaxSalePrice     = product.MarketPrice,
                    Stock            = market.Quantity,                  //限时抢购库存
                    MarketPrice      = product.MarketPrice,              //product.SKUInfo.Min(c => c.SalePrice).ToString("0.##"),
                    IsfreeShipping   = product.Himall_Shops.FreeFreight, //product.Product.IsfreeShipping.ToString(),
                    ThumbnailUrl60   = Core.HimallIO.GetRomoteProductSizeImage(product.ImagePath, 1, (int)ImageSize.Size_350),
                    ProductImgs      = ProductImgs,
                    SkuItemList      = SkuItemList,
                    Skus             = Skus,
                    Freight          = 0,
                    Coupons          = coupons,
                }
            };
            return(json);
        }
예제 #52
0
 public static void ImportProducts(DataTable productData, int categoryId, int lineId, int? brandId, ProductSaleStatus saleStatus, bool isImportFromTaobao,string wid)
 {
     if ((productData != null) && (productData.Rows.Count > 0))
     {
         foreach (DataRow row in productData.Rows)
         {
             ProductInfo product = new ProductInfo {
                 CategoryId = categoryId,
                 MainCategoryPath = CatalogHelper.GetCategory(categoryId).Path + "|",
                 ProductName = (string) row["ProductName"],
                 ProductCode = (string) row["SKU"],
                 BrandId = brandId
             };
             if (row["Description"] != DBNull.Value)
             {
                 product.Description = (string) row["Description"];
             }
             product.MarketPrice = new decimal?((decimal) row["SalePrice"]);
             product.AddedDate = DateTime.Now;
             product.SaleStatus = saleStatus;
             product.HasSKU = false;
             HttpContext current = HttpContext.Current;
             if (row["ImageUrl1"] != DBNull.Value)
             {
                 product.ImageUrl1 = (string) row["ImageUrl1"];
             }
             if (!string.IsNullOrEmpty(product.ImageUrl1) && (product.ImageUrl1.Length > 0))
             {
                 string[] strArray = ProcessImages(current, product.ImageUrl1);
                 product.ThumbnailUrl40 = strArray[0];
                 product.ThumbnailUrl60 = strArray[1];
                 product.ThumbnailUrl100 = strArray[2];
                 product.ThumbnailUrl160 = strArray[3];
                 product.ThumbnailUrl180 = strArray[4];
                 product.ThumbnailUrl220 = strArray[5];
                 product.ThumbnailUrl310 = strArray[6];
                 product.ThumbnailUrl410 = strArray[7];
             }
             if (row["ImageUrl2"] != DBNull.Value)
             {
                 product.ImageUrl2 = (string) row["ImageUrl2"];
             }
             if (!string.IsNullOrEmpty(product.ImageUrl2) && (product.ImageUrl2.Length > 0))
             {
                 ProcessImages(current, product.ImageUrl2);
             }
             if (row["ImageUrl3"] != DBNull.Value)
             {
                 product.ImageUrl3 = (string) row["ImageUrl3"];
             }
             if (!string.IsNullOrEmpty(product.ImageUrl3) && (product.ImageUrl3.Length > 0))
             {
                 ProcessImages(current, product.ImageUrl3);
             }
             if (row["ImageUrl4"] != DBNull.Value)
             {
                 product.ImageUrl4 = (string) row["ImageUrl4"];
             }
             if (!string.IsNullOrEmpty(product.ImageUrl4) && (product.ImageUrl4.Length > 0))
             {
                 ProcessImages(current, product.ImageUrl4);
             }
             if (row["ImageUrl5"] != DBNull.Value)
             {
                 product.ImageUrl5 = (string) row["ImageUrl5"];
             }
             if (!string.IsNullOrEmpty(product.ImageUrl5) && (product.ImageUrl5.Length > 0))
             {
                 ProcessImages(current, product.ImageUrl5);
             }
             SKUItem item = new SKUItem {
                 SkuId = "0",
                 SKU = (string) row["SKU"]
             };
             if (row["Stock"] != DBNull.Value)
             {
                 item.Stock = (int) row["Stock"];
             }
             if (row["Weight"] != DBNull.Value)
             {
                 item.Weight = (decimal) row["Weight"];
             }
             item.SalePrice = (decimal) row["SalePrice"];
             Dictionary<string, SKUItem> skus = new Dictionary<string, SKUItem>();
             skus.Add(item.SkuId, item);
             ProductActionStatus status = AddProduct(product, skus, null, null,wid);
             if (isImportFromTaobao && (status == ProductActionStatus.Success))
             {
                 TaobaoProductInfo taobaoProduct = new TaobaoProductInfo {
                     ProductId = product.ProductId,
                     ProTitle = product.ProductName,
                     Cid = (long) row["Cid"]
                 };
                 if (row["StuffStatus"] != DBNull.Value)
                 {
                     taobaoProduct.StuffStatus = (string) row["StuffStatus"];
                 }
                 taobaoProduct.Num = (long) row["Num"];
                 taobaoProduct.LocationState = (string) row["LocationState"];
                 taobaoProduct.LocationCity = (string) row["LocationCity"];
                 taobaoProduct.FreightPayer = (string) row["FreightPayer"];
                 if (row["PostFee"] != DBNull.Value)
                 {
                     taobaoProduct.PostFee = (decimal) row["PostFee"];
                 }
                 if (row["ExpressFee"] != DBNull.Value)
                 {
                     taobaoProduct.ExpressFee = (decimal) row["ExpressFee"];
                 }
                 if (row["EMSFee"] != DBNull.Value)
                 {
                     taobaoProduct.EMSFee = (decimal) row["EMSFee"];
                 }
                 taobaoProduct.HasInvoice = (bool) row["HasInvoice"];
                 taobaoProduct.HasWarranty = (bool) row["HasWarranty"];
                 taobaoProduct.HasDiscount = (bool) row["HasDiscount"];
                 taobaoProduct.ValidThru = (long) row["ValidThru"];
                 if (row["ListTime"] != DBNull.Value)
                 {
                     taobaoProduct.ListTime = (DateTime) row["ListTime"];
                 }
                 else
                 {
                     taobaoProduct.ListTime = DateTime.Now;
                 }
                 if (row["PropertyAlias"] != DBNull.Value)
                 {
                     taobaoProduct.PropertyAlias = (string) row["PropertyAlias"];
                 }
                 if (row["InputPids"] != DBNull.Value)
                 {
                     taobaoProduct.InputPids = (string) row["InputPids"];
                 }
                 if (row["InputStr"] != DBNull.Value)
                 {
                     taobaoProduct.InputStr = (string) row["InputStr"];
                 }
                 if (row["SkuProperties"] != DBNull.Value)
                 {
                     taobaoProduct.SkuProperties = (string) row["SkuProperties"];
                 }
                 if (row["SkuQuantities"] != DBNull.Value)
                 {
                     taobaoProduct.SkuQuantities = (string) row["SkuQuantities"];
                 }
                 if (row["SkuPrices"] != DBNull.Value)
                 {
                     taobaoProduct.SkuPrices = (string) row["SkuPrices"];
                 }
                 if (row["SkuOuterIds"] != DBNull.Value)
                 {
                     taobaoProduct.SkuOuterIds = (string) row["SkuOuterIds"];
                 }
                 UpdateToaobProduct(taobaoProduct);
             }
         }
     }
 }
    void AddProductInfo(ProductInfo info)
    {
        string strSql
             = @"insert into [products] 
                (CategoryID,HatName,Quantity,ColourID,SupplierID,Price,Path,Description,LoadDate)  
                values(@CategoryID,@HatName,@Quantity,@ColourID, @SupplierID,@Price,@Path,@Description,@LoadDate)";


        SqlParameter[] parmeters = new SqlParameter[]
        {
            new SqlParameter("@CategoryID",info.CategoryID),
            new SqlParameter("@HatName",info.HatName),
            new SqlParameter("@Quantity",info.Quantity),
            new SqlParameter("@ColourID",info.ColourID),
            new SqlParameter("@SupplierID",info.SupplierID),
            new SqlParameter("@Price",info.Price),
            new SqlParameter("@Path",info.Path),
            new SqlParameter("@Description",info.Description),
            new SqlParameter("@LoadDate",info.LoadDate),
        };
        SqlCommand myCmd = dbObj.GetCommandStr(strSql, parmeters);
        dbObj.ExecNonQuery(myCmd);
        Response.Write(ccObj.MessageBox("Successful!", "ProductList.aspx"));
    }
예제 #54
0
        private void DownloadImage(ProductInfo product, string imageUrls, System.Web.HttpContext context)
        {
            imageUrls = System.Web.HttpUtility.UrlDecode(imageUrls);
            string[] array = imageUrls.Split(new char[]
            {
                ';'
            });
            int num = 1;

            string[] array2 = array;
            for (int i = 0; i < array2.Length; i++)
            {
                string text   = array2[i];
                string text2  = string.Format("/Storage/master/product/images/{0}", System.Guid.NewGuid().ToString("N", System.Globalization.CultureInfo.InvariantCulture) + text.Substring(text.LastIndexOf('.')));
                string text3  = text2.Replace("/images/", "/thumbs40/40_");
                string text4  = text2.Replace("/images/", "/thumbs60/60_");
                string text5  = text2.Replace("/images/", "/thumbs100/100_");
                string text6  = text2.Replace("/images/", "/thumbs160/160_");
                string text7  = text2.Replace("/images/", "/thumbs180/180_");
                string text8  = text2.Replace("/images/", "/thumbs220/220_");
                string text9  = text2.Replace("/images/", "/thumbs310/310_");
                string text10 = text2.Replace("/images/", "/thumbs410/410_");
                string text11 = System.Web.HttpContext.Current.Request.MapPath(Globals.ApplicationPath + text2);
                System.Net.WebClient webClient = new System.Net.WebClient();
                try
                {
                    webClient.DownloadFile(text, text11);
                    ResourcesHelper.CreateThumbnail(text11, context.Request.MapPath(Globals.ApplicationPath + text3), 40, 40);
                    ResourcesHelper.CreateThumbnail(text11, context.Request.MapPath(Globals.ApplicationPath + text4), 60, 60);
                    ResourcesHelper.CreateThumbnail(text11, context.Request.MapPath(Globals.ApplicationPath + text5), 100, 100);
                    ResourcesHelper.CreateThumbnail(text11, context.Request.MapPath(Globals.ApplicationPath + text6), 160, 160);
                    ResourcesHelper.CreateThumbnail(text11, context.Request.MapPath(Globals.ApplicationPath + text7), 180, 180);
                    ResourcesHelper.CreateThumbnail(text11, context.Request.MapPath(Globals.ApplicationPath + text8), 220, 220);
                    ResourcesHelper.CreateThumbnail(text11, context.Request.MapPath(Globals.ApplicationPath + text9), 310, 310);
                    ResourcesHelper.CreateThumbnail(text11, context.Request.MapPath(Globals.ApplicationPath + text10), 410, 410);
                    switch (num)
                    {
                    case 1:
                        product.ImageUrl1       = text2;
                        product.ThumbnailUrl40  = text3;
                        product.ThumbnailUrl60  = text4;
                        product.ThumbnailUrl100 = text5;
                        product.ThumbnailUrl160 = text6;
                        product.ThumbnailUrl180 = text7;
                        product.ThumbnailUrl220 = text8;
                        product.ThumbnailUrl310 = text9;
                        product.ThumbnailUrl410 = text10;
                        break;

                    case 2:
                        product.ImageUrl2 = text2;
                        break;

                    case 3:
                        product.ImageUrl3 = text2;
                        break;

                    case 4:
                        product.ImageUrl4 = text2;
                        break;

                    case 5:
                        product.ImageUrl5 = text2;
                        break;
                    }
                    num++;
                }
                catch
                {
                }
            }
        }
 /// <summary>
 ///Function for ReturnFromProductCreationPopup
 /// </summary>
 public void ReturnFromProductCreation(decimal decProductId)
 {
     ProductInfo infoProduct = new ProductInfo();
     ProductCreationBll BllProductCreation = new ProductCreationBll();
     BatchBll BllBatch = new BatchBll();
     List<DataTable> list = new List<DataTable>();
     UnitConvertionBll bllUnitConvertion = new UnitConvertionBll();
     try
     {
         this.Enabled = true;
         this.BringToFront();
         int inI = dgvProduct.CurrentRow.Index;
         if (inI == dgvProduct.Rows.Count - 1)
         {
             dgvProduct.Rows.Add();
         }
         if (decProductId != 0)
         {
             infoProduct = BllProductCreation.ProductView(decProductId);
             dgvProduct.Rows[inI].Cells["dgvtxtProductCode"].Value = infoProduct.ProductCode.ToString();
             dgvProduct.Rows[inI].Cells["dgvtxtProductId"].Value = decProductId.ToString();
             dgvProduct.Rows[inI].Cells["dgvtxtProductName"].Value = infoProduct.ProductName;
             dgvProduct.Rows[inI].Cells["dgvtxtRate"].Value = infoProduct.SalesRate.ToString();
             UnitComboFill1(decProductId, inI, dgvProduct.Rows[inI].Cells["dgvcmbUnit"].ColumnIndex);
             dgvProduct.Rows[inI].Cells["dgvcmbUnit"].Value = infoProduct.UnitId;
             BatchComboFill(decProductId, inI, dgvProduct.Rows[inI].Cells["dgvcmbBatch"].ColumnIndex);
             dgvProduct.Rows[inI].Cells["dgvcmbBatch"].Value = BllBatch.BatchIdViewByProductId(decProductId);
             dgvProduct.Rows[inI].Cells["dgvtxtBarcode"].Value = BllBatch.ProductBatchBarcodeViewByBatchId(Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvcmbBatch"].Value.ToString()));
             GridGodownComboFill(decProductId, dgvProduct.CurrentRow.Index, dgvProduct.Rows[inI].Cells["dgvcmbGodown"].ColumnIndex);
             dgvProduct.Rows[inI].Cells["dgvcmbGodown"].Value = infoProduct.GodownId;
             RackComboFill1(infoProduct.GodownId, inI, dgvProduct.Rows[inI].Cells["dgvcmbRack"].ColumnIndex);
             dgvProduct.Rows[inI].Cells["dgvcmbRack"].Value = infoProduct.RackId;
             list = bllUnitConvertion.DGVUnitConvertionRateByUnitId(infoProduct.UnitId, infoProduct.ProductName);
             dgvProduct.Rows[inI].Cells["dgvtxtUnitConversionId"].Value = list[0].Rows[0]["unitconversionId"].ToString();
             dgvProduct.Rows[inI].Cells["dgvtxtConversionRate"].Value = list[0].Rows[0]["conversionRate"].ToString();
             decCurrentConversionRate = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvtxtConversionRate"].Value.ToString());
             decCurrentRate = Convert.ToDecimal(dgvProduct.Rows[inI].Cells["dgvtxtRate"].Value.ToString());
             AmountCalculation("dgvtxtQty", dgvProduct.CurrentRow.Index);
             dgvProduct.Rows[inI].HeaderCell.Value = "X";
             dgvProduct.Rows[inI].HeaderCell.Style.ForeColor = Color.Red;
             TotalAmountCalculation();
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("DN25:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
예제 #56
0
        private System.Collections.Generic.Dictionary <string, SKUItem> GetSkus(ProductInfo product, decimal weight, System.Web.HttpContext context)
        {
            string text = context.Request.Form["SkuString"];

            System.Collections.Generic.Dictionary <string, SKUItem> dictionary;
            if (string.IsNullOrEmpty(text))
            {
                product.HasSKU = false;
                dictionary     = new System.Collections.Generic.Dictionary <string, SKUItem>
                {
                    {
                        "0",
                        new SKUItem
                        {
                            SkuId     = "0",
                            SKU       = product.ProductCode,
                            SalePrice = decimal.Parse(context.Request.Form["SalePrice"]),
                            CostPrice = 0m,
                            Stock     = int.Parse(context.Request.Form["Stock"]),
                            Weight    = weight
                        }
                    }
                };
            }
            else
            {
                product.HasSKU = true;
                dictionary     = new System.Collections.Generic.Dictionary <string, SKUItem>();
                text           = System.Web.HttpUtility.UrlDecode(text);
                string[] array = text.Split(new char[]
                {
                    '|'
                });
                for (int i = 0; i < array.Length; i++)
                {
                    string   text2  = array[i];
                    string[] array2 = text2.Split(new char[]
                    {
                        ','
                    });
                    SKUItem sKUItem = new SKUItem();
                    sKUItem.SKU       = array2[0].Replace("_", "-");
                    sKUItem.Weight    = weight;
                    sKUItem.Stock     = int.Parse(array2[1]);
                    sKUItem.SalePrice = decimal.Parse(array2[2]);
                    string   text3  = array2[3];
                    string   text4  = "";
                    string[] array3 = text3.Split(new char[]
                    {
                        ';'
                    });
                    for (int j = 0; j < array3.Length; j++)
                    {
                        string   text5  = array3[j];
                        string[] array4 = text5.Split(new char[]
                        {
                            ':'
                        });
                        int specificationId      = ProductTypeHelper.GetSpecificationId(product.TypeId.Value, array4[0]);
                        int specificationValueId = ProductTypeHelper.GetSpecificationValueId(specificationId, array4[1].Replace("\\", "/"));
                        text4 = text4 + specificationValueId + "_";
                        sKUItem.SkuItems.Add(specificationId, specificationValueId);
                    }
                    sKUItem.SkuId = text4.Substring(0, text4.Length - 1);
                    dictionary.Add(sKUItem.SkuId, sKUItem);
                }
            }
            return(dictionary);
        }
 /// <summary>
 /// Fill Product Details Curresponding Product code or Barcode
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void dgvProduct_CellEndEdit(object sender, DataGridViewCellEventArgs e)
 {
     BatchBll BllBatch = new BatchBll();
     try
     {
         ProductInfo infoProduct = new ProductInfo();
         List<DataTable> listObj = new List<DataTable>();
         isValueChange = false;
         isDoAfterGridFill = false;
         decimal DefaultRate = 0;
         if (dgvProduct.Columns[e.ColumnIndex].Name == "dgvtxtBarcode")
         {
             string strBCode = string.Empty;
             if (!dgvProduct.Rows[e.RowIndex].Cells["dgvtxtBarcode"].ReadOnly && dgvProduct.Rows[e.RowIndex].Cells["dgvtxtBarcode"].Value != null && dgvProduct.Rows[e.RowIndex].Cells["dgvtxtBarcode"].Value.ToString() != string.Empty)
             {
                 strBCode = dgvProduct.Rows[e.RowIndex].Cells["dgvtxtBarcode"].Value.ToString();
             }
             listObj = new ProductCreationBll().ProductDetailsCoreespondingToBarcode(strBCode);
             if (listObj[0].Rows.Count > 0)
             {
                 foreach (DataRow RowDetails in listObj[0].Rows)
                 {
                     dgvProduct.Rows[e.RowIndex].Cells["dgvtxtProductId"].Value = RowDetails["productId"].ToString();
                     decimal decProductId = Convert.ToDecimal(dgvProduct.Rows[e.RowIndex].Cells["dgvtxtProductId"].Value.ToString());
                     dgvProduct.Rows[e.RowIndex].Cells["dgvtxtProductCode"].Value = RowDetails["productCode"].ToString();
                     dgvProduct.Rows[e.RowIndex].Cells["dgvtxtProductName"].Value = RowDetails["productName"].ToString();
                     UnitComboFill1(Convert.ToDecimal(RowDetails["productId"].ToString()), e.RowIndex, dgvProduct.Rows[e.RowIndex].Cells["dgvcmbUnit"].ColumnIndex);
                     dgvProduct.Rows[e.RowIndex].Cells["dgvcmbUnit"].Value = Convert.ToDecimal(RowDetails["unitId"].ToString());
                     BatchComboFill(Convert.ToDecimal(RowDetails["productId"].ToString()), e.RowIndex, Convert.ToInt32(dgvProduct.Rows[e.RowIndex].Cells["dgvcmbBatch"].ColumnIndex));
                     dgvProduct.Rows[e.RowIndex].Cells["dgvcmbBatch"].Value = Convert.ToDecimal(RowDetails["batchId"].ToString());
                     GridGodownComboFill(Convert.ToDecimal(RowDetails["productId"].ToString()), e.RowIndex, dgvProduct.Rows[e.RowIndex].Cells["dgvcmbGodown"].ColumnIndex);
                     dgvProduct.Rows[e.RowIndex].Cells["dgvcmbGodown"].Value = Convert.ToDecimal(RowDetails["godownId"].ToString());
                     RackComboFill1(Convert.ToDecimal(RowDetails["godownId"].ToString()), e.RowIndex, dgvProduct.Rows[e.RowIndex].Cells["dgvcmbRack"].ColumnIndex);
                     dgvProduct.Rows[e.RowIndex].Cells["dgvcmbRack"].Value = Convert.ToDecimal(RowDetails["rackId"].ToString());
                     decimal decBatchId = Convert.ToDecimal(dgvProduct.Rows[e.RowIndex].Cells["dgvcmbBatch"].Value.ToString());
                     UnitConvertionBll bllUnitConvertion = new UnitConvertionBll();
                     List<DataTable> ListObj = new List<DataTable>();
                     ListObj = bllUnitConvertion.UnitConversionIdAndConRateViewallByProductId(dgvProduct.Rows[e.RowIndex].Cells["dgvtxtProductId"].Value.ToString());
                     foreach (DataRow drUnitByProduct in ListObj[0].Rows)
                     {
                         if (dgvProduct.Rows[e.RowIndex].Cells["dgvcmbUnit"].Value.ToString() == drUnitByProduct.ItemArray[0].ToString())
                         {
                             dgvProduct.Rows[e.RowIndex].Cells["dgvtxtUnitConversionId"].Value = Convert.ToDecimal(drUnitByProduct.ItemArray[2].ToString());
                             dgvProduct.Rows[e.RowIndex].Cells["dgvtxtConversionRate"].Value = Convert.ToDecimal(drUnitByProduct.ItemArray[3].ToString());
                         }
                     }
                     dgvProduct.Rows[e.RowIndex].Cells["dgvtxtRate"].Value = Math.Round(Convert.ToDecimal(RowDetails["salesRate"].ToString()), PublicVariables._inNoOfDecimalPlaces);
                     decCurrentConversionRate = Convert.ToDecimal(dgvProduct.Rows[e.RowIndex].Cells["dgvtxtConversionRate"].Value.ToString());
                     decCurrentRate = Convert.ToDecimal(dgvProduct.Rows[e.RowIndex].Cells["dgvtxtRate"].Value.ToString());
                     getProductRate(e.RowIndex, decProductId, decBatchId);
                 }
             }
             else
             {
                 dgvProduct.Rows[e.RowIndex].Cells["dgvtxtBarcode"].Value = string.Empty;
                 dgvProduct.Rows[e.RowIndex].Cells["dgvtxtProductId"].Value = string.Empty;
                 dgvProduct.Rows[e.RowIndex].Cells["dgvtxtProductCode"].Value = string.Empty;
                 dgvProduct.Rows[e.RowIndex].Cells["dgvtxtProductName"].Value = string.Empty;
                 dgvProduct.Rows[e.RowIndex].Cells["dgvcmbGodown"].Value = string.Empty;
                 dgvProduct.Rows[e.RowIndex].Cells["dgvcmbRack"].Value = string.Empty;
                 dgvProduct.Rows[e.RowIndex].Cells["dgvcmbUnit"].Value = string.Empty;
                 dgvProduct.Rows[e.RowIndex].Cells["dgvcmbBatch"].Value = string.Empty;
                 dgvProduct.Rows[e.RowIndex].Cells["dgvtxtUnitConversionId"].Value = string.Empty;
                 dgvProduct.Rows[e.RowIndex].Cells["dgvtxtConversionRate"].Value = string.Empty;
                 dgvProduct.Rows[e.RowIndex].Cells["dgvtxtRate"].Value = string.Empty;
                 dgvProduct.Rows[e.RowIndex].Cells["dgvtxtAmount"].Value = string.Empty;
                 dgvProduct.Rows[e.RowIndex].Cells["dgvtxtQty"].Value = string.Empty;
             }
         }
         else if (dgvProduct.Columns[e.ColumnIndex].Name == "dgvtxtProductCode")
         {
             isValueChange = false;
             isDoAfterGridFill = false;
             ProductDetailsFill(dgvProduct.CurrentRow.Index, "ProductCode");
         }
         else if (dgvProduct.Columns[e.ColumnIndex].Name == "dgvtxtProductName")
         {
             isValueChange = false;
             isDoAfterGridFill = false;
             ProductDetailsFill(dgvProduct.CurrentRow.Index, "ProductName");
         }
         else if (dgvProduct.Columns[e.ColumnIndex].Name == "dgvtxtRate")
         {
             if (dgvProduct.Rows[e.RowIndex].Cells["dgvtxtRate"].Value != null)
             {
                 if (dgvProduct.Rows[e.RowIndex].Cells["dgvtxtRate"].Value.ToString() != string.Empty)
                 {
                     DefaultRate = Convert.ToDecimal(dgvProduct.Rows[e.RowIndex].Cells["dgvtxtRate"].Value);
                 }
             }
         }
         AmountCalculation("dgvtxtQty", e.RowIndex);
         TotalAmountCalculation();
         isValueChange = true;
         isDoAfterGridFill = true;
         CheckInvalidEntries(e);
     }
     catch (Exception ex)
     {
         MessageBox.Show("DN68:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
        protected override void AttachChildControls()
        {
            this.hidSupplier             = (HtmlInputHidden)this.FindControl("hidSupplier");
            this.litSupplierName         = (Literal)this.FindControl("litSupplierName");
            this.divConsultationEmpty    = (HtmlGenericControl)this.FindControl("divConsultationEmpty");
            this.rptProductConsultations = (WapTemplatedRepeater)this.FindControl("rptProductConsultations");
            this.fightGroupRule          = (Common_FightGroupRule)this.FindControl("fightGroupRule");
            this.litDescription          = (Literal)this.FindControl("litDescription");
            this.litConsultationsCount   = (Literal)this.FindControl("litConsultationsCount");
            this.rptProductImages        = (WapTemplatedRepeater)this.FindControl("rptProductImages");
            this.divFightGroupsHead      = (HtmlControl)this.FindControl("divFightGroupsHead");
            this.skuSubmitOrder          = (Common_SKUSubmitOrder)this.FindControl("skuSubmitOrder");
            this.fightGroupActivityId    = this.Page.Request["fightGroupActivityId"].ToInt(0);
            this.litJoinNumber           = (Literal)this.FindControl("litJoinNumber");
            this.litLimitedHour          = (Literal)this.FindControl("litLimitedHour");
            this.litEndDate            = (Literal)this.FindControl("litEndDate");
            this.litProductName        = (Literal)this.FindControl("litProductName");
            this.litFGAPrice           = (Literal)this.FindControl("litFGAPrice");
            this.litPPrice             = (Literal)this.FindControl("litPPrice");
            this.litProductReviewCount = (Literal)this.FindControl("litProductReviewCount");
            this.imgEnd          = (Image)this.FindControl("imgEnd");
            this.hlProductReview = (HyperLink)this.FindControl("hlProductReview");
            this.rptFightGroups  = (WapTemplatedRepeater)this.FindControl("rptFightGroups");
            this.litMinPrice     = (Literal)this.FindControl("litMinPrice");
            this.litProductPrice = (Literal)this.FindControl("litProductPrice");
            this.lblStock        = (StockLabel)this.FindControl("lblStock");
            this.litUnit         = (Literal)this.FindControl("litUnit");
            this.divGetBySelf    = (HtmlControl)this.FindControl("divGetBySelf");
            this.hiddenProductId = (HtmlInputText)this.FindControl("hiddenProductId");
            this.hdAppId         = (HtmlInputHidden)this.FindControl("hdAppId");
            this.hdTitle         = (HtmlInputHidden)this.FindControl("hdTitle");
            this.hdDesc          = (HtmlInputHidden)this.FindControl("hdDesc");
            this.hdImgUrl        = (HtmlInputHidden)this.FindControl("hdImgUrl");
            this.hdLink          = (HtmlInputHidden)this.FindControl("hdLink");
            FightGroupActivityInfo fightGroupActivitieInfo = TradeHelper.GetFightGroupActivitieInfo(this.fightGroupActivityId);

            if (fightGroupActivitieInfo != null)
            {
                HtmlInputText htmlInputText = this.hiddenProductId;
                int           num           = fightGroupActivitieInfo.ProductId;
                htmlInputText.Value = num.ToString();
                this.fightGroupRule.FightGroupActivityId = fightGroupActivitieInfo.FightGroupActivityId;
                if (fightGroupActivitieInfo.StartDate > DateTime.Now)
                {
                    this.Page.Response.Redirect("FightGroupActivityDetailsSoon.aspx?fightGroupActivityId=" + this.fightGroupActivityId);
                }
                SiteSettings masterSettings = SettingsManager.GetMasterSettings();
                if (masterSettings.OpenMultStore && StoresHelper.ProductHasStores(fightGroupActivitieInfo.ProductId))
                {
                    this.divGetBySelf.Visible = true;
                }
                this.skuSubmitOrder.FightGroupActivityId = fightGroupActivitieInfo.FightGroupActivityId;
                IList <FightGroupSkuInfo> fightGroupSkus = VShopHelper.GetFightGroupSkus(this.fightGroupActivityId);
                this.hlProductReview.NavigateUrl = $"/vshop/ProductReview.aspx?ProductId={fightGroupActivitieInfo.ProductId}";
                this.imgEnd.Visible = (fightGroupActivitieInfo.EndDate < DateTime.Now);
                Literal literal = this.litJoinNumber;
                num          = fightGroupActivitieInfo.JoinNumber;
                literal.Text = num.ToString();
                Literal literal2 = this.litLimitedHour;
                num                      = fightGroupActivitieInfo.LimitedHour;
                literal2.Text            = num.ToString();
                this.litEndDate.Text     = fightGroupActivitieInfo.EndDate.ToString("yy.MM.dd");
                this.litProductName.Text = fightGroupActivitieInfo.ProductName;
                decimal num2 = fightGroupSkus.Min((FightGroupSkuInfo c) => c.SalePrice);
                this.litFGAPrice.Text = num2.F2ToString("f2");
                if (fightGroupSkus.Count() > 1)
                {
                    decimal num3 = fightGroupSkus.Max((FightGroupSkuInfo c) => c.SalePrice);
                    if (num3 > num2)
                    {
                        this.litFGAPrice.Text = num2.F2ToString("f2") + "~" + num3.F2ToString("f2");
                    }
                }
                this.litMinPrice.Text = num2.F2ToString("f2");
                IList <int> list = null;
                Dictionary <int, IList <int> > dictionary = default(Dictionary <int, IList <int> >);
                ProductInfo productDetails = ProductHelper.GetProductDetails(fightGroupActivitieInfo.ProductId, out dictionary, out list);
                if (productDetails != null)
                {
                    this.skuSubmitOrder.ProductInfo = productDetails;
                    this.litPPrice.Text             = MemberProcessor.GetMemberPrice(productDetails).F2ToString("f2");
                    this.litProductPrice.Text       = this.litPPrice.Text;
                }
                int supplierId = productDetails.SupplierId;
                if (supplierId > 0)
                {
                    SupplierInfo supplierById = SupplierHelper.GetSupplierById(supplierId);
                    if (supplierById != null)
                    {
                        this.hidSupplier.Value    = "true";
                        this.litSupplierName.Text = supplierById.SupplierName;
                    }
                }
                else
                {
                    this.hidSupplier.Value = "false";
                }
                Literal literal3 = this.litProductReviewCount;
                num = ProductBrowser.GetProductReviews(new ProductReviewQuery
                {
                    PageIndex = 1,
                    PageSize  = 2147483647,
                    ProductId = fightGroupActivitieInfo.ProductId
                }).TotalRecords;
                literal3.Text = num.ToString();
                DataTable fightGroups = VShopHelper.GetFightGroups(this.fightGroupActivityId);
                for (int i = 0; i < fightGroups.Rows.Count; i++)
                {
                    fightGroups.Rows[i]["Name"] = DataHelper.GetHiddenUsername(fightGroups.Rows[i]["Name"].ToString());
                }
                this.divFightGroupsHead.Visible = (fightGroups.Rows.Count > 0);
                this.rptFightGroups.DataSource  = fightGroups;
                this.rptFightGroups.DataBind();
                this.hdAppId.Value = base.site.WeixinAppId;
                if (string.IsNullOrEmpty(fightGroupActivitieInfo.ShareTitle))
                {
                    this.hdTitle.Value = (string.IsNullOrEmpty(productDetails.Title) ? productDetails.ProductName : productDetails.Title);
                }
                else
                {
                    this.hdTitle.Value = fightGroupActivitieInfo.ShareTitle.Trim();
                }
                if (string.IsNullOrEmpty(fightGroupActivitieInfo.ShareContent.Trim()))
                {
                    this.hdDesc.Value = productDetails.Meta_Description;
                }
                else
                {
                    this.hdDesc.Value = fightGroupActivitieInfo.ShareContent.Trim();
                }
                string local = string.IsNullOrEmpty(fightGroupActivitieInfo.Icon) ? SettingsManager.GetMasterSettings().DefaultProductImage : fightGroupActivitieInfo.Icon;
                this.hdImgUrl.Value = Globals.FullPath(local);
                this.hdLink.Value   = Globals.FullPath(this.Page.Request.Url.ToString());
                if (this.rptProductImages != null)
                {
                    string locationUrl = "javascript:;";
                    if (string.IsNullOrEmpty(productDetails.ImageUrl1) && string.IsNullOrEmpty(productDetails.ImageUrl2) && string.IsNullOrEmpty(productDetails.ImageUrl3) && string.IsNullOrEmpty(productDetails.ImageUrl4) && string.IsNullOrEmpty(productDetails.ImageUrl5))
                    {
                        productDetails.ImageUrl1 = masterSettings.DefaultProductImage;
                    }
                    DataTable         skus  = ProductBrowser.GetSkus(fightGroupActivitieInfo.ProductId);
                    List <SlideImage> list2 = new List <SlideImage>();
                    list2.Add(new SlideImage(productDetails.ImageUrl1, locationUrl));
                    list2.Add(new SlideImage(productDetails.ImageUrl2, locationUrl));
                    list2.Add(new SlideImage(productDetails.ImageUrl3, locationUrl));
                    list2.Add(new SlideImage(productDetails.ImageUrl4, locationUrl));
                    list2.Add(new SlideImage(productDetails.ImageUrl5, locationUrl));
                    this.rptProductImages.DataSource = from item in list2
                                                       where !string.IsNullOrWhiteSpace(item.ImageUrl)
                                                       select item;
                    this.rptProductImages.DataBind();
                    Literal control = this.litConsultationsCount;
                    num = ProductBrowser.GetProductConsultationsCount(productDetails.ProductId, false);
                    control.SetWhenIsNotNull(num.ToString());
                    if (this.litDescription != null)
                    {
                        string text  = "";
                        Regex  regex = new Regex("<script[^>]*?>.*?</script>", RegexOptions.IgnoreCase);
                        if (!string.IsNullOrWhiteSpace(productDetails.MobbileDescription))
                        {
                            text = regex.Replace(productDetails.MobbileDescription, "");
                        }
                        else if (!string.IsNullOrWhiteSpace(productDetails.Description))
                        {
                            text = regex.Replace(productDetails.Description, "");
                        }
                        text = text.Replace("src", "data-url");
                        this.litDescription.Text = text;
                    }
                    DataTable data = ProductBrowser.GetProductConsultations(new ProductConsultationAndReplyQuery
                    {
                        ProductId  = productDetails.ProductId,
                        PageIndex  = 1,
                        PageSize   = 2147483647,
                        SortOrder  = SortAction.Desc,
                        SortBy     = "ConsultationId",
                        HasReplied = true
                    }).Data;
                    for (int j = 0; j < data.Rows.Count; j++)
                    {
                        data.Rows[j]["UserName"] = DataHelper.GetHiddenUsername(data.Rows[j]["UserName"].ToNullString());
                    }
                    this.rptProductConsultations.DataSource = data;
                    this.rptProductConsultations.DataBind();
                    this.divConsultationEmpty.Visible = data.IsNullOrEmpty();
                }
            }
            else
            {
                base.GotoResourceNotFound("活动不存在");
            }
        }
예제 #59
0
 public void AssignProduct(ProductInfo product)
 {
     currentProduct = product;
     ResetProduct();
     if (product == null) return;
 }
예제 #60
0
    // 礼包
    private void initPeck()
    {
        showTabColor(ShopType.Peck);
        for (int i = 0; i < contentGo.transform.childCount; i++)
        {
            Destroy(contentGo.transform.GetChild(i).gameObject);
        }

        itemGo.Clear();

        Dictionary <int, string> products = new Dictionary <int, string>();

        foreach (PeckTable peckTable in Params.peckTables.Values)
        {
            products.Add(peckTable.Id, "s_" + peckTable.Price);
        }

        Purchaser.ins().InitializePurchasing(delegate(bool success) {
            if (success)
            {
                //
                Purchaser.ins().buyCallBack = buyCallBack;
                //
                Object shopItemObj         = Resources.Load("shopItem3");
                RectTransform contentTrans = contentGo.GetComponent <RectTransform>();
                contentTrans.sizeDelta     = new Vector2(0, 140 * Params.peckTables.Count);

                // goldMoneyRate
                ProductInfo onePi = Purchaser.ins().productInfos[1];
                PeckTable onePt   = Params.peckTables[1];
                goldMoneyRate     = onePi.price / onePt.goldNum;

                int index = 0;
                foreach (KeyValuePair <int, ProductInfo> pi in Purchaser.ins().productInfos)
                {
                    PeckTable peckTable = Params.peckTables[pi.Key];
                    GameObject go       = Instantiate(shopItemObj) as GameObject;

                    ShopItem si = go.GetComponent <ShopItem>();
                    si.shop     = this;
                    si.type     = ShopType.Peck;
                    si.id       = peckTable.Id;
                    si.gold     = peckTable.gold;
                    si.goldNum  = peckTable.goldNum;
                    si.items    = peckTable.Items;
                    //Mathf.
                    si.price = decimal.Round(calOriginPrice(peckTable.gold, peckTable.Items), 2);
                    //si.price = calOriginPrice(peckTable.gold, peckTable.Items);
                    si.price2 = decimal.Round(pi.Value.price, 2);
                    //si.price2 = pi.Value.price;//peckTable.Price;
                    si.isDiscount = true;

                    go.transform.localPosition = new Vector3(0, -140 * index++, 0);

                    go.transform.localScale = new Vector3(1, 1, 1);
                    go.transform.SetParent(contentGo.transform, false);
                }

                //int index = 0;
                //foreach (PeckTable peckTable in Params.peckTables.Values)
                //{
                //    GameObject go = Instantiate(shopItemObj) as GameObject;

                //    ShopItem si = go.GetComponent<ShopItem>();
                //    si.shop = this;
                //    si.type = ShopType.Peck;
                //    si.id = peckTable.Id;
                //    si.gold = peckTable.gold;
                //    si.goldNum = peckTable.goldNum;
                //    si.items = peckTable.Items;
                //    si.price = calOriginPrice(peckTable.gold, peckTable.Items);
                //    si.price2 = peckTable.Price;
                //    si.isDiscount = true;

                //    go.transform.localPosition = new Vector3(0, -140 * index++, 0);

                //    go.transform.localScale = new Vector3(1, 1, 1);
                //    go.transform.SetParent(contentGo.transform, false);
                //}
            }
        }, products);
    }