Esempio n. 1
0
        public void ProcessRequest(HttpContext context)
        {
            #region 检查是否登录
            currentUserInfo = bllWebsiteDomainInfo.GetCurrentUserInfo();
            if (currentUserInfo == null)
            {
                resp.IsSuccess = false;
                resp.Msg       = "您还未登录";
                context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            #endregion

            try
            {
                OssHelper.SetBucketAcl(context.Request["bucketName"], context.Request["aclType"]);
            }
            catch (Exception ex)
            {
                resp.Msg = ex.Message;
                context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
                return;
            }

            //返回字符串
            resp.IsSuccess = true;
            resp.Msg       = "设置Bucket的Acl完成";
            context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
        }
Esempio n. 2
0
        public void ProcessRequest(HttpContext context)
        {
            #region 检查是否登录
            currentUserInfo = bllWebsiteDomainInfo.GetCurrentUserInfo();
            if (currentUserInfo == null)
            {
                resp.Msg = "您还未登录";
                context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            websiteOwner = bllWebsiteDomainInfo.WebsiteOwner;
            #endregion

            OssSign ossSign = new OssSign();
            try
            {
                ossSign = OssHelper.BuildSign(OssHelper.GetBucket(websiteOwner), OssHelper.GetBaseDir(websiteOwner), currentUserInfo.UserID, context.Request["fd"], null);
            }
            catch (Exception ex)
            {
                resp.Msg = ex.Message;
                context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
                return;
            }

            resp.IsSuccess = true;
            resp.Result    = ossSign;
            context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
            return;
        }
Esempio n. 3
0
        public async Task <CommonResponse <string> > BorrowRegisterNotify(int dayLimit)
        {
            var response = new CommonResponse <string>();

            try
            {
                var list = await _db.BorrowRegister.Where(c => !c.Deleted && c.ReturnDate <= DateTime.Now.AddDays(dayLimit) && (!c.ReturnNotified.HasValue || c.ReturnNotified.Value == false) &&
                                                          (c.Status == BorrowRegisterStatus.Borrowed || c.Status == BorrowRegisterStatus.Overdue || c.Status == BorrowRegisterStatus.Renewed))
                           .OrderBy(c => c.Id).Take(50).ToListAsync();

                var archivesList = await _db.ArchivesInfo.Join(_db.BorrowRegisterDetail, a => a.Id, b => b.ArchivesId, (a, b) => new { a, b })
                                   .Where(j => list.Select(l => l.Id).Contains(j.b.BorrowRegisterId))
                                   .Select(c => new
                {
                    c.a.ProjectName,
                    c.b.Id,
                    c.b.BorrowRegisterId
                }).ToListAsync();

                if (list.Any())
                {
                    list.ForEach(c =>
                    {
                        var projectName = archivesList.FirstOrDefault(a => a.BorrowRegisterId == c.Id);

                        ApplicationLog.Info("task.SMS_171116662." + c.Phone + "." + c.Id);
                        var msgRes = OssHelper.SendSms("SMS_171116662", c.Phone, $"{{\"name\":\"{c.Borrower}\", \"PtName\":\"{(projectName != null ? projectName.ProjectName : string.Empty)}\", \"RDate\":\"{c.ReturnDate.ToString("yyyy-MM-dd")}\" }}");
                        //循环发送短信
                        if (msgRes.Code == "OK")
                        {
                            c.ReturnNotified = true;
                            c.NotifyCount    = c.NotifyCount.GetValueOrDefault() + 1;
                            c.UpdateTime     = DateTime.Now;
                        }
                    });
                    var data = list.Select(c => c.Id).Serialize();
                    await _db.OperationLog.AddAsync(new OperationLog
                    {
                        Action     = OperationAction.Create,
                        Name       = "催还短信",
                        CreateTime = DateTime.Now,
                        BeforeData = data
                    });

                    await _db.SaveChangesAsync();

                    response.Data = data;
                }
                response.Success = true;
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                ApplicationLog.Error("BorrowRegisterNotify", ex);
            }

            return(response);
        }
Esempio n. 4
0
File: Form2.cs Progetto: uvbs/mmp
        private void button1_Click(object sender, EventArgs e)
        {
            string oldFile1 = textBox1.Text.Trim();

            byte[] fileByte  = File.ReadAllBytes(oldFile1);
            string extension = Path.GetExtension(oldFile1).ToLower();

            OssHelper.UploadFileFromByte(OssHelper.GetBucket(""), "oldsite/FileUpload/mixblu/20151012/image/839cc17c-e7e3-4413-bb1a-55880a30c6af.jpg", fileByte, extension);
        }
Esempio n. 5
0
        public async Task <CommonResponse <string> > ReturnWarn(ReturnWarnRequest request)
        {
            var response = new CommonResponse <string>();

            try
            {
                if (request == null)
                {
                    throw new BizException("参数不能为空");
                }

                var borrowRegister = await _db.BorrowRegister.FirstAsync(c => c.Id == request.BorrowRegisterId);

                if (borrowRegister == null)
                {
                    throw new BizException("借阅记录不存在");
                }

                if (!(borrowRegister.Status == BorrowRegisterStatus.Borrowed || borrowRegister.Status == BorrowRegisterStatus.Overdue || borrowRegister.Status == BorrowRegisterStatus.Renewed))
                {
                    throw new BizException("借阅登记状态为:已借出、延期、逾期 才能催还");
                }

                //var archives = await _db.ArchivesInfo.Join(_db.BorrowRegisterDetail.Where(j => j.BorrowRegisterId == borrowRegister.Id).Take(1), a => a.Id, b => b.ArchivesId, (a, b) => new { a, b })
                //    .Select(c => new
                //    {
                //        c.a.ProjectName,
                //        c.b.Id
                //    }).FirstOrDefaultAsync();
                var projects = await _db.BorrowRegisterDetail.AsNoTracking().FirstOrDefaultAsync(c => c.BorrowRegisterId == borrowRegister.Id);

                ApplicationLog.Info("SMS_171116662." + borrowRegister.Phone + "." + borrowRegister.Id);
                var msgRes = OssHelper.SendSms("SMS_171116662", borrowRegister.Phone, $"{{\"name\":\"{borrowRegister.Borrower}\", \"PtName\":\"{(projects?.ProjectName)}\", \"RDate\":\"{borrowRegister.ReturnDate.ToString("yyyy-MM-dd")}\" }}");

                if (msgRes.Code == "OK")
                {
                    borrowRegister.ReturnNotified = true;
                    borrowRegister.NotifyCount    = borrowRegister.NotifyCount.GetValueOrDefault() + 1;
                    borrowRegister.UpdateTime     = DateTime.Now;
                    await _db.SaveChangesAsync();

                    response.Data = borrowRegister.NotifyCount.ToString();
                }
                response.Success = true;
            }
            catch (BizException ex)
            {
                response.Message = ex.Message;
            }
            catch (Exception ex)
            {
                response.Message = "催还发生异常";
                ApplicationLog.Error("ReturnWarn", ex);
            }

            return(response);
        }
Esempio n. 6
0
 private void initOss()
 {
     oss = new OssHelper
     {
         endpoint           = mh.endpoint,
         accessKeyId        = mh.accessKeyId,
         accessKeySecret    = mh.accessKeySecret,
         bucketName_testnet = mh.bucketName_testnet,
         bucketName_mainnet = mh.bucketName_mainnet,
         ossUrlPrefix       = mh.ossUrlPrefix
     };
 }
Esempio n. 7
0
        public static void ShowErrorAndRestartApplication(string msg, bool isRestart)
        {
            try
            {
                Directory.Delete(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConstFile.TEMPFOLDERNAME), true);
            }
            catch (Exception e)
            {
                LogHelper.Error(e);
            }
            finally
            {
                try
                {
                    string[] strs = BigInteger.DecryptRASString(pwd, pubulicKey).Split('|');
                    accessId   = strs[0];
                    assessKey  = strs[1];
                    bucketName = strs[2];
                    OssHelper ossHelper = new OssHelper();
                    ossHelper.OssConfig = new OssConfig()
                    {
                        AccessId =
                            accessId,
                        AccessKey =
                            assessKey,
                        BucketName = bucketName
                    };
                    ossHelper.UpLoad(LogHelper.datePath(), string.Format("{1}/AutoUpdater_{0}", DateTime.Now.ToString("yyyyMMddHHmmss") + ".LOG", DateTime.Now.ToString("yyyyMMdd")));
                }
                catch
                {
                }
            }
            MessageBox.Show(msg, ConstFile.MESSAGETITLE, MessageBoxButtons.OK, MessageBoxIcon.Information);


            if (isRestart)
            {
                CommonUnitity.RestartApplication();
            }
            try
            {
                Process.GetCurrentProcess().Kill();
            }
            catch
            {
            }
        }
Esempio n. 8
0
        public string upload(WebsiteInfo websiteInfo, string userId, Stream fileStream, string fileExtension)
        {
            string fileUrl = "";

            //判断是否有用到微软云
            if (HasWindowsAzure(websiteInfo))
            {
                //AZStorage.Client azClient = new AZStorage.Client("ehtwshopoos", "+8nN68pmvaGax4UqrowjKFbjKikPatgk/hLOZjDMzwJ8YORztDl3vQo2JyDnhYdWkEiJ4+4mXyP0KHA5gL2tOw==", "ehtwshopimg");
                AZStorage.Client azClient = new AZStorage.Client(websiteInfo.AzureAccountName, websiteInfo.AzureAccountKey, websiteInfo.AzureContainerName);
                fileUrl = azClient.upload(fileStream, fileExtension);
            }
            else
            {
                fileUrl = OssHelper.UploadFileFromStream(OssHelper.GetBucket(websiteInfo.WebsiteOwner), OssHelper.GetBaseDir(websiteInfo.WebsiteOwner), userId, "image", fileStream, fileExtension);
            }

            return(fileUrl);
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            try
            {
                OssHelper ossHelper = new OssHelper();
                ossHelper.OssConfig = new OssConfig()
                {
                    AccessId = "8rtKfQTKlHlgDNHc", AccessKey = "dVRZLKfLS9SYNnv5bwLolTfv9cJqoS", BucketName = "neapmet"
                };


                ossHelper.MutiPartUpload("MDT.Tools.Aliyun.Common.exe.config", "aa");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
            Console.ReadLine();
        }
Esempio n. 10
0
        public static bool StoreFile(OssHelper oss, string bucketName, string oldFileUrl, string fileUrl, out string newFileUrl)
        {
            newFileUrl = "";
            // tmp -> origin
            string fileName = fileUrl.toFileName();

            if (fileName.Trim().Length != 0)
            {
                string fileNameTemp   = fileName.toTemp();
                string fileNameNormal = fileName.toNormal();
                newFileUrl = fileUrl.Replace(fileName, fileNameNormal);
                if (oss.ExistKey(bucketName, fileNameNormal))
                {
                    return(true);
                }
                if (!oss.ExistKey(bucketName, fileNameTemp))
                {
                    return(false);
                }
                try
                {
                    oss.CopyObject(bucketName, fileNameTemp, fileNameNormal);
                }
                catch
                {
                    return(false);
                }
            }

            // delete tmp
            fileName = oldFileUrl.toFileName();
            if (fileName != "")
            {
                try
                {
                    oss.DeleteObject(bucketName, fileName);
                }
                catch { }
            }
            return(true);
        }
Esempio n. 11
0
        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                this.Hide();
                btnSend.Enabled = btnCancel.Enabled = false;

                string[] strs    = name.Split('|');
                string[] prefixs = Prefix.Split('|');
                for (int i = 0; i < strs.Length; i++)
                {
                    var       errorReport = strs[i];
                    OssHelper ossHelper   = new OssHelper();
                    ossHelper.OssConfig = new OssConfig()
                    {
                        AccessId = accessId, AccessKey = accessKey, BucketName = bucketName
                    };
                    string guid = Guid.NewGuid().ToString() + ".LOG";
                    if (prefixs.Length == strs.Length)
                    {
                        if (!string.IsNullOrEmpty(prefixs[i]))
                        {
                            guid = prefixs[i] + ".LOG";
                        }
                    }
                    ossHelper.UpLoad(errorReport, guid);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
            finally
            {
                Application.Exit();
            }
        }
Esempio n. 12
0
        public string gettoken4zf()
        {
            string s = OssHelper.gettoken_zf();

            return(s);
        }
Esempio n. 13
0
        public async Task <CommonResponse <string> > ConfirmBorrowed(ConfirmBorrowedRequest request)
        {
            var response = new CommonResponse <string>();

            using (var trans = await _db.Database.BeginTransactionAsync())
            {
                try
                {
                    if (request == null)
                    {
                        throw new BizException("参数不能为空");
                    }

                    var borrowRegister = await _db.BorrowRegister.FirstOrDefaultAsync(c => c.Id == request.BorrowRegisterId && !c.Deleted);

                    if (borrowRegister == null)
                    {
                        throw new BizException("借阅登记不存在");
                    }

                    if (borrowRegister.Status == BorrowRegisterStatus.Borrowed)
                    {
                        //response.Message = "当前状态已经借出";
                        //response.ErrorCode = 1;
                        //response.Success = true;
                        //return response;
                        throw new BizException("当前借阅的状态为已借出");
                    }

                    if (borrowRegister.Status != BorrowRegisterStatus.Registered)
                    {
                        throw new BizException("借阅登记状态为:已登记 才能确认借出");
                    }

                    /*
                     * var archives = await _db.ArchivesInfo.Join(_db.BorrowRegisterDetail, a => a.Id, b => b.ArchivesId, (a, b) => new { a, b })
                     *  .Where(j => j.b.BorrowRegisterId == borrowRegister.Id)
                     *  .Select(c => c.a).ToListAsync();
                     * //如果当前状态为init,将档案改为
                     * archives.ForEach(c =>
                     * {
                     *  switch (c.Status)
                     *  {
                     *      case ArchivesStatus.Init:
                     *      case ArchivesStatus.Normal:
                     *          c.Status = ArchivesStatus.Borrowed;
                     *          break;
                     *      case ArchivesStatus.Borrowed:
                     *          throw new BizException("您选择的档案可能已借出,无法再次借阅");
                     *      default:
                     *          throw new BizException("您选择的档案档案当前状态出错,无法确认借出");
                     *  }
                     * });
                     */
                    borrowRegister.UpdateTime = DateTime.Now;
                    borrowRegister.Status     = BorrowRegisterStatus.Borrowed;
                    borrowRegister.UpdateTime = DateTime.Now;

                    await _db.SaveChangesAsync();

                    trans.Commit();
                    response.Success = true;

                    var projects = await _db.BorrowRegisterDetail.AsNoTracking().FirstOrDefaultAsync(c => c.BorrowRegisterId == borrowRegister.Id);

                    ApplicationLog.Info("SMS_171116670." + borrowRegister.Phone + "." + borrowRegister.Id);
                    var msgRes = OssHelper.SendSms("SMS_171116670", borrowRegister.Phone, $"{{\"name\":\"{borrowRegister.Borrower}\", \"PtName\":\"{(projects?.ProjectName)}\", \"RDate\":\"{borrowRegister.ReturnDate.ToString("yyyy-MM-dd")}\" }}");
                }
                catch (BizException ex)
                {
                    trans.Rollback();
                    response.Message = ex.Message;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    response.Message = "提交续借发生异常";
                    ApplicationLog.Error("ConfirmBorrowed", ex);
                }
            }

            return(response);
        }
Esempio n. 14
0
        /// <summary>
        /// 续借
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <CommonResponse <string> > RenewBorrow(RenewBorrowRequest request)
        {
            var response = new CommonResponse <string>();

            try
            {
                if (request == null)
                {
                    throw new BizException("参数不能为空");
                }

                if (request.RenewDate < DateTime.Now)
                {
                    throw new BizException("续借日期不能小于当天");
                }

                var borrowRegister = await _db.BorrowRegister.FirstOrDefaultAsync(c => c.Id == request.BorrowRegisterId && !c.Deleted);

                if (borrowRegister == null)
                {
                    throw new BizException("借阅登记不存在");
                }

                if (!(borrowRegister.Status == BorrowRegisterStatus.Renewed || borrowRegister.Status == BorrowRegisterStatus.Overdue || borrowRegister.Status == BorrowRegisterStatus.Borrowed))
                {
                    throw new BizException("借阅登记状态为:已借出、延期、逾期 才能续借");
                }

                borrowRegister.ReturnDate     = request.RenewDate;
                borrowRegister.Status         = BorrowRegisterStatus.Renewed;
                borrowRegister.UpdateTime     = DateTime.Now;
                borrowRegister.ReturnNotified = false;
                await _db.SaveChangesAsync();

                response.Success = true;

                var projects = await _db.BorrowRegisterDetail.AsNoTracking().FirstOrDefaultAsync(c => c.BorrowRegisterId == borrowRegister.Id);

                try
                {
                    //var archivesFirst = await _db.ArchivesInfo.AsNoTracking().Join(_db.BorrowRegisterDetail.AsNoTracking().Where(j => j.BorrowRegisterId == borrowRegister.Id).Take(1),
                    //    a => a.Id, b => b.ArchivesId, (a, b) => new { a, b })
                    //    .Select(c => new
                    //    {
                    //        c.a.ProjectName
                    //    }).FirstOrDefaultAsync();
                    ApplicationLog.Info("SMS_171116665." + borrowRegister.Phone + "." + borrowRegister.Id);
                    var msgRes = OssHelper.SendSms("SMS_171116665", borrowRegister.Phone, $"{{\"name\":\"{borrowRegister.Borrower}\", \"PtName\":\"{(projects?.ProjectName)}\", \"RDate\":\"{borrowRegister.ReturnDate.ToString("yyyy-MM-dd")}\" }}");
                }
                catch (Exception ex1)
                {
                    ApplicationLog.Error("RenewBorrow notice exception", ex1);
                }
            }
            catch (BizException ex)
            {
                response.Message = ex.Message;
            }
            catch (Exception ex)
            {
                response.Message = "提交续借发生异常";
                ApplicationLog.Error("RenewBorrow", ex);
            }
            return(response);
        }
Esempio n. 15
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string Add(HttpContext context)
        {
            //定义允许上传的文件扩展名
            Hashtable extTable = new Hashtable();

            extTable.Add("image", "gif,jpg,jpeg,png,bmp");
            extTable.Add("flash", "swf,flv");
            extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            extTable.Add("file", "doc,docx,xls,xlsx,ppt,pdf,htm,html,txt,zip,rar,gz,bz2,mp3,wmv");
            extTable.Add("app", "apk,app,ipa");

            String dirName = context.Request["dir"];

            if (String.IsNullOrEmpty(dirName))
            {
                dirName = "image";
            }

            webSiteInfo = bll.GetWebsiteInfoModel();
            if (webSiteInfo == null)
            {
                return(ZentCloud.Common.JSONHelper.ObjectToJson(new
                {
                    errcode = 2,
                    errmsg = "找不到站点信息。"
                }));
            }
            currentUserInfo = bll.GetCurrentUserInfo();
            if (currentUserInfo != null)
            {
                userId = currentUserInfo.UserID;
            }
            else
            {
                userId = "other";
            }

            List <string>  fileUrlList   = new List <string>();
            List <dynamic> otherInfoList = new List <dynamic>();

            var postFileList = context.Request.Files;

            for (int i = 0; i < postFileList.Count; i++)
            {
                String fileName = postFileList[i].FileName;
                String fileExt  = Path.GetExtension(fileName).ToLower();

                if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
                {
                    return(ZentCloud.Common.JSONHelper.ObjectToJson(new
                    {
                        errcode = 1,
                        errmsg = "上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。"
                    }));
                }
                try
                {
                    int maxWidth  = 800;
                    int maxHeight = 0;
                    if (!string.IsNullOrWhiteSpace(context.Request["maxWidth"]))
                    {
                        maxWidth = Convert.ToInt32(context.Request["maxWidth"]);
                    }
                    if (!string.IsNullOrWhiteSpace(context.Request["maxHeight"]))
                    {
                        maxHeight = Convert.ToInt32(context.Request["maxHeight"]);
                    }
                    if (dirName == "image" && (maxWidth > 0 || maxHeight > 0))
                    {
                        ZentCloud.Common.ImgWatermarkHelper imgHelper = new ZentCloud.Common.ImgWatermarkHelper();
                        Image image = Image.FromStream(postFileList[i].InputStream);

                        if ((image.Width > maxWidth && maxWidth > 0) || (image.Height > maxHeight && maxHeight > 0))
                        {
                            double ratio     = imgHelper.GetRatio(image.Width, image.Height, maxWidth, maxHeight);
                            int    newWidth  = Convert.ToInt32(Math.Round(ratio * image.Width));
                            int    newHeight = Convert.ToInt32(Math.Round(ratio * image.Height));
                            image = imgHelper.PhotoSizeChange(image, newWidth, newHeight);
                        }
                        if (ZentCloud.Common.ConfigHelper.GetConfigInt("Oss_Enable") == 0)
                        {
                            //文件保存目录路径
                            String fname      = Guid.NewGuid().ToString("N").ToUpper() + fileExt;
                            String savePath   = "/FileUpload/" + dirName + "/" + bll.WebsiteOwner + "/" + userId + "/" + DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo) + "/";
                            String serverPath = context.Server.MapPath(savePath);
                            if (!Directory.Exists(serverPath))
                            {
                                Directory.CreateDirectory(serverPath);
                            }
                            String serverFile = serverPath + fname;
                            String saveFile   = savePath + fname;
                            image.Save(serverFile, imgHelper.GetImageFormat(fileExt));

                            fileUrlList.Add(saveFile);

                            otherInfoList.Add(new
                            {
                                width      = image.Width,
                                height     = image.Height,
                                old_name   = postFileList[i].FileName,
                                filelength = postFileList[i].ContentLength
                            });
                        }
                        else
                        {
                            Stream stream = new MemoryStream();
                            image.Save(stream, imgHelper.GetImageFormat(fileExt));
                            stream.Position = 0;

                            string fileUrl = bllUploadOtherServer.upload(stream, fileExt); //= OssHelper.UploadFileFromStream(OssHelper.GetBucket(webSiteInfo.WebsiteOwner), OssHelper.GetBaseDir(webSiteInfo.WebsiteOwner), userId, "image", stream, fileExt);

                            fileUrlList.Add(fileUrl);

                            otherInfoList.Add(new
                            {
                                width      = image.Width,
                                height     = image.Height,
                                old_name   = postFileList[i].FileName,
                                filelength = postFileList[i].ContentLength
                            });
                        }
                    }
                    else
                    {
                        if (ZentCloud.Common.ConfigHelper.GetConfigInt("Oss_Enable") == 0)
                        {
                            //文件保存目录路径
                            String fname      = Guid.NewGuid().ToString("N").ToUpper() + fileExt;
                            String savePath   = "/FileUpload/" + dirName + "/" + bll.WebsiteOwner + "/" + userId + "/" + DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo) + "/";
                            String serverPath = context.Server.MapPath(savePath);
                            if (!Directory.Exists(serverPath))
                            {
                                Directory.CreateDirectory(serverPath);
                            }
                            String serverFile = serverPath + fname;
                            String saveFile   = savePath + fname;
                            fileUrlList.Add(saveFile);
                            if (dirName == "image")
                            {
                                ZentCloud.Common.ImgWatermarkHelper imgHelper = new ZentCloud.Common.ImgWatermarkHelper();
                                Image image = Image.FromStream(postFileList[i].InputStream);
                                image.Save(serverFile, imgHelper.GetImageFormat(fileExt));
                                otherInfoList.Add(new
                                {
                                    width      = image.Width,
                                    height     = image.Height,
                                    old_name   = postFileList[i].FileName,
                                    filelength = postFileList[i].ContentLength
                                });
                            }
                            else
                            {
                                postFileList[i].SaveAs(serverFile);
                                otherInfoList.Add(new
                                {
                                    old_name    = postFileList[i].FileName,
                                    file_length = postFileList[i].ContentLength
                                });
                            }
                        }
                        else
                        {
                            String fileUrl = OssHelper.UploadFile(OssHelper.GetBucket(webSiteInfo.WebsiteOwner), OssHelper.GetBaseDir(webSiteInfo.WebsiteOwner), userId, dirName, postFileList[i]);
                            fileUrlList.Add(fileUrl);

                            if (dirName == "image")
                            {
                                Image image = Image.FromStream(postFileList[i].InputStream);
                                otherInfoList.Add(new
                                {
                                    width      = image.Width,
                                    height     = image.Height,
                                    old_name   = postFileList[i].FileName,
                                    filelength = postFileList[i].ContentLength
                                });
                            }
                            else
                            {
                                otherInfoList.Add(new
                                {
                                    old_name    = postFileList[i].FileName,
                                    file_length = postFileList[i].ContentLength
                                });
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (ZentCloud.Common.ConfigHelper.GetConfigInt("Oss_Enable") == 0)
                    {
                        return(ZentCloud.Common.JSONHelper.ObjectToJson(new
                        {
                            errcode = 4,
                            errmsg = "上传出错:" + ex.Message
                        }));
                    }
                    else
                    {
                        return(ZentCloud.Common.JSONHelper.ObjectToJson(new
                        {
                            errcode = 4,
                            errmsg = "上传到Oss出错:" + ex.Message
                        }));
                    }
                }
            }
            //
            if (fileUrlList.Count > 0)
            {
                return(ZentCloud.Common.JSONHelper.ObjectToJson(new
                {
                    errcode = 0,
                    errmsg = "ok",
                    file_url_list = fileUrlList,
                    other_info_list = otherInfoList
                }));
            }
            else
            {
                return(ZentCloud.Common.JSONHelper.ObjectToJson(new
                {
                    errcode = 1,
                    errmsg = "fail"
                }));
            }
        }
Esempio n. 16
0
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbContent.Text.Trim()))
            {
                MessageBox.Show(this, @"问题不能为空,请认真描述你遇到的问题!", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (!vCode.ToLower().Equals(tbVC.Text.Trim().ToLower()))
            {
                MessageBox.Show(this, @"验证码输入有误!", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                genVC();
                return;
            }
            Enabled      = false;
            btnSend.Text = "提交中";
            ThreadPool.QueueUserWorkItem(o => {
                try
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("报告时间:" + DateTime.Now.ToString() + Environment.NewLine);
                    sb.AppendLine("问题描述:");
                    sb.AppendLine("\t" + tbContent.Text.Trim());
                    sb.AppendLine("屏幕截图:");
                    sb.AppendLine("\t" + cbScreen.Checked);
                    sb.AppendLine("联系电话:");
                    sb.AppendLine("\t" + tbPhone.Text.Trim());
                    sb.AppendLine("邮箱地址:");
                    sb.AppendLine("\t" + tbMail.Text.Trim());
                    OssHelper ossHelper = new OssHelper();
                    ossHelper.OssConfig = new OssConfig()
                    {
                        AccessId =
                            accessId,
                        AccessKey =
                            assessKey,
                        BucketName = bucketName
                    };
                    byte[] bt   = Encoding.UTF8.GetBytes(sb.ToString());
                    string time = DateTime.Now.ToString("yyyyMMddHHmmss");
                    string date = DateTime.Now.ToString("yyyyMMdd");
                    using (var ms = new MemoryStream())
                    {
                        ms.Write(bt, 0, bt.Length);
                        ms.Flush();
                        ms.Seek(0, SeekOrigin.Begin);

                        ossHelper.UpLoad(ms, string.Format("{1}/HelpDesk_{0}.txt", time, date));
                    }
                    if (cbScreen.Checked)
                    {
                        this.Invoke(new MethodInvoker(delegate
                        {
                            this.Visible = false;
                        }));
                        Thread.CurrentThread.Join(1000);
                        int width   = Screen.PrimaryScreen.Bounds.Width;
                        int height  = Screen.PrimaryScreen.Bounds.Height;
                        Image image = new Bitmap(width, height);
                        Graphics g  = Graphics.FromImage(image);
                        g.CopyFromScreen(0, 0, 0, 0, new System.Drawing.Size(width, height));
                        using (var ms = new MemoryStream())
                        {
                            image.Save(ms, ImageFormat.Jpeg);
                            ms.Write(bt, 0, bt.Length);
                            ms.Flush();
                            ms.Seek(0, SeekOrigin.Begin);
                            ossHelper.UpLoad(ms, string.Format("{1}/HelpDesk_{0}.jpeg", time, date));
                        }
                    }
                    sendSuccess();
                }
                catch (Exception ex)
                {
                    sendFailed();
                }
                finally
                {
                    Process.GetCurrentProcess().Kill();
                }
            });
        }
Esempio n. 17
0
 public static string StoreFile(OssHelper oss, string bucketName, string filename, Stream stream)
 {
     return(oss.PutObject(bucketName, filename, stream));
 }
Esempio n. 18
0
File: Form1.cs Progetto: uvbs/mmp
        private void ToOss2(DataTable dt)
        {
            StringBuilder sb = new StringBuilder();

            foreach (DataRow dr in dt.Rows)
            {
                try
                {
                    string oldFile = dr[txt2].ToString();
                    if (string.IsNullOrWhiteSpace(oldFile))
                    {
                        continue;
                    }
                    string oldFile1 = "";

                    if (oldFile.StartsWith(OssHelper.GetDomain()))
                    {
                        SetTextErrorMessage("已经在Oss服务器:" + oldFile);
                        continue;
                    }
                    else if (oldFile.StartsWith("/"))
                    {
                        oldFile1 = oldFile;
                    }
                    else
                    {
                        bool   haveLocalSrc = false;
                        string nowWebDomain = "";
                        for (int i = 0; i < txtLikeWebDomain.Length; i++)
                        {
                            if (oldFile.IndexOf(txtLikeWebDomain[i]) > 0)
                            {
                                haveLocalSrc = true;
                                nowWebDomain = txtLikeWebDomain[i];
                                break;
                            }
                        }
                        if (!haveLocalSrc)
                        {
                            SetTextErrorMessage("不是本站图片:" + oldFile);
                            continue;
                        }

                        oldFile1 = oldFile.Substring(oldFile.IndexOf(nowWebDomain) + nowWebDomain.Length - 1);
                    }
                    SetTextErrorMessage(oldFile1);
                    string  url = "";
                    DataSet ds  = DbHelperSQL.Query(string.Format("SELECT TOP 1 OldPath,NewPath FROM {0} WHERE OldPath='{1}' ", "FileToOssLog", oldFile1));
                    if (ds != null && ds.Tables.Count != 0 && ds.Tables[0].Rows.Count == 1)
                    {
                        url = ds.Tables[0].Rows[0]["NewPath"].ToString();
                    }
                    if (string.IsNullOrWhiteSpace(url))
                    {
                        ds = DbHelperSQL.Query(string.Format("SELECT TOP 1 OldPath,NewPath FROM {0} WHERE OldPath='{1}' ", "FileToOssLog", oldFile));
                        if (ds != null && ds.Tables.Count != 0 && ds.Tables[0].Rows.Count == 1)
                        {
                            url = ds.Tables[0].Rows[0]["NewPath"].ToString();
                        }
                    }
                    if (string.IsNullOrWhiteSpace(url))
                    {
                        string LocalPath = txt5 + oldFile1.Replace("/", @"\");
                        string extension = Path.GetExtension(oldFile1).ToLower();
                        if (!File.Exists(LocalPath))
                        {
                            SetTextErrorMessage("文件不存在:" + LocalPath);
                            continue;
                        }
                        byte[] fileByte = File.ReadAllBytes(LocalPath);
                        if (fileByte.Length == 0)
                        {
                            SetTextErrorMessage("文件大小为空:" + LocalPath);
                            continue;
                        }
                        url = OssHelper.UploadFileFromByte(OssHelper.GetBucket(""), baseDir + oldFile1, fileByte, extension);
                    }

                    DataSet ds1 = DbHelperSQL.Query(
                        string.Format("SELECT 1 FROM {0} WHERE [TableKeyID]='{1}' AND [TableName]='{2}' AND [FieldName]='{3}' AND [OldPath]='{4}'"
                                      , "FileToOssLog", dr[txt4].ToString(), txt1, txt2, oldFile));

                    if (ds1 != null && ds1.Tables.Count != 0 && ds1.Tables[0].Rows.Count == 0)
                    {
                        sb.AppendFormat("INSERT INTO {0} ([TableKeyID],[TableName],[FieldName],[OldPath],[NewPath]) ", "FileToOssLog");
                        sb.AppendFormat("VALUES ('{0}','{1}','{2}','{3}','{4}') ;", dr[txt4].ToString(), txt1, txt2, oldFile, url);
                    }
                }
                catch (Exception ex)
                {
                    SetTextErrorMessage(ex.Message);
                }
                finally
                {
                    now++;
                    SetTextMessage();
                }
            }
            try
            {
                if (!string.IsNullOrWhiteSpace(sb.ToString()))
                {
                    DbHelperSQL.ExecuteSql(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                SetTextErrorMessage(ex.Message);
            }
        }
Esempio n. 19
0
        public override void Process()
        {
            //byte[] uploadFileBytes = null;
            string uploadFileName = null;
            Stream fileStream     = null;

            if (UploadConfig.Base64)
            {
                uploadFileName = UploadConfig.Base64Filename;
                //uploadFileBytes = Convert.FromBase64String(Request[UploadConfig.UploadFieldName]);
            }
            else
            {
                var file = Request.Files[UploadConfig.UploadFieldName];
                uploadFileName = file.FileName;

                if (!CheckFileType(uploadFileName))
                {
                    Result.State = UploadState.TypeNotAllow;
                    WriteResult();
                    return;
                }
                if (!CheckFileSize(file.ContentLength))
                {
                    Result.State = UploadState.SizeLimitExceed;
                    WriteResult();
                    return;
                }

                //uploadFileBytes = new byte[file.ContentLength];
                try
                {
                    //file.InputStream.Read(uploadFileBytes, 0, file.ContentLength);
                    fileStream = file.InputStream;
                }
                catch (Exception)
                {
                    Result.State = UploadState.NetworkError;
                    WriteResult();
                }
            }

            Result.OriginFileName = uploadFileName;

            var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat);

            //var localPath = Server.MapPath(savePath);
            try
            {
//            if (!Directory.Exists(Path.GetDirectoryName(localPath)))
//            {
//                Directory.CreateDirectory(Path.GetDirectoryName(localPath));
//            }
//            File.WriteAllBytes(localPath, uploadFileBytes);
                var key = OssHelper.PutObject(fileStream, savePath);
                Result.Url   = key;
                Result.State = UploadState.Success;
            }
            catch (Exception e)
            {
                Result.State        = UploadState.FileAccessError;
                Result.ErrorMessage = e.Message;
            }
            finally
            {
                WriteResult();
            }
        }
Esempio n. 20
0
        public override void Process()
        {
            if (!string.IsNullOrWhiteSpace(UploadConfig.OssBucket))
            {
                #region 改Oss后方法
                var file = Request.Files[UploadConfig.UploadFieldName];
                Result.OriginFileName = file.FileName;
                try
                {
                    Result.Url   = OssHelper.UploadFile(OssHelper.GetBucket(UploadConfig.WebsiteOwner), OssHelper.GetBaseDir(UploadConfig.WebsiteOwner), UploadConfig.UserID, UploadConfig.FileType, file);
                    Result.State = UploadState.Success;
                }
                catch (Exception ex)
                {
                    Result.State        = UploadState.FileAccessError;
                    Result.ErrorMessage = ex.Message;
                }
                finally
                {
                    WriteResult();
                }
                #endregion
            }
            else
            {
                #region 改Oss前方法
                byte[] uploadFileBytes = null;
                string uploadFileName  = null;

                if (UploadConfig.Base64)
                {
                    uploadFileName  = UploadConfig.Base64Filename;
                    uploadFileBytes = Convert.FromBase64String(Request[UploadConfig.UploadFieldName]);
                }
                else
                {
                    var file = Request.Files[UploadConfig.UploadFieldName];
                    uploadFileName = file.FileName;

                    if (!CheckFileType(uploadFileName))
                    {
                        Result.State = UploadState.TypeNotAllow;
                        WriteResult();
                        return;
                    }
                    if (!CheckFileSize(file.ContentLength))
                    {
                        Result.State = UploadState.SizeLimitExceed;
                        WriteResult();
                        return;
                    }

                    uploadFileBytes = new byte[file.ContentLength];
                    try
                    {
                        file.InputStream.Read(uploadFileBytes, 0, file.ContentLength);
                    }
                    catch (Exception)
                    {
                        Result.State = UploadState.NetworkError;
                        WriteResult();
                    }
                }

                Result.OriginFileName = uploadFileName;

                var savePath  = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat);
                var localPath = Server.MapPath(savePath);
                try
                {
                    if (!Directory.Exists(Path.GetDirectoryName(localPath)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(localPath));
                    }
                    File.WriteAllBytes(localPath, uploadFileBytes);
                    Result.Url   = savePath;
                    Result.State = UploadState.Success;
                }
                catch (Exception e)
                {
                    Result.State        = UploadState.FileAccessError;
                    Result.ErrorMessage = e.Message;
                }
                finally
                {
                    WriteResult();
                }
                #endregion
            }
        }
Esempio n. 21
0
        public string gettoken4face()
        {
            string s = OssHelper.gettoken_jjrface();

            return(s);
        }
Esempio n. 22
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            #region 检查是否登录

            currentUserInfo = bllWebsiteDomainInfo.GetCurrentUserInfo();
            if (currentUserInfo == null)
            {
                resp.Msg = "您还未登录";
                context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            websiteOwner = bllWebsiteDomainInfo.WebsiteOwner;
            #endregion

            #region 检查文件
            //文件夹
            string fd = context.Request["fd"];
            if (string.IsNullOrWhiteSpace(fd))
            {
                fd = "audio";
            }

            //检查文件
            if (context.Request.Files.Count == 0)
            {
                resp.Msg = "请选择文件";
                context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
                return;
            }

            string fileName      = context.Request.Files[0].FileName;
            string fileExtension = Path.GetExtension(fileName).ToLower();
            if (string.IsNullOrWhiteSpace(fileName))
            {
                resp.Msg = "请选择文件";
                context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            //格式限制
            if (fileExtension != ".mp3")
            {
                resp.Msg = "为保障兼容请上传mp3文件";
                context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            #endregion

            string filePath = "";
            try
            {
                filePath = OssHelper.UploadFile(OssHelper.GetBucket(websiteOwner), OssHelper.GetBaseDir(websiteOwner), currentUserInfo.UserID, "audio", context.Request.Files[0]);
            }
            catch (Exception ex)
            {
                resp.Msg = ex.Message;
                context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            //返回字符串
            resp.IsSuccess = true;
            resp.ExStr     = filePath;
            resp.Msg       = "上传完成";
            context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
        }
Esempio n. 23
0
        public async Task <HttpResponseMessage> Upload()
        {
            var streamProvider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(streamProvider);

            var fileNames = new List <string>();

            foreach (var item in streamProvider.Contents)
            {
                if (item.Headers.ContentDisposition.FileName != null)
                {
                    var ms = item.ReadAsStreamAsync().Result;

                    //double size = ms.Length/1024;
                    //int maxSize = 50;
                    //int maxWidth = 640;
                    //int maxHeight = 200;
                    //if (size > maxSize)
                    //{
                    //Image img = Image.FromStream(ms);
                    //    int imgWidth = img.Width;
                    //    int imgHeight = img.Height;
                    //    if (imgWidth > imgHeight)
                    //    {
                    //        if (imgWidth > maxWidth)
                    //        {
                    //            float toImgWidth = maxWidth;
                    //            //float toImgHeight = imgHeight / (imgWidth / toImgWidth);
                    //            // float toImgHeight = toImgWidth*imgHeight/imgWidth;
                    //            float toImgHeight = imgHeight * (toImgWidth / imgWidth);
                    //            // Bitmap newImg=new Bitmap(img,int.Parse(toImgWidth.ToString()),int.Parse(toImgHeight.ToString()));
                    //            Bitmap newImg = new Bitmap(img, Convert.ToInt16(toImgWidth), Convert.ToInt16(toImgHeight));

                    //            MemoryStream stream = new MemoryStream();
                    //            //newImg.Save(stream, newImg.RawFormat);
                    //            newImg.Save(stream, ImageFormat.Png);
                    //            ms = stream;
                    //        }
                    //    }
                    //    else
                    //    {
                    //        if (imgHeight > maxHeight)
                    //        {
                    //            float toImgHeight = maxHeight;
                    //            float toImgWidth = imgWidth / (imgHeight / toImgHeight);
                    //            var newImg = new Bitmap(img, int.Parse(toImgWidth.ToString()), int.Parse(toImgHeight.ToString()));
                    //            MemoryStream stream = new MemoryStream();
                    //            newImg.Save(stream, newImg.RawFormat);
                    //            ms = stream;
                    //        }
                    //    }

                    //}
                    var fileLength = ms.Length;
                    var info       = new FileInfo(item.Headers.ContentDisposition.FileName.Replace("\"", ""));
                    //var allowFomat = new[] {".png",".jpg",".jepg",".gif"};
                    //var isImage = allowFomat.Contains(info.Extension.ToLower());
                    var fileNewName = GetUniquelyString();

                    //保存至OSS
                    var key = OssHelper.PutObject(ms, fileNewName + info.Extension);
                    //if (isImage)
                    //{
                    //    OssHelper.PutThumbnaiObject(ms, fileNewName + info.Extension);
                    //}

                    var resource = new ResourceEntity
                    {
                        Guid   = Guid.NewGuid(),
                        Name   = fileNewName,
                        Length = fileLength,
                        Type   = info.Extension.Substring(1).ToLower(),
                        //  Adduser = ((UserBase)_workContent.CurrentUser).Id,
                        Addtime = DateTime.Now,
                        //  UpdUser = _workContent.CurrentUser.Id,
                        UpdTime = DateTime.Now,
                    };
                    if (_resourceService.Create(resource).Id > 0)
                    {
                        fileNames.Add(key);
                    }
                }
            }
            return(PageHelper.toJson(PageHelper.ReturnValue(true, string.Join("|", fileNames))));
        }
Esempio n. 24
0
        private void check()
        {
            int par = urlList.Count * 3 + 10;
            int num = 0;

            lt.Clear();
            try
            {
                changeClTipText("正在检测  操作系统");
                LogHelper.Debug("check OS.");
                string[] os = MachineHelper.GetOperatingSystem();
                if (osSet.Contains(os[0]))
                {
                    initlt[0].Name        = "操作系统";
                    initlt[0].IsInstall   = "是";
                    initlt[0].CheckResult = os[1] + (MachineHelper.getPhysicalMemory() ? " 64位" : " 32位");
                    initlt[0].IsOk        = "符合";
                    initlt[0].AResult     = "无建议";
                }
                else
                {
                    initlt[0].Name        = "操作系统";
                    initlt[0].IsInstall   = "是";
                    initlt[0].CheckResult = os[1] + (MachineHelper.getPhysicalMemory() ? " 64位" : " 32位");
                    initlt[0].IsOk        = "不符合";
                    initlt[0].AResult     = "您使用了不支持的操作系统,系统支持的操作系统包括:Windows XP,Windows Server 2003,Windows Vista, Windows Server 2008,Windows 7, Windows Server 2008 R2,Windows 8";
                }
                this.setLoading(100 / (10 + par + num) * 1);

                //操作系统语言
                LogHelper.Debug("check Language.");
                if (MachineHelper.ContainsChineseLanguage())
                {
                    initlt[1].Name        = "操作系统语言";
                    initlt[1].IsInstall   = "是";
                    initlt[1].CheckResult = "简体中文";
                    initlt[1].IsOk        = "符合";
                    initlt[1].AResult     = "无建议";
                }
                else
                {
                    initlt[1].Name        = "操作系统语言";
                    initlt[1].IsInstall   = "否";
                    initlt[1].CheckResult = "简体中文";
                    initlt[1].IsOk        = "不符合";
                    initlt[1].AResult     = "No Chinese language package supported!";

                    LogHelper.Warn("No Chinese language package supported.");
                }
                this.setLoading(100 / (10 + par + num) * 2);


                //Settings.Default.ie_version;
                changeClTipText("正在检测  系统内存");
                double memory = MachineHelper.GetPhysicalMemory();
                if (memory < 0.512)
                {
                    initlt[2].Name        = "内存";
                    initlt[2].IsInstall   = "是";
                    initlt[2].CheckResult = memory * 1000 + "M";
                    initlt[2].IsOk        = "不符合";
                    initlt[2].AResult     = "内存最少不低于512M";
                    LogHelper.Error("内存最少不低于512M.");
                }
                else if (memory < 2.00)
                {
                    initlt[2].Name        = "内存";
                    initlt[2].IsInstall   = "是";
                    initlt[2].CheckResult = memory.ToString("N2") + "G";
                    initlt[2].IsOk        = "符合";
                    initlt[2].AResult     = "内存在2G以上,系统运行更好";
                }
                else
                {
                    initlt[2].Name        = "内存";
                    initlt[2].IsInstall   = "是";
                    initlt[2].CheckResult = memory.ToString("N2") + "G";
                    initlt[2].IsOk        = "符合";
                    initlt[2].AResult     = "无建议";
                }
                this.setLoading(100 / (10 + par + num) * 3);

                //.net framework
                changeClTipText("正在检测  .net framework版本");
                LogHelper.Debug("check .Net.");
                int visions = 0;
                frameworkList = MachineHelper.GetNetFramework(out visions);
                int counter = 0;
                foreach (string framework in frameworkList)
                {
                    string[] str = framework.Split(';');
                    if (initlt[3].CheckResult.Contains("Windows 7"))
                    {
                        switch (visions)
                        {
                        case 1:
                            initlt[3].Name        = ".NET FRAMEWORK";
                            initlt[3].IsInstall   = "否";
                            initlt[3].CheckResult = framework;
                            initlt[3].IsOk        = "不符合";
                            initlt[3].AResult     = "请先安装.Net Framework 3.5完整软件包";
                            break;

                        case 2:
                            if (!framework.Contains("v3.5"))
                            {
                                initlt[3].Name        = ".NET FRAMEWORK";
                                initlt[3].IsInstall   = "是";
                                initlt[3].CheckResult = framework;
                                initlt[3].IsOk        = "符合";
                                initlt[3].AResult     = "请单击开始-控制面板-程序和功能-打开或关闭Windows功能,开启.Net Framework 3.5服务";
                            }
                            else
                            {
                                initlt[3].Name        = ".NET FRAMEWORK";
                                initlt[3].IsInstall   = "否";
                                initlt[3].CheckResult = framework;
                                initlt[3].IsOk        = "不符合";
                                initlt[3].AResult     = "请先安装.Net Framework 3.5完整软件包";
                            }
                            break;

                        case 3:
                            initlt[3].Name        = ".NET FRAMEWORK";
                            initlt[3].IsInstall   = "是";
                            initlt[3].CheckResult = framework;
                            initlt[3].IsOk        = "符合";
                            initlt[3].AResult     = "无建议";
                            break;

                        case -1:
                            initlt[3].Name        = ".NET FRAMEWORK";
                            initlt[3].IsInstall   = "否";
                            initlt[3].CheckResult = framework;
                            initlt[3].IsOk        = "不符合";
                            initlt[3].AResult     = "请先卸载.Net Framework,再安装.Net Framework 3.5完整软件包";
                            break;
                        }
                    }
                    else
                    {
                        switch (visions)
                        {
                        case 3:
                            initlt[3].Name        = ".NET FRAMEWORK";
                            initlt[3].IsInstall   = "是";
                            initlt[3].CheckResult = framework;
                            initlt[3].IsOk        = "符合";
                            initlt[3].AResult     = "无建议";
                            break;

                        case -1:
                            initlt[3].Name        = ".NET FRAMEWORK";
                            initlt[3].IsInstall   = "否";
                            initlt[3].CheckResult = framework;
                            initlt[3].IsOk        = "不符合";
                            initlt[3].AResult     = "请先卸载.Net Framework,再安装.Net Framework 3.5完整软件包";
                            break;

                        default:
                            initlt[3].Name        = ".NET FRAMEWORK";
                            initlt[3].IsInstall   = "否";
                            initlt[3].CheckResult = framework;
                            initlt[3].IsOk        = "不符合";
                            initlt[3].AResult     = "请先安装.Net Framework 3.5完整软件包";
                            break;
                        }
                    }
                    counter++;
                    this.setLoading(100 / (10 + par + num) * 4);
                }


                //分辨率
                changeClTipText("正在检测  分辨率");
                LogHelper.Debug("check resolution.");
                Rectangle resolution = MachineHelper.GetResolution();
                if (true)
                {
                    initlt[4].Name        = "分辨率";
                    initlt[4].IsInstall   = "是";
                    initlt[4].CheckResult = resolution.Width + "*" + resolution.Height;
                    initlt[4].IsOk        = "符合";
                    initlt[4].AResult     = "无建议";
                }
                this.setLoading(100 / (10 + par + num) * 5);
                //颜色
                changeClTipText("正在检测  系统颜色");
                LogHelper.Debug("check color.");
                int color = MachineHelper.GetColorDepth();
                if (color >= 16)
                {
                    initlt[5].Name        = "系统色彩深度";
                    initlt[5].IsInstall   = "是";
                    initlt[5].CheckResult = color + "-bit";
                    initlt[5].IsOk        = "符合";
                    initlt[5].AResult     = "无建议";
                }
                else if (color >= 8)
                {
                    initlt[5].Name        = "系统色彩深度";
                    initlt[5].IsInstall   = "是";
                    initlt[5].CheckResult = color + "-bit";
                    initlt[5].IsOk        = "不符合";
                    initlt[5].AResult     = "为了更好使用本系统,请设置计算机色彩至少在16-bit。";

                    LogHelper.Warn("为了更好使用本系统,请设置计算机色彩至少在16-bit。");
                }
                else
                {
                    initlt[5].Name        = "系统色彩深度";
                    initlt[5].IsInstall   = "是";
                    initlt[5].CheckResult = color + "-bit";
                    initlt[5].IsOk        = "不符合";
                    initlt[5].AResult     = "目前系统颜色设置小于8-bit,为了更好使用本系统,请设置计算机色彩至少在16-bit。";
                }
                this.setLoading(100 / (10 + par + num) * 6);
                //操作系统



                //浏览器
                changeClTipText("正在检测  浏览器版本");
                object[] Browser    = MachineHelper.GetBrowser();
                double   browserVer = (double)Browser[0];
                if (browserVer >= IE_Version)
                {
                    initlt[6].Name        = "浏览器";
                    initlt[6].IsInstall   = "是";
                    initlt[6].CheckResult = (string)Browser[1];
                    initlt[6].IsOk        = "符合";
                    initlt[6].AResult     = "无建议";
                }
                else
                {
                    //WarningWin win = new WarningWin("警告", WARN, (string)Browser[1], "需要安装Internet Explorer 6.x以上版本,这样才能在本系统使用农行签约、解约和出入金功能。");

                    initlt[6].Name        = "浏览器";
                    initlt[6].IsInstall   = "是";
                    initlt[6].CheckResult = (string)Browser[1];
                    initlt[6].IsOk        = "不符合";
                    initlt[6].AResult     = "需要安装Internet Explorer 6.x以上版本,这样才能在本系统使用农行签约、解约和出入金功能。";

                    LogHelper.Warn("需要安装Internet Explorer 6.x以上版本,这样才能在本系统使用农行签约、解约和出入金功能。");
                }
                this.setLoading(100 / (10 + par + num) * 7);

                //http1.1
                changeClTipText("正在检测  http1.1");
                LogHelper.Debug("check HTTP.");
                if (MachineHelper.IsEnableHttp1_1())
                {
                    //SuccessWin win = new SuccessWin("HTTP", "HTTP1.1 Enabled.");

                    initlt[7].Name        = "HTTP";
                    initlt[7].IsInstall   = "是";
                    initlt[7].CheckResult = "HTTP1.1 Enabled.";
                    initlt[7].IsOk        = "符合";
                    initlt[7].AResult     = "无建议";
                }
                else
                {
                    initlt[7].Name        = "HTTP";
                    initlt[7].IsInstall   = "是";
                    initlt[7].CheckResult = "未启用.";
                    initlt[7].IsOk        = "不符合";
                    initlt[7].AResult     = "需要在IE中设置使用HTTP 1.1。打开Internet Explorer,菜单中选择工具-> 选项,选择高级,打开使用HTTP1.1。";

                    LogHelper.Warn("HTTP1.1 检查不通过.");
                }
                this.setLoading(100 / (10 + par + num) * 8);
                changeClTipText("正在检测  操作系统语言");

                //字体大小
                changeClTipText("正在检测  字体大小");
                LogHelper.Debug("check size(not).");
                string size = MachineHelper.GetFontSize();
                if (true)
                {
                    //SuccessWin win = new SuccessWin("字体大小", size);

                    initlt[8].Name        = "字体大小";
                    initlt[8].IsInstall   = "是";
                    initlt[8].CheckResult = size;
                    initlt[8].IsOk        = "符合";
                    initlt[8].AResult     = "无建议";
                }
                this.setLoading(100 / (10 + par + num) * 9);


                //字体检查
                changeClTipText("正在检测  包含字体");
                LogHelper.Debug("check YaHei Font.");
                if (MachineHelper.ContainsYaHeiFont())
                {
                    initlt[9].Name        = "字体";
                    initlt[9].IsInstall   = "是";
                    initlt[9].CheckResult = "微软雅黑";
                    initlt[9].IsOk        = "符合";
                    initlt[9].AResult     = "无建议";
                }
                else
                {
                    initlt[9].Name        = "字体";
                    initlt[9].IsInstall   = "否";
                    initlt[9].CheckResult = "微软雅黑";
                    initlt[9].IsOk        = "不符合";
                    initlt[9].AResult     = "请先下载微软雅黑字体";
                    LogHelper.Warn("未检测到微软雅黑, 没有安装微软雅黑字体.");
                }
                this.setLoading(100 / (10 + par + num) * 10);
                int count = 0;
                //检查ip地址通讯
                foreach (string[] urlinfo in urlList)
                {
                    changeClTipText("正在检测  " + urlinfo[0].Replace(":", "") + "网络通信");
                    String Msg       = "";
                    string telnetMsg = MachineHelper.canTelnet(urlinfo[2], Convert.ToInt32(urlinfo[3]));
                    if (telnetMsg == "0000")
                    {
                        initlt[10 + num + count].Name        = urlinfo[0] + "端口通信";
                        initlt[10 + num + count].IsInstall   = "是";
                        initlt[10 + num + count].CheckResult = "目标端口通信正常";
                        initlt[10 + num + count].IsOk        = "符合";
                        initlt[10 + num + count].AResult     = "无建议";
                        initlt[10 + num + count].Ip          = " " + urlinfo[2] + ":" + urlinfo[3] + " ";
                        this.setLoading((100 / (10 + par + num)) * (11 + counter + count));
                        count++;



                        MachineHelper.canPing(urlinfo[2], out Msg);
                        LogHelper.Info("msg:" + Msg);
                        string msg     = "";
                        string lossStr = "";
                        if (Msg.IndexOf("Average = ") >= 0)
                        {
                            msg     = Msg.Substring(Msg.IndexOf("Average = ") + 10);
                            lossStr = Msg.Substring(Msg.IndexOf("Lost = "), Msg.IndexOf("%") - Msg.IndexOf("Lost = "));
                        }
                        else
                        {
                            msg     = Msg.Substring(Msg.IndexOf("平均 = ") + 5);
                            lossStr = Msg.Substring(Msg.IndexOf("丢失 = "), Msg.IndexOf("%") - Msg.IndexOf("丢失 = "));
                        }
                        LogHelper.Info("msg:" + msg);
                        LogHelper.Info("lossStr:" + lossStr);
                        int ms = Convert.ToInt32(msg.Substring(0, msg.IndexOf("ms")));

                        int lossRate = int.Parse(lossStr.Substring(lossStr.IndexOf("(") + 1));

                        initlt[10 + num + count].Name        = urlinfo[0] + "丢包率";
                        initlt[10 + num + count].IsInstall   = "是";
                        initlt[10 + num + count].CheckResult = lossRate == 0 ? "无丢包" : "丢包率:" + lossRate;
                        initlt[10 + num + count].IsOk        = "符合";
                        initlt[10 + num + count].AResult     = lossRate == 0 ? "无建议" : "建议优化网络:" + lossRate;
                        initlt[10 + num + count].Ip          = " " + urlinfo[2] + ":" + urlinfo[3] + " ";
                        this.setLoading(100 / (10 + par + num) * (11 + counter + count));
                        count++;

                        initlt[10 + num + count].Name        = urlinfo[0] + "网络质量";
                        initlt[10 + num + count].IsInstall   = "是";
                        initlt[10 + num + count].CheckResult = (ms <= 100 ? "优" : ms <= 300 ? "中等" : "差");
                        initlt[10 + num + count].IsOk        = "符合";
                        initlt[10 + num + count].AResult     = (ms <= 100 ? "无建议" : "建议优化网络");
                        initlt[10 + num + count].Ip          = " " + urlinfo[2] + ":" + urlinfo[3] + " ";
                        initlt[10 + num + count].Delay       = " 延迟" + ms + "ms";
                        this.setLoading(100 / (10 + par + num) * (11 + counter + count));
                        count++;

                        if (urlinfo[0].Contains("查询服务器"))
                        {
                            if (MachineHelper.canUpdate(urlinfo[1] + "://" + urlinfo[2] + ":" + urlinfo[3] + "/" + ClientType.ToLower() + "autoUpdaterUrl.txt"))
                            {
                                initlt[10 + num + count].Name        = urlinfo[0].Replace("(查询服务器)", "(更新服务器)") + "端口通信";
                                initlt[10 + num + count].IsInstall   = "是";
                                initlt[10 + num + count].CheckResult = "目标端口通信正常";
                                initlt[10 + num + count].IsOk        = "符合";
                                initlt[10 + num + count].AResult     = "无建议";
                                initlt[10 + num + count].Ip          = " " + urlinfo[2] + ":" + urlinfo[3] + " ";
                                this.setLoading(100 / (10 + par + num) * (12 + counter + count));
                                count++;

                                initlt[10 + num + count].Name        = urlinfo[0].Replace("(查询服务器)", "(更新服务器)") + "更新服务";
                                initlt[10 + num + count].IsInstall   = "是";
                                initlt[10 + num + count].CheckResult = "可以更新客户端";
                                initlt[10 + num + count].IsOk        = "符合";
                                initlt[10 + num + count].AResult     = "无建议";
                                initlt[10 + num + count].Ip          = " " + urlinfo[2] + ":" + urlinfo[3] + " ";
                                this.setLoading(100 / (10 + par + num) * (11 + counter + count));
                                count++;
                            }
                            else
                            {
                                initlt[10 + num + count].Name        = urlinfo[0].Replace("(查询服务器)", "(更新服务器)") + "端口通信";
                                initlt[10 + num + count].IsInstall   = "是";
                                initlt[10 + num + count].CheckResult = "目标端口无法连通";
                                initlt[10 + num + count].IsOk        = "不符合";
                                initlt[10 + num + count].AResult     = "建议:检查本地网络";
                                initlt[10 + num + count].Ip          = " " + urlinfo[2] + ":" + urlinfo[3] + " ";
                                this.setLoading(100 / (10 + par + num) * (11 + counter + count));
                                count++;

                                initlt[10 + num + count].Name        = urlinfo[0].Replace("(查询服务器)", "(更新服务器)") + "更新服务";
                                initlt[10 + num + count].IsInstall   = "是";
                                initlt[10 + num + count].CheckResult = "无法更新客户端";
                                initlt[10 + num + count].IsOk        = "不符合";
                                initlt[10 + num + count].AResult     = "建议:检查本地网络";
                                initlt[10 + num + count].Ip          = " " + urlinfo[2] + ":" + urlinfo[3] + " ";
                                this.setLoading(100 / (10 + par + num) * (11 + counter + count));
                                count++;
                            }
                        }
                    }
                    else
                    {
                        initlt[10 + num + count].Name        = urlinfo[0] + "端口通信";
                        initlt[10 + num + count].IsInstall   = "是";
                        initlt[10 + num + count].CheckResult = "目标端口无法连通";
                        initlt[10 + num + count].IsOk        = "不符合";
                        initlt[10 + num + count].AResult     = "建议:检查本地网络";
                        initlt[10 + num + count].Ip          = " " + urlinfo[2] + ":" + urlinfo[3] + " ";
                        this.setLoading(100 / (10 + par + num) * (11 + counter + count));
                        count++;


                        initlt[10 + num + count].Name        = urlinfo[0] + "丢包率";
                        initlt[10 + num + count].IsInstall   = "是";
                        initlt[10 + num + count].CheckResult = "丢包率:100%";
                        initlt[10 + num + count].IsOk        = "不符合";
                        initlt[10 + num + count].AResult     = "建议:检查本地网络";
                        initlt[10 + num + count].Ip          = " " + urlinfo[2] + ":" + urlinfo[3] + " ";
                        this.setLoading(100 / (10 + par + num) * (11 + counter + count));
                        count++;

                        initlt[10 + num + count].Name        = urlinfo[0] + "网络质量";
                        initlt[10 + num + count].IsInstall   = "是";
                        initlt[10 + num + count].CheckResult = "无";
                        initlt[10 + num + count].IsOk        = "不符合";
                        initlt[10 + num + count].AResult     = "建议:检查本地网络";
                        initlt[10 + num + count].Delay       = " 延迟" + "999" + "ms";
                        initlt[10 + num + count].Ip          = " " + urlinfo[2] + ":" + urlinfo[3] + " ";
                        this.setLoading(100 / (10 + par + num) * (11 + counter + count));
                        count++;

                        if (urlinfo[0].Contains("查询服务器"))
                        {
                            initlt[10 + num + count].Name        = urlinfo[0].Replace("(查询服务器)", "(更新服务器)") + "端口通信";
                            initlt[10 + num + count].IsInstall   = "是";
                            initlt[10 + num + count].CheckResult = "目标端口无法连通";
                            initlt[10 + num + count].IsOk        = "不符合";
                            initlt[10 + num + count].AResult     = "建议:检查本地网络";
                            initlt[10 + num + count].Ip          = " " + urlinfo[2] + ":" + urlinfo[3] + " ";
                            this.setLoading(100 / (10 + par + num) * (11 + counter + count));
                            count++;

                            initlt[10 + num + count].Name        = urlinfo[0].Replace("(查询服务器)", "(更新服务器)") + "更新服务";
                            initlt[10 + num + count].IsInstall   = "是";
                            initlt[10 + num + count].CheckResult = "无法更新客户端";
                            initlt[10 + num + count].IsOk        = "不符合";
                            initlt[10 + num + count].AResult     = "建议:检查本地网络";
                            initlt[10 + num + count].Ip          = " " + urlinfo[2] + ":" + urlinfo[3] + " ";
                            this.setLoading(100 / (10 + par + num) * (11 + counter + count));
                            count++;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
            finally
            {
                this.setLoading(100);
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("检查项目" + "\t" + "是否安装" + "\t" + "检查结果" + "\t" + "是否符合" + "\t" + "建议结果");
                sb.AppendLine();
                foreach (CheckItemModel mode in initlt)
                {
                    sb.AppendLine(mode.ToString());
                }
                ThreadPool.QueueUserWorkItem(o =>
                {
                    try
                    {
                        sb.AppendLine("报告时间:" + DateTime.Now.ToString() +
                                      Environment.NewLine);

                        OssHelper ossHelper = new OssHelper();
                        ossHelper.OssConfig = new OssConfig()
                        {
                            AccessId =
                                accessId,
                            AccessKey =
                                assessKey,
                            BucketName = bucketName
                        };
                        byte[] bt   = Encoding.UTF8.GetBytes(sb.ToString());
                        string time = DateTime.Now.ToString("yyyyMMddHHmmss");
                        string date = DateTime.Now.ToString("yyyyMMdd");
                        using (var ms = new MemoryStream())
                        {
                            ms.Write(bt, 0, bt.Length);
                            ms.Flush();
                            ms.Seek(0, SeekOrigin.Begin);

                            ossHelper.UpLoad(ms,
                                             string.Format("{1}/SysCheck_{0}.txt", time,
                                                           date));
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error(ex);
                    }
                });
            }
        }
Esempio n. 25
0
        private static void UploadData()
        {
            var 务器     = Config["服务器"];
            var 本地数据路径 = new DirectoryInfo(Config["本地数据路径"]);
            var 间隔     = int.Parse(Config["上传间隔"]);
            var DB用户名  = Config["DB用户名"];
            var DB密码   = Config["DB密码"];
            var OSSAKI = Config["OSSAKI"];
            var OSSAKS = Config["OSSAKS"];

            OssHelper.IsDevelopment   = true;
            OssHelper.AccessKeyID     = OSSAKI;
            OssHelper.AccessKeySecret = OSSAKS;

            var dataContext = new MkhxCoreContext(DB用户名, DB密码);

            while (true)
            {
                WriteText("\r\n");
                WriteText(DateTime.Now + "\t");
                WriteInfo("更新数据..." + "\r\n");

                var files = 本地数据路径.GetFiles("*.txt");
                foreach (var fi in files)
                {
                    var FileName = fi.Name.Split('_')[0].ToLower();

                    switch (FileName)
                    {
                    case "allcards":
                    case "allrunes":
                    case "allskills":
                    case "allmapstage":
                    case "allmaphardstage":
                    case "keywords":
                    {
                        try
                        {
                            var Version = GetVersion(fi);

                            WriteText(DateTime.Now + "\t");
                            WriteText(FileName + "\t");
                            WriteText(Version + "\t");

                            var newest = dataContext.GameDataFiles.Where(m => m.Server == 务器 && m.FileName == FileName).OrderByDescending(m => m.Time).FirstOrDefault();

                            if (newest?.Version != Version)
                            {
                                var key = "data/" + Version + ".json";
                                if (!OssHelper.Exist(key))
                                {
                                    OssHelper.Upload(key, fi);
                                }

                                var GameDataFiles = new GameDataFiles
                                {
                                    Id       = Guid.NewGuid(),
                                    Version  = Version,
                                    FileName = FileName,
                                    Server   = 务器,
                                    Time     = fi.LastWriteTime,
                                    Remark   = "",
                                };
                                dataContext.GameDataFiles.Add(GameDataFiles);
                                dataContext.SaveChanges();
                                WriteSuccess("成功" + "\r\n");

                                Console.Title = $"服务器{Config["服务器"]} 更新时间:{fi.LastWriteTime}";
                            }
                            else
                            {
                                WriteWarning("不需要更新" + "\r\n");
                            }
                        }
                        catch (Exception ex)
                        {
                            WriteError("失败 - " + ex + "\r\n");
                        }
                        break;
                    }
                    }
                }

                var Status     = "GameDataLastUpdateTime";
                var UpdateTime = DateTime.Now.ToString();
                var Data       = dataContext.Enum.First(m => m.Type == "GameDataLastUpdateTime");
                Data.Desc         = Status;
                Data.Value1Format = UpdateTime;
                dataContext.SaveChanges();

                WriteText(DateTime.Now + "\t");
                WriteInfo("数据更新完毕" + "\r\n");
                WriteText("\r\n");

                Thread.Sleep(间隔);
            }
        }