Exemple #1
0
        public ActionResult List(HttpPostedFileBase file)
        {
            try
            {
                Tools.Config.UploadConfig config = UploadProvice.Instance();
                SiteOption option   = config.SiteOptions["local"];
                string     filePath = option.Folder + config.Settings["file"].FilePath + DateTime.Now.ToString("yyyyMMddHHmmss")
                                      + (file.FileName.IndexOf(".xlsx") > 0 ? ".xlsx" : ".xls");

                string result = FileHelper.ValicationAndSaveFileToPath(file, filePath);
                if (result != "0")
                {
                    return(MessageBoxAndJump($"上传失败,{result}", "list"));
                }

                var    sheet = ExcelHelper.ReadExcel(filePath);
                string msg   = ExcelToList(sheet, 5);

                if (msg != "0")
                {
                    return(MessageBoxAndJump("导入失败," + GetMsg(msg), "list"));
                }
            }
            catch (Exception ex)
            {
                return(MessageBoxAndJump("导入失败:" + ex.Message.ToString(), "list"));
            }

            return(Redirect("list"));
        }
Exemple #2
0
        public static string GetProductUrl(string imgurl)
        {
            if (string.IsNullOrWhiteSpace(imgurl))
            {
                return(string.Empty);
            }

            imgurl = imgurl.Replace("\\", "/").TrimStart('/');
            var        ext           = Path.GetExtension(imgurl);
            string     url           = string.Empty;
            SiteOption option        = config.SiteOptions["files"];
            var        productConfig = config.Settings["product"];
            //图片
            string dirPath = option.Folder.TrimEnd('\\') + productConfig.FilePath + "upload\\";
            string imgPath = string.Concat(dirPath, imgurl.Replace("/", "\\"));

            if (ext == ".jpg" || ext == ".gif" || ext == ".jpeg" || ext == ".bmp" || ext == ".png")
            {
                if (option != null && productConfig != null)
                {
                    imgurl = "upload/" + imgurl;
                    url    = string.Concat(option.Url, productConfig.UrlFilePath, imgurl);
                    if (File.Exists(imgPath))
                    {
                        ProductImgQueueInfo queueInfo = new ProductImgQueueInfo();
                        queueInfo.ImgPath = imgPath;
                        queueInfo.ImgUrl  = imgurl;
                        ProdcutImgQueue.ProdcutImgQueueInstance.AddQueue(queueInfo);
                    }
                }
            }
            return(url);
        }
Exemple #3
0
        public ActionResult BatchImportExcel(HttpPostedFileBase file)
        {
            try
            {
                Tools.Config.UploadConfig config = UploadProvice.Instance();
                SiteOption option   = config.SiteOptions["local"];
                string     filePath = option.Folder + config.Settings["file"].FilePath + DateTime.Now.ToString("yyyyMMddHHmmss")
                                      + (file.FileName.IndexOf(".xlsx") > 0 ? ".xlsx" : ".xls");

                string result = FileHelper.ValicationAndSaveFileToPath(file, filePath);
                if (result != "0")
                {
                    return(MessageBoxAndJump($"上传失败,{result}", "list"));
                }

                var sheet     = ExcelHelper.ReadExcel(filePath);
                var modelList = BatchExcelToList(sheet, 1);

                if (modelList == null || modelList.Count < 1)
                {
                    return(MessageBoxAndJump("数据为空,导入失败!", "list"));
                }

                if (Bll.BllSupplier_List.Insert(modelList) < 1)
                {
                    return(MessageBoxAndJump("导入失败", "list"));
                }
            }
            catch (Exception ex)
            {
                return(MessageBoxAndJump("导入失败:" + ex.Message.ToString(), "list"));
            }

            return(Redirect("list"));
        }
