public static void AsyncGetObject(COSXML.CosXml cosXml, string bucket, string key, string localDir, string localFileName) { GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName); //设置签名有效时长 request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600); request.SetCosProgressCallback(delegate(long completed, long total) { Console.WriteLine(String.Format("progress = {0} / {1} : {2:##.##}%", completed, total, completed * 100.0 / total)); }); //执行请求 cosXml.GetObject(request, delegate(CosResult result) { GetObjectResult getObjectResult = result as GetObjectResult; Console.WriteLine(getObjectResult.GetResultInfo()); }, delegate(CosClientException clientEx, CosServerException serverEx) { if (clientEx != null) { QLog.D("XIAO", clientEx.Message); Console.WriteLine("CosClientException: " + clientEx.StackTrace); } if (serverEx != null) { QLog.D("XIAO", serverEx.Message); Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } }); }
public void GetObject(COSXML.CosXml cosXml, string bucket, string key, string localDir, string localFileName) { try { GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName); //设置签名有效时长 request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600); request.SetCosProgressCallback(delegate(long completed, long total) { // Console.WriteLine(String.Format("progress = {0} / {1} : {2:##.##}%", completed, total, completed * 100.0 / total)); }); //执行请求 GetObjectResult result = cosXml.GetObject(request); Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { Console.WriteLine("CosClientException: " + clientEx.Message); Assert.True(false); } catch (COSXML.CosException.CosServerException serverEx) { Console.WriteLine("CosServerException: " + serverEx.GetInfo()); Assert.True(false); } }
public void testGetObject() { try { GetObjectRequest request = new GetObjectRequest(bucket, commonKey, localDir, localFileName); request.SetCosProgressCallback(delegate(long completed, long total) { Console.WriteLine(String.Format("progress = {0} / {1} : {2:##.##}%", completed, total, completed * 100.0 / total)); }); //执行请求 GetObjectResult result = cosXml.GetObject(request); Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { Console.WriteLine("CosClientException: " + clientEx.Message); Assert.True(false); } catch (COSXML.CosException.CosServerException serverEx) { Console.WriteLine("CosServerException: " + serverEx.GetInfo()); Assert.True(false); } }
/// 下载对象 public void GetObject() { //.cssg-snippet-body-start:[get-object] try { string bucket = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPID string key = "exampleobject"; //对象键 string localDir = System.IO.Path.GetTempPath(); //本地文件夹 string localFileName = "my-local-temp-file"; //指定本地保存的文件名 GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName); //设置进度回调 request.SetCosProgressCallback(delegate(long completed, long total) { Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total)); }); //执行请求 GetObjectResult result = cosXml.GetObject(request); //请求成功 Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { //请求失败 Console.WriteLine("CosClientException: " + clientEx); } catch (COSXML.CosException.CosServerException serverEx) { //请求失败 Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } //.cssg-snippet-body-end }
public void SetResult(GetObjectResult result) { this.eTag = result.eTag; this.httpCode = result.httpCode; this.httpMessage = result.httpMessage; this.responseHeaders = result.responseHeaders; }
public async Task <ResponseModel> DownObject(string key, string localDir, string localFileName) { try { string bucket = _buketName + "-" + _appid; //存储桶名称 格式:BucketName-APPID GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName); //设置签名有效时长 request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600); //设置进度回调 request.SetCosProgressCallback(delegate(long completed, long total) { Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total)); }); //执行请求 GetObjectResult result = await Task.FromResult(_cosXml.GetObject(request)); return(new ResponseModel { Code = 200, Message = result.GetResultInfo() }); } catch (CosClientException clientEx) { return(new ResponseModel { Code = 0, Message = "CosClientException: " + clientEx.Message }); } catch (CosServerException serverEx) { return(new ResponseModel { Code = 0, Message = serverEx.GetInfo() }); } }
private void GetObject() { if (getObjectRequest == null) { getObjectRequest = new GetObjectRequest(bucket, key, localDir, localFileName); } if (progressCallback != null) { getObjectRequest.SetCosProgressCallback(progressCallback); } getObjectRequest.SetRange(rangeStart, rangeEnd); getObjectRequest.SetLocalFileOffset(localFileOffset); cosXmlServer.GetObject(getObjectRequest, delegate(CosResult result) { lock (syncExit) { if (isExit) { return; } } if (UpdateTaskState(TaskState.Completed)) { GetObjectResult getObjectResult = result as GetObjectResult; DownloadTaskResult downloadTaskResult = new DownloadTaskResult(); downloadTaskResult.SetResult(getObjectResult); if (successCallback != null) { successCallback(downloadTaskResult); } } } , delegate(CosClientException clientEx, CosServerException serverEx) { lock (syncExit) { if (isExit) { return; } } if (UpdateTaskState(TaskState.Failed)) { if (failCallback != null) { failCallback(clientEx, serverEx); } } }); }
/// <summary> /// 分段下载 /// </summary> /// <param name="key"></param> /// <param name="targetFolder"></param> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> public static DownloadResult DownloadObject(DownloadRecord record, string targetFolder, long start, long end) { DownloadResult downloadResult = new DownloadResult(); Random reum = new Random(); int randomdata = reum.Next(100000); string tempFileName = DateUtil.currentTimeMillis(new DateTime()) + randomdata + ".temp"; try { GetObjectRequest request = new GetObjectRequest(BosConfig.BucketName, record.CloudFile.Key, targetFolder, tempFileName); request.SetRange(start, end); //设置签名有效时长 request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600); //执行请求 GetObjectResult result = getCosXmlServer().GetObject(request); Console.WriteLine("msg" + result.GetResultInfo()); if (String.Equals("OK", result.httpMessage)) { } else if (String.Equals("Requested Range Not Satisfiable", result.httpMessage)) { downloadResult.state = 1; File.Delete(targetFolder + @"\" + tempFileName); return(downloadResult); } else if (String.Equals("Not Found", result.httpMessage)) { downloadResult.state = 2; File.Delete(targetFolder + @"\" + tempFileName); return(downloadResult); } Stream stream = new FileStream(targetFolder + @"\" + tempFileName, FileMode.Open); downloadResult = FileUtil.saveFileContent(stream, record.FileName, targetFolder); File.Delete(targetFolder + @"\" + tempFileName); } catch (COSXML.CosException.CosClientException clientEx) { //请求失败 Console.WriteLine("CosClientException: " + clientEx.Message); downloadResult.state = 2; } catch (COSXML.CosException.CosServerException serverEx) { //请求失败 Console.WriteLine("CosServerException: " + serverEx.GetInfo()); downloadResult.state = 2; } return(downloadResult); }
public void download(string download_dir, string key = "md5list.json") { //初始化 CosXmlConfig string appid = "1255334966"; //设置腾讯云账户的账户标识 APPID string region = "ap-beijing"; //设置一个默认的存储桶地域 CosXmlConfig config = new CosXmlConfig.Builder() .IsHttps(true) //设置默认 HTTPS 请求 .SetAppid(appid) //设置腾讯云账户的账户标识 APPID .SetRegion(region) //设置一个默认的存储桶地域 .SetDebugLog(true) //显示日志 .Build(); //创建 CosXmlConfig 对象 //方式1, 永久密钥 string secretId = Properties.Resources.TencentID; //"云 API 密钥 SecretId"; string secretKey = Properties.Resources.TencentKey; //"云 API 密钥 SecretKey"; long durationSecond = 1000; //每次请求签名有效时长,单位为秒 QCloudCredentialProvider cosCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond); //初始化 CosXmlServer CosXmlServer cosXml = new CosXmlServer(config, cosCredentialProvider); try { string bucket = "thuai-1255334966"; //存储桶,格式:BucketName-APPID string localDir = System.IO.Path.GetDirectoryName(download_dir); //本地文件夹 <-------------- string localFileName = System.IO.Path.GetFileName(download_dir); //指定本地保存的文件名 <-------------- GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName); //设置签名有效时长 //request.SetSign(DateTimeOffset.UtcNow.ToString(), 1000); //设置进度回调 Dictionary <string, string> test = request.GetRequestHeaders(); request.SetCosProgressCallback(delegate(long completed, long total) { //Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total)); }); //执行请求 GetObjectResult result = cosXml.GetObject(request); //请求成功 Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { throw clientEx; } catch (COSXML.CosException.CosServerException serverEx) { throw serverEx; } }
/// 下载时添加盲水印 public void DownloadObjectWithWatermark() { string bucket = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPID string key = "exampleobject"; //对象键 string localDir = System.IO.Path.GetTempPath(); //本地文件夹 string localFileName = "my-local-temp-file"; //指定本地保存的文件名 //.cssg-snippet-body-start:[download-object-with-watermark] GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, key, localDir, localFileName); //处理参数,规则参见:https://cloud.tencent.com/document/product/460/19017 getObjectRequest.SetQueryParameter("watermark/3/type/<type>/image/<imageUrl>/text/<text>", null); GetObjectResult result = cosXml.GetObject(getObjectRequest); //.cssg-snippet-body-end }
/// 获取预签名下载链接 public void GetPresignDownloadUrl() { //.cssg-snippet-body-start:[get-presign-download-url] try { PreSignatureStruct preSignatureStruct = new PreSignatureStruct(); preSignatureStruct.appid = "1250000000"; //腾讯云账号 APPID preSignatureStruct.region = "COS_REGION"; //存储桶地域 preSignatureStruct.bucket = "examplebucket-1250000000"; //存储桶 preSignatureStruct.key = "exampleobject"; //对象键 preSignatureStruct.httpMethod = "GET"; //HTTP 请求方法 preSignatureStruct.isHttps = true; //生成 HTTPS 请求 URL preSignatureStruct.signDurationSecond = 600; //请求签名时间为600s preSignatureStruct.headers = null; //签名中需要校验的 header preSignatureStruct.queryParameters = null; //签名中需要校验的 URL 中请求参数 string requestSignURL = cosXml.GenerateSignURL(preSignatureStruct); //下载请求预签名 URL (使用永久密钥方式计算的签名 URL) string localDir = System.IO.Path.GetTempPath(); //本地文件夹 string localFileName = "my-local-temp-file"; //指定本地保存的文件名 GetObjectRequest request = new GetObjectRequest(null, null, localDir, localFileName); //设置下载请求预签名 URL request.RequestURLWithSign = requestSignURL; //设置进度回调 request.SetCosProgressCallback(delegate(long completed, long total) { Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total)); }); //执行请求 GetObjectResult result = cosXml.GetObject(request); //请求成功 Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { //请求失败 Console.WriteLine("CosClientException: " + clientEx); } catch (COSXML.CosException.CosServerException serverEx) { //请求失败 Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } //.cssg-snippet-body-end }
private static GetObjectResult GetObject(object parent, string propertyName, string inputName, bool includeStatics) { var result = new GetObjectResult { PropertyName = propertyName, Input = parent, InputName = inputName }; var isEnumerable = ReflectionMethods.EnumerablePattern.IsMatch(propertyName); var stripped = ReflectionMethods.StripIndexer(propertyName); var propInfo = parent .GetType() .GetPublicProperties(includeStatics) .FirstOrDefault(p => ReflectionMethods.NameMatch(p, stripped)); var propVal = propInfo?.GetValue(parent); if (isEnumerable) { result.Property = propVal; var index = ReflectionMethods.GetIndexerValue(propertyName); if (index == null) { return(null); } var item = ReflectionMethods.GetItem(propVal, index.Value); if (item == null) { return(null); } result.Leaf = item; } else { result.Property = parent; result.Leaf = propVal; } result.PropertyInfo = result.Input.GetType().GetProperty(stripped); return(result); }
public void GetFileDow(string keyw, string name, OnProgressCallback Dwjindu, string path) { CosXmlConfig config = new CosXmlConfig.Builder() .SetConnectionTimeoutMs(SetConnectionTimeoutMs) //设置连接超时时间,单位毫秒,默认45000ms .SetReadWriteTimeoutMs(SetReadWriteTimeoutMs) //设置读写超时时间,单位毫秒,默认45000ms .IsHttps(IsHttps) //设置默认 HTTPS 请求 .SetAppid(SetAppid) //设置腾讯云账户的账户标识 APPID .SetRegion(SetRegion) //设置一个默认的存储桶地域 .Build(); string secretId = SecretId; //云 API 密钥 SecretId string secretKey = SecretKey; //云 API 密钥 SecretKey long durationSecond = 600; //每次请求签名有效时长,单位为秒 QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond); CosXml cosXml = new CosXmlServer(config, qCloudCredentialProvider); try { string bucket = "yuanguhl"; //存储桶,格式:BucketName-APPID string key = keyw; //对象在存储桶中的位置,即称对象键 string localDir = path; //本地文件夹 string localFileName = name; //指定本地保存的文件名 GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName); request.Region = "ap-beijing"; //设置签名有效时长 request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600); //设置进度回调 request.SetCosProgressCallback(Dwjindu); //执行请求 GetObjectResult result = cosXml.GetObject(request); //请求成功 } catch (COSXML.CosException.CosClientException clientEx) { //请求失败 throw clientEx; } catch (COSXML.CosException.CosServerException serverEx) { //请求失败 throw serverEx; } }
private void syncDownloadFile(string bucket, string fileKey, string localDir, string localFileName, OnProgressCallback progressCb, OnSuccessCallback <CosResult> successCb, OnFailedCallback failedCb) { try { GetObjectRequest request = new GetObjectRequest(bucket, fileKey, localDir, localFileName); request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600); request.SetCosProgressCallback(progressCb); GetObjectResult result = cosXml.GetObject(request); } catch (CosClientException clientEx) { failedCb(clientEx, null); } catch (CosServerException serverEx) { failedCb(null, serverEx); } }
public static async Task <MiObject> GetAllObjects(string bucket, string prefix, Action <MiObject> OnNewObjects) { var result = new GetObjectResult() { RootDirectory = new MiDirectoryObject(prefix, prefix), NextMarker = string.Empty }; do { result = await Utility.RetryAsync(async() => { return(await GetObjects(bucket, prefix, result.RootDirectory, result.NextMarker)); }, TimeSpan.FromSeconds(1)); if (OnNewObjects != null) { OnNewObjects(result.RootDirectory); } }while (!string.IsNullOrWhiteSpace(result.NextMarker)); return(result.RootDirectory); }
public static XenReflectionProperty[] GetXenRefProperties(this object parent, string[] path, bool includeStatics = false) { var target = parent; var result = new List <XenReflectionProperty>(); if (path == null || path.Length == 0) { throw new InvalidOperationException("This method is meant to traverse an object graph."); } if (path.Length == 1) { var res = GetObject(parent, path[0], null, includeStatics); // null if the index is out of bounds. if (res == null) { return new XenReflectionProperty[] {} } ; result.Add(CreateXenRefProperty(null, res.Input, res.PropertyName, null, res.PropertyInfo)); } else { GetObjectResult res = null; object grandParent = null; string inputName = null; for (var i = 0; i < path.Length; i++) { var name = path[i]; res = GetObject(target, name, inputName, includeStatics); target = res.Leaf; // should be one behind inputName = name; if (path.Length == 2) { grandParent = parent; } else { // 3 places back is the grandparent if (i == path.Length - 3) { grandParent = target; } } } if (res != null) { result.Add(CreateXenRefProperty(grandParent, res.Input, res.PropertyName, res.InputName, res.PropertyInfo)); } } return(result.ToArray()); }
/// <summary> /// 登录按钮被点击 /// </summary> private void ucBtnExt_Login_BtnClick(object sender, EventArgs e) { ucBtnExt_Login.FillColor = Color.FromArgb(155, 155, 155); ucBtnExt_Login.Enabled = false; string ret = Verify.Login(ucTextBoxEx_Key.InputText, localVersion, IpConfig.GetMac()); if (ret.Length == 32)//登录成功 { //登录按钮消失,进度条取代,进行必要的变量的声明 ucBtnExt_Login.Visible = false; ucProcessLine.Visible = true; ucProcessLine.Location = ucBtnExt_Login.Location; string expiredTimeS = null; string diskSerialNumber = SystemConfig.GetDiskSerialNumber(); bool isDownload = false; Thread loginSuccessThread = new Thread(() => { //对userLoginData进行赋值 userLoginData.Key = ucTextBoxEx_Key.InputText; userLoginData.StatusCode = ret; expiredTimeS = Verify.GetExpired(userLoginData.Key); userLoginData.ExpiredTimeS = expiredTimeS; DateTime expiredTime = Convert.ToDateTime(userLoginData.ExpiredTimeS); userLoginData.ExpiredTime = expiredTime; //取到期时间的时间间隔 TimeSpan ts = expiredTime.Subtract(Convert.ToDateTime(GetData.GetNetDateTime())); //用网络时间进行计算 label_Status.ForeColor = Color.FromArgb(66, 66, 66); label_Status.Text = String.Format("{0}{1}天{2}时{3}分", "卡密剩余时间:", ts.Days.ToString(), ts.Hours.ToString(), ts.Minutes.ToString()); //写配置文件保存卡密 OperateIniFile.WriteIniData("Ares", "Key", Encrypt.DES(userLoginData.Key, "areskeys"), "logindata.ini"); //核心数据取COS下载数据并解析 string appCode = Verify.GetAppCore(userLoginData.StatusCode, userLoginData.Key); if (appCode == "-1") { FrmDialog.ShowDialog(this, "Ares无法下载核心云端数据\n\n点击\"确定\"按钮退出Ares软件", "Ares - 致命错误"); Environment.Exit(0); } if (appCode.Length <= 10) { FrmDialog.ShowDialog(this, "Ares下载的核心云端数据不合法\n\n点击\"确定\"按钮退出Ares软件", "Ares - 致命错误"); Environment.Exit(0); } DllDownloadData dllDownloadData = JsonConvert.DeserializeObject <DllDownloadData>(appCode); //判断文档中的 TencentCos 文件夹是否存在,不存在就新建一个 if (Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + diskSerialNumber) != true) { try { Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + diskSerialNumber); } catch { FrmDialog.ShowDialog(this, "Ares申请的读写目录权限申请失败\n\n点击\"确定\"按钮退出Ares软件", "Ares - 致命错误"); Environment.Exit(0); } Console.WriteLine("TencentCos文件夹不存在,已经新建完毕"); } //文件是否已经存在,存在就不再下载,节省流量 if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + diskSerialNumber + "\\" + Decrypt.DES(dllDownloadData.LocalFileName, Decrypt.DES(webApiUrlData.Key, "actingnb"))) == true) { //文件存在,进行MD5校验,校验通过就不重新下载了 string existFileMD5 = MD5.GetMD5HashFromFile(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + diskSerialNumber + "\\" + Decrypt.DES(dllDownloadData.LocalFileName, Decrypt.DES(webApiUrlData.Key, "actingnb"))); if (existFileMD5 != "-1") //验证是否成功取到MD5 { if (existFileMD5 == Decrypt.DES(dllDownloadData.MD5, Decrypt.DES(webApiUrlData.Key, "actingnb"))) //验证MD5是否与服务器的相符 { isDownload = false; //MD5相符,不需要重新下载 ucProcessLine.Value = 100; Console.WriteLine("MD5相符,不需要重新下载"); } else { isDownload = true;//MD5不符,需要重新下载 Console.WriteLine("MD5不符,需要重新下载"); } } } else { isDownload = true;//文件不存在,进行下载 Console.WriteLine("文件不存在,进行下载"); } //云下载DLL if (isDownload == true) { string secretId = Decrypt.DES(dllDownloadData.SecretId, Decrypt.DES(webApiUrlData.Key, "actingnb")); // API SecretId string secretKey = Decrypt.DES(dllDownloadData.SecretKey, Decrypt.DES(webApiUrlData.Key, "actingnb")); // API SecretKey string region = Decrypt.DES(dllDownloadData.Region, Decrypt.DES(webApiUrlData.Key, "actingnb")); // 存储桶所在地域 CosXmlConfig config = new CosXmlConfig.Builder() //普通初始化方式 .IsHttps(true) //设置默认 HTTPS 请求 .SetRegion(region) .SetDebugLog(true) .Build(); long durationSecond = 600; //每次请求签名有效时长,单位为秒 QCloudCredentialProvider cosCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond); CosXml cosXml = new CosXmlServer(config, cosCredentialProvider); try { string bucket = Decrypt.DES(dllDownloadData.Bucket, Decrypt.DES(webApiUrlData.Key, "actingnb")); //存储桶,格式:BucketName-APPID string key = Decrypt.DES(dllDownloadData.Key, Decrypt.DES(webApiUrlData.Key, "actingnb")); //对象键 string localDir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + diskSerialNumber; //下载到的目录 不需要文件名 string localFileName = Decrypt.DES(dllDownloadData.LocalFileName, Decrypt.DES(webApiUrlData.Key, "actingnb")); //指定本地保存的文件名 GetObjectRequest request = new GetObjectRequest(bucket, key, localDir, localFileName); //设置进度回调 request.SetCosProgressCallback(delegate(long completed, long total) { //Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total)); ucProcessLine.Value = Convert.ToInt32(completed * 100.0 / total); }); //执行请求 GetObjectResult result = cosXml.GetObject(request); //请求成功 Console.WriteLine(result.GetResultInfo()); } catch (CosClientException clientEx) { //请求失败 //MessageBox.Show("CosClientException: " + clientEx); FrmDialog.ShowDialog(this, "Ares无法下载核心云端文件\n\n点击\"确定\"按钮退出Ares软件" + "CosClientException: " + clientEx, "Ares - 致命错误"); Environment.Exit(0); } catch (CosServerException serverEx) { //请求失败 //MessageBox.Show("CosServerException: " + serverEx.GetInfo()); FrmDialog.ShowDialog(this, "Ares无法下载核心云端文件\n\n点击\"确定\"按钮退出Ares软件" + "CosServerException: " + serverEx.GetInfo(), "Ares - 致命错误"); Environment.Exit(0); } //下载完成后判断文件是否已经存在,不存在就是下载失败 if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + diskSerialNumber + "\\" + Decrypt.DES(dllDownloadData.LocalFileName, Decrypt.DES(webApiUrlData.Key, "actingnb"))) == true) { //文件存在,进行MD5校验,校验通过就不重新下载了 string existFileMD5 = MD5.GetMD5HashFromFile(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + diskSerialNumber + "\\" + Decrypt.DES(dllDownloadData.LocalFileName, Decrypt.DES(webApiUrlData.Key, "actingnb"))); if (existFileMD5 != "-1") //验证是否成功取到MD5 { if (existFileMD5 != Decrypt.DES(dllDownloadData.MD5, Decrypt.DES(webApiUrlData.Key, "actingnb"))) //验证MD5是否与服务器的相符 { FrmDialog.ShowDialog(this, "Ares下载的核心云端文件与服务器不符\n\n点击\"确定\"按钮退出Ares软件", "Ares - 致命错误"); Console.WriteLine("下载的文件MD5不符"); Environment.Exit(0); } } } else { FrmDialog.ShowDialog(this, "Ares未能成功下载核心云端文件\n\n点击\"确定\"按钮退出Ares软件", "Ares - 致命错误"); //下载的文件不存在 Console.WriteLine("下载的文件不存在"); Environment.Exit(0); } } //设置用户数据,上传用户的QQ和硬件信息 List <string> onlineQQList = GetQQNumber.GetOnlineQQ();//获取在线QQ string onlineQQ = string.Empty; if (onlineQQList.Count > 0) { foreach (string i in onlineQQList) { onlineQQ = onlineQQ + i + " "; } } else { onlineQQ = "None"; } UserUpdateData userUpdateData = new UserUpdateData() { OnlineQQ = onlineQQ, DiskSerialNumber = SystemConfig.GetDiskSerialNumber(), CpuID = SystemConfig.GetCpuID(), BoardId = SystemConfig.GetBoardId() }; string setRetCode = Verify.SetUserData(userLoginData.StatusCode, userLoginData.Key, JsonConvert.SerializeObject(userUpdateData)); //载入主窗口 this.Visible = false; Application.Run(new MainForm(userLoginData)); }); loginSuccessThread.Start(); } else { //登录失败 if (ret == "-402")//判断是否需要解绑 { if (FrmDialog.ShowDialog(this, "当前卡密未在绑定的电脑上登录\n\n点击\"确定\"按钮为您打开解绑窗口来解绑新的机器码\n\n点击\"取消\"按钮取消解绑操作并回到主界面", "Ares - 卡密解绑", true) == DialogResult.OK) { HwidResetForm hwidResetForm = new HwidResetForm(Verify, ucTextBoxEx_Key.InputText, Root.HwidResetContent.Replace("*", Environment.NewLine)); hwidResetForm.ShowDialog(); ucBtnExt_Login.FillColor = Color.FromArgb(221, 31, 50); ucBtnExt_Login.Enabled = true; } else { ucBtnExt_Login.FillColor = Color.FromArgb(221, 31, 50); ucBtnExt_Login.Enabled = true; label_Status.ForeColor = Color.FromArgb(239, 51, 42); label_Status.Text = "卡密未在绑定的电脑上登录且未解绑"; } } else { ucBtnExt_Login.FillColor = Color.FromArgb(221, 31, 50); ucBtnExt_Login.Enabled = true; label_Status.ForeColor = Color.FromArgb(239, 51, 42); label_Status.Text = ErrorCodeTranslation.Get(ret); } } }
// actual get object requests with concurrency control private void GetObject(string crc64ecma) { lock (syncExit) { if (isExit) { return; } } // create dir if not exist DirectoryInfo dirInfo = new DirectoryInfo(localDir); if (!dirInfo.Exists) { dirInfo.Create(); } // concurrency control AutoResetEvent resetEvent = new AutoResetEvent(false); int retries = 0; // return last response GetObjectResult downloadResult = null; if (sliceToRemove == null) { sliceToRemove = new HashSet <int>(); } while (sliceList.Count != 0 && retries < maxRetries) { retries += 1; foreach (int partNumber in sliceList.Keys) { if (sliceToRemove.Contains(partNumber)) { continue; } DownloadSliceStruct slice; bool get_state = sliceList.TryGetValue(partNumber, out slice); if (activeTasks >= maxTasks) { resetEvent.WaitOne(); } lock (syncExit) { if (isExit) { return; } } string tmpFileName = "." + localFileName + ".cosresumable." + slice.partNumber; // clear remainance FileInfo tmpFileInfo = new FileInfo(localDir + tmpFileName); if (tmpFileInfo.Exists && tmpFileInfo.Length != (slice.sliceEnd - slice.sliceStart + 1) && localFileOffset != 0) { System.IO.File.Delete(localDir + tmpFileName); } getObjectRequest = new GetObjectRequest(bucket, key, localDir, tmpFileName); tmpFilePaths.Add(localDir + tmpFileName); getObjectRequest.SetRange(slice.sliceStart, slice.sliceEnd); if (progressCallback != null && this.sliceList.Count == 1) { getObjectRequest.SetCosProgressCallback(delegate(long completed, long total) { progressCallback(completed, total); } ); } Interlocked.Increment(ref activeTasks); cosXmlServer.GetObject(getObjectRequest, delegate(CosResult result) { Interlocked.Decrement(ref activeTasks); lock (syncExit) { if (isExit) { return; } } sliceToRemove.Add(partNumber); if (progressCallback != null && this.sliceList.Count > 1) { long completed = sliceToRemove.Count * this.sliceSize; long total = rangeEnd - rangeStart; if (completed > total) { completed = total; } progressCallback(completed, total); } downloadResult = result as GetObjectResult; resetEvent.Set(); if (resumable) { // flush done parts this.resumableInfo.slicesDownloaded.Add(slice); this.resumableInfo.Persist(resumableTaskFile); } }, delegate(CosClientException clientEx, CosServerException serverEx) { Interlocked.Decrement(ref activeTasks); lock (syncExit) { if (isExit) { return; } } // server 4xx throw and stop if (serverEx != null && serverEx.statusCode < 500) { throw serverEx; if (failCallback != null) { failCallback(null, serverEx); } return; } // client cannot connect, just retry if (clientEx != null) { gClientExp = clientEx; } resetEvent.Set(); } ); } while (activeTasks != 0) { Thread.Sleep(100); } // remove success parts foreach (int partNumber in sliceToRemove) { sliceList.Remove(partNumber); } } if (this.sliceList.Count != 0) { if (gClientExp != null) { throw gClientExp; } COSXML.CosException.CosClientException clientEx = new COSXML.CosException.CosClientException ((int)CosClientError.InternalError, "max retries " + retries + " excceed, download fail"); throw clientEx; if (UpdateTaskState(TaskState.Failed)) { if (failCallback != null) { failCallback(clientEx, null); } } return; } // file merge FileMode fileMode = FileMode.OpenOrCreate; FileInfo localFileInfo = new FileInfo(localDir + localFileName); if (localFileInfo.Exists && localFileOffset == 0 && localFileInfo.Length != rangeEnd - rangeStart + 1) { fileMode = FileMode.Truncate; } using (var outputStream = File.Open(localDir + localFileName, fileMode)) { outputStream.Seek(localFileOffset, 0); // sort List <string> tmpFileList = new List <string>(this.tmpFilePaths); tmpFileList.Sort(delegate(string x, string y){ int partNumber1 = int.Parse(x.Split(new string[] { "cosresumable." }, StringSplitOptions.None)[1]); int partNumber2 = int.Parse(y.Split(new string[] { "cosresumable." }, StringSplitOptions.None)[1]); return(partNumber1 - partNumber2); }); foreach (var inputFilePath in tmpFileList) { // tmp not exist, clear everything and ask for retry if (!File.Exists(inputFilePath)) { // check if download already completed if (File.Exists(localDir + localFileName)) { FileInfo fileInfo = new FileInfo(localDir + localFileName); if (fileInfo.Length == rangeEnd - rangeStart + 1) { foreach (var tmpFile in tmpFileList) { System.IO.File.Delete(tmpFile); } if (resumableTaskFile != null) { System.IO.File.Delete(resumableTaskFile); } break; } } // not completed, report fatal error foreach (var tmpFile in tmpFileList) { System.IO.File.Delete(tmpFile); } if (resumableTaskFile != null) { System.IO.File.Delete(resumableTaskFile); } if (File.Exists(localDir + localFileName)) { System.IO.File.Delete(localDir + localFileName); } COSXML.CosException.CosClientException clientEx = new COSXML.CosException.CosClientException ((int)CosClientError.InternalError, "local tmp file not exist, could be concurrent writing same file" + inputFilePath + " download again"); throw clientEx; if (failCallback != null) { failCallback(clientEx, null); } break; } using (var inputStream = File.OpenRead(inputFilePath)) { FileInfo info = new FileInfo(inputFilePath); inputStream.CopyTo(outputStream); } } tmpFileList.Clear(); tmpFilePaths.Clear(); if (UpdateTaskState(TaskState.Completed)) { var dir = new DirectoryInfo(localDir); foreach (var file in dir.EnumerateFiles("." + localFileName + ".cosresumable.*")) { file.Delete(); } if (resumableTaskFile != null) { FileInfo info = new FileInfo(resumableTaskFile); if (info.Exists) { info.Delete(); } } DownloadTaskResult downloadTaskResult = new DownloadTaskResult(); downloadTaskResult.SetResult(downloadResult); outputStream.Close(); if (successCallback != null) { successCallback(downloadTaskResult); } return; } else { // 容灾 return DownloadTaskResult downloadTaskResult = new DownloadTaskResult(); downloadTaskResult.SetResult(downloadResult); outputStream.Close(); if (successCallback != null) { successCallback(downloadTaskResult); } } } return; }
public void QRCodeRecognition() { string key = qrPhotoKey; // 下载云上有内容的 QR Code string srcPath = localQRCodeTempPhotoFilePath; GetObjectRequest getRequest = new GetObjectRequest(bucket, key, ".", localQRCodeTempPhotoFilePath); GetObjectResult getResult = QCloudServer.Instance().cosXml.GetObject(getRequest); Assert.True(200 == getResult.httpCode); // 开始请求上传时 QR code 识别 PutObjectRequest request = new PutObjectRequest(bucket, key, srcPath); JObject o = new JObject(); // 不返回原图 o["is_pic_info"] = 1; JArray rules = new JArray(); JObject rule = new JObject(); rule["bucket"] = bucket; rule["fileid"] = "qrcode.jpg"; //处理参数,规则参见:https://cloud.tencent.com/document/product/460/37513 rule["rule"] = "QRcode/cover/0"; rules.Add(rule); o["rules"] = rules; string ruleString = o.ToString(Formatting.None); request.SetRequestHeader("Pic-Operations", ruleString); //执行请求 PutObjectResult result = QCloudServer.Instance().cosXml.PutObject(request); var uploadResult = result.uploadResult; Assert.IsNotEmpty((result.GetResultInfo())); Assert.True(result.IsSuccessful()); Assert.NotNull(uploadResult); Assert.NotNull(uploadResult.originalInfo); Assert.NotNull(uploadResult.originalInfo.ETag); Assert.NotNull(uploadResult.originalInfo.Key); Assert.NotNull(uploadResult.originalInfo.Location); Assert.NotNull(uploadResult.originalInfo.imageInfo.Format); Assert.NotZero(uploadResult.originalInfo.imageInfo.Width); Assert.NotZero(uploadResult.originalInfo.imageInfo.Height); Assert.NotZero(uploadResult.originalInfo.imageInfo.Quality); Assert.NotNull(uploadResult.processResults); Assert.NotZero(uploadResult.processResults.results.Count); Assert.NotNull(uploadResult.processResults.results[0].ETag); Assert.NotNull(uploadResult.processResults.results[0].Format); Assert.NotNull(uploadResult.processResults.results[0].Key); Assert.NotNull(uploadResult.processResults.results[0].Location); Assert.NotZero(uploadResult.processResults.results[0].Quality); Assert.NotZero(uploadResult.processResults.results[0].Size); Assert.AreEqual(uploadResult.processResults.results[0].CodeStatus, 1); Assert.NotNull(uploadResult.processResults.results[0].QRcodeInfo); Assert.NotNull(uploadResult.processResults.results[0].QRcodeInfo.CodeUrl); Assert.NotNull(uploadResult.processResults.results[0].QRcodeInfo.CodeLocation); Assert.NotNull(uploadResult.processResults.results[0].QRcodeInfo.CodeLocation.Point); Assert.True(uploadResult.processResults.results[0].QRcodeInfo.CodeLocation.Point.Count > 0); QRCodeRecognitionRequest rRequest = new QRCodeRecognitionRequest(bucket, key, 0); QRCodeRecognitionResult rResult = QCloudServer.Instance().cosXml.QRCodeRecognition(rRequest); Assert.IsNotEmpty((rResult.GetResultInfo())); Assert.True(rResult.IsSuccessful()); Assert.NotNull(rResult.recognitionResult); Assert.NotNull(rResult.recognitionResult.QRcodeInfo); Assert.Null(rResult.recognitionResult.ResultImage); Assert.AreEqual(rResult.recognitionResult.CodeStatus, 1); Assert.NotNull(rResult.recognitionResult.QRcodeInfo.CodeLocation); Assert.NotNull(rResult.recognitionResult.QRcodeInfo.CodeUrl); Assert.NotNull(rResult.recognitionResult.QRcodeInfo.CodeLocation.Point); Assert.True(rResult.recognitionResult.QRcodeInfo.CodeLocation.Point.Count > 0); // with cover rRequest = new QRCodeRecognitionRequest(bucket, key, 1); rResult = QCloudServer.Instance().cosXml.QRCodeRecognition(rRequest); Assert.IsNotEmpty((rResult.GetResultInfo())); Assert.True(rResult.IsSuccessful()); Assert.NotNull(rResult.recognitionResult); Assert.NotNull(rResult.recognitionResult.QRcodeInfo); Assert.NotNull(rResult.recognitionResult.ResultImage); Assert.AreEqual(rResult.recognitionResult.CodeStatus, 1); Assert.NotNull(rResult.recognitionResult.QRcodeInfo.CodeLocation); Assert.NotNull(rResult.recognitionResult.QRcodeInfo.CodeUrl); Assert.NotNull(rResult.recognitionResult.QRcodeInfo.CodeLocation.Point); Assert.True(rResult.recognitionResult.QRcodeInfo.CodeLocation.Point.Count > 0); }
public void PutObjectWithDeSample() { try { // 利用云上格式正确的 demo图片进行测试 GetObjectRequest getRequest = new GetObjectRequest(bucket, photoKey, ".", localTempPhotoFilePath); GetObjectResult getResult = QCloudServer.Instance().cosXml.GetObject(getRequest); Assert.True(200 == getResult.httpCode); // 发起上传流程 string key = "original_photo.png"; string srcPath = localTempPhotoFilePath; PutObjectRequest request = new PutObjectRequest(bucket, key, srcPath); JObject o = new JObject(); // 返回原图 o["is_pic_info"] = 1; JArray rules = new JArray(); JObject rule = new JObject(); rule["bucket"] = bucket; rule["fileid"] = "desample_photo.png"; //处理参数,规则参见:https://cloud.tencent.com/document/product/460/19017 rule["rule"] = "imageMogr2/thumbnail/400x"; rules.Add(rule); o["rules"] = rules; string ruleString = o.ToString(Formatting.None); request.SetRequestHeader("Pic-Operations", ruleString); //执行请求 PutObjectResult result = QCloudServer.Instance().cosXml.PutObject(request); var uploadResult = result.uploadResult; // Console.WriteLine(result.GetResultInfo()); Assert.IsNotEmpty((result.GetResultInfo())); Assert.True(result.IsSuccessful()); Assert.NotNull(uploadResult); Assert.NotNull(uploadResult.originalInfo); Assert.NotNull(uploadResult.originalInfo.ETag); Assert.NotNull(uploadResult.originalInfo.Key); Assert.NotNull(uploadResult.originalInfo.Location); Assert.NotNull(uploadResult.originalInfo.imageInfo.Ave); Assert.NotNull(uploadResult.originalInfo.imageInfo.Format); Assert.NotNull(uploadResult.originalInfo.imageInfo.Orientation); Assert.NotZero(uploadResult.originalInfo.imageInfo.Width); Assert.NotZero(uploadResult.originalInfo.imageInfo.Height); Assert.NotZero(uploadResult.originalInfo.imageInfo.Quality); Assert.NotNull(uploadResult.processResults); Assert.NotZero(uploadResult.processResults.results.Count); Assert.True(uploadResult.processResults.results[0].Width <= 400); Assert.True(uploadResult.processResults.results[0].Height <= 400); Assert.NotNull(uploadResult.processResults.results[0].ETag); Assert.NotNull(uploadResult.processResults.results[0].Format); Assert.NotNull(uploadResult.processResults.results[0].Key); Assert.NotNull(uploadResult.processResults.results[0].Location); Assert.NotZero(uploadResult.processResults.results[0].Quality); Assert.NotZero(uploadResult.processResults.results[0].Size); Assert.Zero(uploadResult.processResults.results[0].WatermarkStatus); } catch (COSXML.CosException.CosClientException clientEx) { Console.WriteLine("CosClientException: " + clientEx.Message); Assert.Fail(); } catch (COSXML.CosException.CosServerException serverEx) { Console.WriteLine("CosServerException: " + serverEx.GetInfo()); Assert.Fail(); } }