Exemple #4
0
        private void ModifyRssOption()
        {
            SiteOption siteOption = SiteConfig.ConfigInfo().SiteOption;

            this.RssEnable.SelectedValue = this.SelectValue(siteOption.RssEnable);
            this.WapEnable.SelectedValue = this.SelectValue(siteOption.WapEnable);
        }
        public async Task <IActionResult> PutSiteOption(int id, SiteOption siteOption)
        {
            if (id != siteOption.Id)
            {
                return(BadRequest());
            }

            _context.Entry(siteOption).State = EntityState.Modified;

            try
            {
                var aesKey = EncryptProvider.CreateAesKey();
                var key    = aesKey.Key;
                var iv     = aesKey.IV;

                siteOption.SMTPPassword = $"{EncryptProvider.AESEncrypt(siteOption.SMTPPassword, key, iv)}.{key}.{iv}";
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!SiteOptionExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Exemple #6
0
 public void SiteOptionConstructorTest()
 {
     string section = string.Empty;
     string name = string.Empty;
     string value = "1";
     SiteOption.SiteOptionType type = SiteOption.SiteOptionType.Int;
     string description = string.Empty;
     var target = new SiteOption(DEFAULT_SITE_ID, section, name, value, type, description);
     Assert.AreEqual(type, target.OptionType);
 }
Exemple #7
0
        public void Start()//启动
        {
            option        = config.SiteOptions["files"];
            productConfig = config.Settings["product"];
            if (option != null && productConfig != null)
            {
                dirPath = option.Folder.TrimEnd('\\') + productConfig.FilePath;
            }
            Thread thread = new Thread(threadStart);

            thread.Start();
        }
Exemple #8
0
 public AccountService(
     IAuditBaseRepository <LinUser, long> userRepository,
     IEmailSender emailSender,
     IOptions <MailKitOptions> options,
     IUserIdentityService userIdentityService,
     IOptions <SiteOption> siteOption)
 {
     _userRepository      = userRepository;
     _emailSender         = emailSender;
     _mailKitOptions      = options.Value;
     _userIdentityService = userIdentityService;
     _siteOption          = siteOption.Value;
 }
Exemple #9
0
        public IActionResult Edit(IFormCollection collection)
        {
            var siteOption = new SiteOption()
            {
                // should probably check input is safe first
                Id    = int.Parse(collection["Id"]),
                Name  = collection["Name"],
                Value = collection["Value"],
                Type  = collection["Type"],
            };

            _context.SiteOptions.Update(siteOption);
            _context.SaveChanges();

            var model = _context.SiteOptions.ToList();

            return(View(model));
        }
Exemple #10
0
        public ActionResult SingleImportExcel(HttpPostedFileBase file)
        {
            try
            {
                Tools.Config.UploadConfig config = UploadProvice.Instance();
                SiteOption option   = config.SiteOptions["local"];
                string     filePath = option.Folder + config.Settings["file"].FilePath + DateTime.Now.ToString("yyyyMMddHHmmss")
                                      + (file.FileName.IndexOf(".xlsx") > 0 ? ".xlsx" : ".xls");

                string result = FileHelper.ValicationAndSaveFileToPath(file, filePath);
                if (result != "0")
                {
                    return(MessageBoxAndJump($"上传失败,{result}", "list"));
                }

                var sheet     = Tools.Tool.ExcelHelper.ReadExcel(filePath);
                var modelList = SingleExcelToList(sheet, 1, ref result);

                if (modelList == null)
                {
                    return(MessageBoxAndJump($"导入失败,{result}!", "list"));
                }

                result = Bll.BllSupplier_VendorInfo.AddVendorInfo(modelList);
                if (result != "0")
                {
                    return(MessageBoxAndJump("导入失败," + result, "list"));
                }
            }
            catch (Exception)
            {
                return(MessageBoxAndJump("导入失败:请联系管理员", "list"));
            }

            return(Redirect("list"));
        }
Exemple #11
0
 public void GetValueInt_ValidInt_ReturnsInt()
 {
     string section = string.Empty;
     string name = string.Empty;
     string value = "1";
     SiteOption.SiteOptionType type = SiteOption.SiteOptionType.Int;
     string description = string.Empty;
     SiteOption target = new SiteOption(DEFAULT_SITE_ID, section, name, value, type, description);
     int expected = 1;
     int actual = target.GetValueInt();
     Assert.AreEqual(expected, actual);
 }
        public ActionResult ImportProduct(HttpPostedFileBase file)
        {
            try
            {
                int classId = RequestInt("classId");
                if (classId == 0)
                {
                    return(LayerAlertErrorAndReturn("请选择一个分类!"));
                }
                var classModel = Bll.BllProduct_Class.First(o => o.Id == classId);
                if (classModel == null)
                {
                    return(LayerAlertErrorAndClose("分类不存在!"));
                }
                if (classModel.ChildNum > 0)
                {
                    return(LayerAlertErrorAndReturn("请选择一个最底层分类!"));
                }

                Tools.Config.UploadConfig config = UploadProvice.Instance();
                SiteOption option   = config.SiteOptions["local"];
                string     filePath = option.Folder + config.Settings["file"].FilePath + DateTime.Now.ToString("yyyyMMddHHmmss")
                                      + (file.FileName.IndexOf(".xlsx") > 0 ? ".xlsx" : ".xls");

                string result = FileHelper.ValicationAndSaveFileToPath(file, filePath);
                if (result != "0")
                {
                    return(MessageBoxAndReturn($"上传失败,{result}!"));
                }

                var sheet = Tools.Tool.ExcelHelper.ReadExcel(filePath);
                if (sheet == null)
                {
                    return(MessageBoxAndReturn($"Excel读取失败,请检查格式!"));
                }
                if (sheet.LastRowNum < 1)
                {
                    return(MessageBoxAndReturn($"Excel无数据!"));
                }

                int succuessCount        = 0;
                List <Product_Info> list = new List <Product_Info>();
                IRow row;
                for (int i = 1; i <= sheet.LastRowNum; i++) //从第二行开始读取
                {
                    row = sheet.GetRow(i);                  //第i行数据
                    if (row != null)
                    {
                        string title = row.GetCell(0)?.ToString();
                        if (string.IsNullOrEmpty(title))
                        {
                            continue;                              //标题为空,跳过
                        }
                        if (Bll.BllProduct_Info.Any(o => o.Title == title))
                        {
                            continue;                                                 //标题和老SPU已存在,跳过
                        }
                        //产品Spu
                        var    classIds = classModel.ParPath.TrimEnd(',').Split(',');
                        string spu      = Bll.BllProduct_Class.GetSpuCode(classId);
                        if (string.IsNullOrEmpty(spu))
                        {
                            continue;                            //spu编码生成失败,跳过
                        }
                        if (Bll.BllProduct_Info.IsExistsSpu(spu))
                        {
                            continue;                                       //Spu重复,跳过
                        }
                        string titleEn       = row.GetCell(1)?.ToString();
                        string oldSpu        = row.GetCell(2)?.ToString();
                        string supplierCode  = row.GetCell(3)?.ToString();
                        string supplierName  = row.GetCell(4)?.ToString();
                        string specification = row.GetCell(5)?.ToString();
                        string priceRemark   = row.GetCell(6)?.ToString();
                        string hsCode        = row.GetCell(7)?.ToString();
                        string InvoiceName   = row.GetCell(8)?.ToString();
                        string firstPic      = row.GetCell(9)?.ToString();
                        var    model         = new Product_Info()
                        {
                            ClassId_1           = classIds.Length > 0 ? classIds[0].ToInt32() : 0,
                            ClassId_2           = classIds.Length > 1 ? classIds[1].ToInt32() : 0,
                            ClassId             = classModel.Id,
                            ClassParPath        = classModel.ParPath,
                            Title               = title,
                            Title_En            = titleEn,
                            IsShow              = true,
                            Old_Spu             = oldSpu,
                            Spu                 = spu,
                            SupplierProductCode = supplierCode,
                            SupplierName        = supplierName,
                            Specification       = specification,
                            PriceRemark         = priceRemark,
                            HS_Code             = hsCode,
                            InvoiceName         = InvoiceName,
                            AdminId             = MyInfo.Id,
                            CreateDate          = DateTime.Now,
                            PriceUnit           = "$",
                            Currency            = "USD",
                            Price               = 0,
                            TaxPrice            = 0,
                            Moq                 = 1,
                            FirstPic            = ImgConfig.GetProductUrl(firstPic)
                        };
                        if (Bll.BllProduct_Info.Insert(model) > 0)
                        {
                            succuessCount++;
                        }
                    }
                }
                if (succuessCount > 0)
                {
                    return(MessageBoxAndReturn("导入成功!"));
                }
                else
                {
                    return(MessageBoxAndReturn("导入失败,请联系管理员!"));
                }
            }
            catch (Exception ex)
            {
                Tools.Tool.LogHelper.WriteLog(typeof(ProductController), ex, MyInfo.Id, MyInfo.RealName);
                return(MessageBoxAndReturn("导入失败,请联系管理员!" + ex));
            }
        }
Exemple #13
0
 public void GetValueString_ValidString_ReturnsString()
 {
     string section = string.Empty;
     string name = string.Empty;
     string value = "1";
     SiteOption.SiteOptionType type = SiteOption.SiteOptionType.String;
     string description = string.Empty;
     SiteOption target = new SiteOption(DEFAULT_SITE_ID, section, name, value, type, description);
     string expected = "1";
     string actual = target.GetValueString();
     Assert.AreEqual(expected, actual);
 }
Exemple #14
0
        public ActionResult ImportProduct(HttpPostedFileBase file)
        {
            try
            {
                int contractId = RequestInt("contractId");
                if (contractId == 0)
                {
                    return(LayerAlertErrorAndReturn("请选择一个合同!"));
                }
                var contract = Bll.BllOrder_Contract.First(o => o.Id == contractId);
                if (contract == null)
                {
                    return(LayerAlertErrorAndClose("合同不存在!"));
                }

                Tools.Config.UploadConfig config = UploadProvice.Instance();
                SiteOption option   = config.SiteOptions["local"];
                string     filePath = option.Folder + config.Settings["file"].FilePath + DateTime.Now.ToString("yyyyMMddHHmmss")
                                      + (file.FileName.IndexOf(".xlsx") > 0 ? ".xlsx" : ".xls");

                string result = FileHelper.ValicationAndSaveFileToPath(file, filePath);
                if (result != "0")
                {
                    return(MessageBoxAndReturn($"上传失败,{result}!"));
                }

                var sheet = Tools.Tool.ExcelHelper.ReadExcel(filePath);
                if (sheet == null)
                {
                    return(MessageBoxAndReturn($"Excel读取失败,请检查格式!"));
                }

                int updateCount = 0;
                List <Order_ContractProduct> list = new List <Order_ContractProduct>();
                IRow row;
                for (int i = 1; i <= sheet.LastRowNum; i++) //从第二行开始读取
                {
                    row = sheet.GetRow(i);                  //第i行数据
                    if (row != null)
                    {
                        var name = row.GetCell(0).ToString();
                        if (!string.IsNullOrEmpty(name))
                        {
                            var price    = row.GetCell(1).ToString().ToDecimal();
                            var quantity = row.GetCell(2).ToString().ToInt32();
                            var model    = Bll.BllOrder_ContractProduct.First(o => o.Name == name && o.ContractId == contractId);
                            if (model != null)
                            {
                                model.Quantity  += quantity;
                                model.Price     += price;
                                model.TotalPrice = model.Quantity * model.Price;
                                if (Bll.BllOrder_ContractProduct.Update(model) > 0)
                                {
                                    updateCount++;
                                }
                            }
                            else
                            {
                                list.Add(new Order_ContractProduct()
                                {
                                    ContractId = contractId,
                                    Name       = name,
                                    Price      = price,
                                    Quantity   = quantity,
                                    TotalPrice = price * quantity,
                                    AddTime    = DateTime.Now,
                                    AdminId    = MyInfo.Id
                                });
                            }
                        }
                    }
                }
                if (Bll.BllOrder_ContractProduct.Insert(list) > 0 || updateCount > 0)
                {
                    return(MessageBoxAndReturn("导入成功!"));
                }
                else
                {
                    return(MessageBoxAndReturn("导入失败,请联系管理员!"));
                }
            }
            catch (Exception ex)
            {
                return(MessageBoxAndReturn("导入失败,请联系管理员!"));
            }
        }
Exemple #15
0
        private void UpdateBooleanSiteOption(int siteID, string section, string name, string value, string description)
        {
            IDnaDataReaderCreator readerCreator;
            SetupDataBaseMockedDataReaderCreator(out readerCreator);

            SiteOption updatedSiteOption = new SiteOption(siteID, section, name, value, SiteOption.SiteOptionType.Bool, description);
            List<SiteOption> updatedSiteoptions = new List<SiteOption>();
            updatedSiteoptions.Add(updatedSiteOption);
            SiteOption.UpdateSiteOptions(updatedSiteoptions, readerCreator);
        }
Exemple #16
0
        public void ShouldRemoveSiteOptionForSite()
        {
            IDnaDataReaderCreator readerCreator;
            SetupDataBaseMockedDataReaderCreator(out readerCreator);

            string section = "General";
            string name = "IsURLFiltered";
            string description = "Set if this site is to be url filtered";
            int siteID = 1;

            // Check the option exists first
            GetValueForGivenSiteOptionAssertFail(readerCreator, section, name, siteID, true);

            SiteOption siteOption = new SiteOption(siteID, section, name, "0", SiteOption.SiteOptionType.Bool, description);
            SiteOption.RemoveSiteOptionFromSite(siteOption, siteID, readerCreator);
            GetValueForTheSpecificSiteSiteOptionAssertFail(readerCreator, section, name, siteID, false);
        }
Exemple #17
0
        public void ShouldUpdateSiteOptionsWithValidUpdateOption()
        {
            IDnaDataReaderCreator readerCreator;
            SetupDataBaseMockedDataReaderCreator(out readerCreator);

            string section = "General";
            string name = "SiteIsPrivate";
            string description = "If true, this site's content won't get pulled out on lists in any other site";
            int siteID = 1;
            int changeToValue = GetValueForGivenSiteOptionAssertFail(readerCreator, section, name, siteID, true) == 1 ? 0 : 1;

            SiteOption siteOption = new SiteOption(siteID, section, name, changeToValue.ToString(), SiteOption.SiteOptionType.Bool, description);
            List<SiteOption> updatedSiteoptions = new List<SiteOption>();
            updatedSiteoptions.Add(siteOption);

            SiteOption.UpdateSiteOptions(updatedSiteoptions, readerCreator);
            int storedValue = GetValueForGivenSiteOptionAssertFail(readerCreator, section, name, siteID, true);

            Assert.AreEqual(changeToValue, storedValue);
        }
Exemple #18
0
        public void GetValueString_InvalidString_ThrowsException()
        {
            string section = string.Empty;
            string name = string.Empty;
            string value = "1";
            SiteOption.SiteOptionType type = SiteOption.SiteOptionType.Bool;
            string description = string.Empty;
            SiteOption target = new SiteOption(DEFAULT_SITE_ID, section, name, value, type, description);

            try
            {
                target.GetValueString();
                throw new Exception("GetValueString should throw exception");
            }
            catch (SiteOptionInvalidTypeException)
            {
            }
        }
Exemple #19
0
        public void SetValueBool_NotBoolType_ThrowsException()
        {
            string section = string.Empty;
            string name = string.Empty;
            string value = "1";
            SiteOption.SiteOptionType type = SiteOption.SiteOptionType.Int;
            string description = string.Empty;
            SiteOption target = new SiteOption(DEFAULT_SITE_ID, section, name, value, type, description);

            try
            {
                target.SetValueBool(true);
                throw new Exception("SetValueBool should throw exception");
            }
            catch (SiteOptionInvalidTypeException)
            {
            }
        }
 public NamedOptionsController(IOptionsMonitor <SiteOption> options)
 {
     site1 = options.Get("Site1");
     site2 = options.Get("Site2");
 }
Exemple #21
0
 public void GetValueInt_InvalidInt_ThrowsException()
 {
     string section = string.Empty;
     string name = string.Empty;
     string value = "0";
     SiteOption.SiteOptionType type = SiteOption.SiteOptionType.Bool;
     string description = string.Empty;
     SiteOption target = new SiteOption(DEFAULT_SITE_ID, section, name, value, type, description);
     bool actual = target.GetValueBool();
     Assert.IsFalse(actual);
     try
     {
         target.GetValueInt();
         throw new Exception("GetValueInt should throw exception");
     }
     catch (SiteOptionInvalidTypeException)
     {
     }
 }
Exemple #22
0
 public void GetRawValue_ValidInt_ReturnsIntString()
 {
     string section = string.Empty;
     string name = string.Empty;
     string value = "1";
     SiteOption.SiteOptionType type = SiteOption.SiteOptionType.Int;
     string description = string.Empty;
     SiteOption target = new SiteOption(DEFAULT_SITE_ID, section, name, value, type, description);
     Assert.AreEqual(value, target.GetRawValue());
 }
Exemple #23
0
        public void GetValueBool_InvalidBool_ThrowsException()
        {
            string section = string.Empty;
            string name = string.Empty;
            string value = "1";
            SiteOption.SiteOptionType type = SiteOption.SiteOptionType.Int;
            string description = string.Empty;
            SiteOption target = new SiteOption(DEFAULT_SITE_ID, section, name, value, type, description);
            int expected = 1;
            int actual = target.GetValueInt();
            Assert.AreEqual(expected, actual);

            try
            {
                target.GetValueBool();
                throw new Exception("GetValueBool should throw exception");
            }
            catch (SiteOptionInvalidTypeException)
            {
            }
        }
        public object UploadFile()
        {
            string uptype    = HttpContext.Current.Request["uptype"].Trim2();     //获取上传配置
            string checkCode = HttpContext.Current.Request["checkCode"].Trim2();  // 验证权限
            string key       = HttpContext.Current.Request["key"].Trim2();        // 验证权限
            string id        = HttpContext.Current.Request["id"].Trim2();         //文件Id
            string name      = HttpContext.Current.Request["name"].Trim2();       //源文件名
            string domain    = HttpContext.Current.Request["domain"].Trim2();     //文件域
            string title     = HttpContext.Current.Request["title"].Trim2();      //文件标题
            bool   isproduct = HttpContext.Current.Request["Isproduct"].ToBool(); //是否是产品图片
            int    proid     = HttpContext.Current.Request["proid"].ToInt32();    //产品Id
            byte   imagetype = HttpContext.Current.Request["imagetype"].ToByte(); //图片类型

            string status = "success";

            if (HttpContext.Current.Request.Files.Count == 0)
            {
                return(Json(new { code = 0, id = id, name = name, url = "", msg = "please select files" }));
            }
            try
            {
                if (!Core.Crypt.WebKey.KeyCheck2(key, checkCode))
                {
                    status = "验证出错!";
                    goto result;
                }
                if (uptype == "")
                {
                    status = "上传配置丢失!";
                    goto result;
                }
                else
                {
                    //读取当前网站上传配置
                    SiteOption option = config.SiteOptions[domain];
                    if (option == null)
                    {
                        status = "没有找到当前网站配置!";
                        goto result;
                    }
                    //读取图片类型配置
                    Setting setting = config.Settings[uptype];
                    if (setting == null)
                    {
                        status = "没有找到当前配置!";
                        goto result;
                    }
                    else
                    {
                        //检测上传限制
                        HttpPostedFile fileUpload = HttpContext.Current.Request.Files[0];

                        #region 文件格式大小检测
                        if (fileUpload == null)
                        {
                            status = "请选择上传文件!";
                            goto result;
                        }
                        if (string.IsNullOrEmpty(fileUpload.FileName))
                        {
                            status = "请选择上传文件!";
                            goto result;
                        }
                        if (fileUpload.ContentLength <= 0)
                        {
                            status = "请选择上传文件!";
                            goto result;
                        }
                        //检测文件大小是否超过限制
                        if (fileUpload.ContentLength > setting.MaxFileSize)
                        {
                            status = "上传文件超过大小限制!";
                            goto result;
                        }
                        //检测文件类型
                        string fileExt = Path.GetExtension(fileUpload.FileName).ToLower();
                        if (string.IsNullOrEmpty(fileExt))
                        {
                            status = "文件类型出错!";
                            goto result;
                        }
                        else
                        {
                            bool     allowUploadExt = false;
                            string   allUploadExts  = setting.AllowUpload;
                            string[] exps           = allUploadExts.Split('|');
                            foreach (string exp in exps)
                            {
                                if (exp.ToLower() == fileExt)
                                {
                                    allowUploadExt = true;
                                    break;
                                }
                            }
                            if (!allowUploadExt)
                            {
                                status = "文件类型出错!";
                                goto result;
                            }
                        }

                        //判断是否是文件类型
                        bool isFile = true;
                        if (fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".jpeg" || fileExt == ".bmp" || fileExt == ".png")
                        {
                            isFile = false;
                        }
                        #endregion

                        #region MD5对比
                        //数据库md5检测
                        string md5 = Tools.Security.Md5Helper.GetMd5HashFromFile(fileUpload.InputStream);
                        if (isproduct && !string.IsNullOrEmpty(md5))
                        {
                            string url = string.Empty;
                            //判断数据库记录是否存在
                            bool isExist = isFile ?
                                           Bll.BllProduct_Files.GetFileUrlByMd5(md5, ref url) :
                                           Bll.BllProduct_Image.GetImageUrlByMd5(md5, ref url, imagetype);
                            if (isExist)
                            {
                                //判断真实文件是否存在
                                string filePath = option.Folder.TrimEnd('\\') + url.Replace(option.Url, "").Replace("/", "\\");
                                if (File.Exists(filePath))
                                {
                                    return(Json(new FileResult()
                                    {
                                        code = 1, id = id, name = name, url = url, msg = status
                                    }));
                                }
                            }
                        }
                        #endregion

                        string saveDoc     = DateTime.Now.ToString(@"yy\\MM\\");
                        string rndFileName = Tools.Usual.Common.GetDataShortRandom();

                        //如果文件需要标题,则在路径中添加标题
                        //if (!string.IsNullOrEmpty(title))
                        //{
                        //    rndFileName = Tools.Usual.Utils.ConverUrl(Tools.Common.StringProcess.CutString(title, 50)).TrimEnd('-') + "-" + rndFileName;
                        //}

                        #region 文件名处理
                        //文件名
                        string fileName = Tools.Usual.Utils.GetFileName(name);

                        //文件名有中文则强制转拼音
                        if (Tools.Chinese.HasChinese(fileName))
                        {
                            fileName = Tools.Usual.Hz2Py.Convert(fileName);
                        }

                        //字数限制
                        if (fileName.Length > 60)
                        {
                            fileName = Tools.Usual.Common.CutString(fileName, 60);
                        }

                        rndFileName = Tools.Usual.Utils.ConverUrl(fileName).Replace("_", "-").TrimEnd('-') + "-" + rndFileName;

                        #endregion

                        //获取绝对路径
                        string dirPath     = option.Folder.TrimEnd('\\') + setting.FilePath;
                        string newFileName = saveDoc + rndFileName + fileExt;
                        if (status == "success")
                        {
                            #region 保存文件

                            if (!Directory.Exists(dirPath + saveDoc))
                            {
                                Directory.CreateDirectory(dirPath + saveDoc);
                            }
                            // 文件上传
                            fileUpload.SaveAs(dirPath + newFileName);

                            //如果上传图片,则执行图片配置选项.
                            if (!isFile)
                            {
                                // 限制图片大小
                                Tools.Tool.ImageTools.SetImgSize(dirPath + newFileName, setting.MaxWidth, setting.MaxHeight);

                                //不同大小的图片名
                                string newBigFileName    = saveDoc + rndFileName + "b" + fileExt;
                                string newMiddleFileName = saveDoc + rndFileName + "m" + fileExt;
                                string newMinFileName    = saveDoc + rndFileName + "xs" + fileExt;
                                string newSmallFileName  = saveDoc + rndFileName + "s" + fileExt;

                                //生成缩略图
                                if (setting.CreateMinPic)
                                {
                                    ImageTools.CreateSmallImage(dirPath + newFileName, dirPath + newMinFileName, setting.MinWidth, setting.MinHeight);
                                }
                                //生成小图
                                if (setting.CreateSmallPic)
                                {
                                    ImageTools.CreateSmallImage(dirPath + newFileName, dirPath + newSmallFileName, setting.Width, setting.Height);
                                }
                                //生成中图
                                if (setting.CreateMiddlePic)
                                {
                                    ImageTools.CreateSmallImage(dirPath + newFileName, dirPath + newMiddleFileName, setting.MiddleWidth, setting.MiddleHeight);
                                }
                                //生成大图
                                if (setting.CreateBigPic)
                                {
                                    ImageTools.CreateSmallImage(dirPath + newFileName, dirPath + newBigFileName, setting.BigWidth, setting.BigHeight);
                                }
                                //打水印
                                if (setting.AddWaterMark)
                                {
                                    WaterMarkType wmtype;
                                    string        waterMarkImgOrTxt;
                                    if (setting.WaterMarkType == "image")
                                    {
                                        wmtype            = WaterMarkType.ImageMark;
                                        waterMarkImgOrTxt = HttpContext.Current.Server.MapPath(setting.WaterMarkImgOrTxt);
                                    }
                                    else
                                    {
                                        wmtype            = WaterMarkType.TextMark;
                                        waterMarkImgOrTxt = setting.WaterMarkImgOrTxt;
                                    }

                                    //原图和大图打水印
                                    //Tools.Tool.ImageTools.AddWaterMark(dirPath + newFileName, dirPath + newFileName, waterMarkImgOrTxt, wmtype, WaterMarkPosition.Right_Bottom, setting.Transparency);
                                    Tools.Tool.ImageTools.AddWaterMark(dirPath + newBigFileName, dirPath + newBigFileName, waterMarkImgOrTxt, wmtype, WaterMarkPosition.Right_Bottom, setting.Transparency);
                                }
                            }
                            #endregion
                        }

                        // 返回url
                        string urlRealm    = setting.UrlFilePath;
                        string urlFile     = urlRealm + newFileName.Replace(@"\", @"/"); //相对路径
                        string urlComplete = option.Url + urlFile;                       //完整路径

                        #region 保存到数据库
                        //文件记录到数据库
                        if (isproduct && !string.IsNullOrEmpty(md5))
                        {
                            if (isFile)
                            {
                                Bll.BllProduct_Files.Insert(new Model.Product_Files()
                                {
                                    FileSize = fileUpload.ContentLength,
                                    FilePath = urlComplete,
                                    FileExt  = fileExt.TrimStart('.'),
                                    FileName = name,
                                    Md5      = md5,
                                    AddTime  = DateTime.Now,
                                    ProId    = proid
                                });
                            }
                            else
                            {
                                Bll.BllProduct_Image.Insert(new Model.Product_Image()
                                {
                                    FileSize     = fileUpload.ContentLength,
                                    ImagePath    = urlComplete,
                                    ImageExt     = fileExt.TrimStart('.'),
                                    BigWidth     = setting.BigWidth,
                                    BigHeight    = setting.BigHeight,
                                    MiddleWidth  = setting.MiddleWidth,
                                    MiddleHeight = setting.MiddleHeight,
                                    SmallWidth   = setting.Width,
                                    SmailHeight  = setting.Height,
                                    MinWidth     = setting.MinWidth,
                                    MinHeight    = setting.MinHeight,
                                    Md5          = md5,
                                    AddTime      = DateTime.Now,
                                    ProId        = proid,
                                    Type         = imagetype
                                });
                            }
                        }
                        #endregion

                        return(Json(new FileResult()
                        {
                            code = 1, id = id, name = name, url = urlComplete, msg = status
                        }));
                    }
                }
            }
            catch (Exception ex)
            {
                return(Json(new FileResult()
                {
                    code = -1, id = id, name = name, url = "", msg = ex.ToString()
                }));
            }
result:
            return(Json(new FileResult()
            {
                code = 0, id = id, name = name, url = "", msg = status
            }));
        }
Exemple #25
0
 public void GetValueBool_ValidBool_ReturnsBool()
 {
     string section = string.Empty;
     string name = string.Empty;
     string value = "1";
     SiteOption.SiteOptionType type = SiteOption.SiteOptionType.Bool;
     string description = string.Empty;
     SiteOption target = new SiteOption(DEFAULT_SITE_ID, section, name, value, type, description);
     bool actual = target.GetValueBool();
     Assert.IsTrue(actual);
 }