public async Task <IActionResult> SignIn(SignData signData) { if (!ModelState.IsValid) { return(BadRequest()); } User user = await UserService.CheckCredentials(signData.Email, signData.Password); if (user == null) { return(Unauthorized("Invalid user or password")); } else if (user.IsBlocked) { return(Unauthorized("Account is blocked after too many failed attempts. Ask a manager to unblock it")); } if (!user.IsVerified) { Task task = UserService.SendVerificationMailAsync(user); return(Unauthorized("User not verified. Verification mail sent again. Check mail")); } else { var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())); identity.AddClaim(new Claim(ClaimTypes.Role, user.Role)); HttpContext.User = new ClaimsPrincipal(identity); return(Ok()); } }
public string SignN3Rsa(string data) { var cspParams = new CspParameters { KeyContainerName = "XML_DSIG_RSA_KEY" }; var key = new RSACryptoServiceProvider(cspParams); var cspBlob = key.ExportCspBlob(false); var base64Blob = Convert.ToBase64String(cspBlob); var rsaFormatter = new RSAPKCS1SignatureFormatter(key); rsaFormatter.SetHashAlgorithm("MD5"); var hash = Md5Helper.GetMd5Hash(data); var base64Hash = Convert.ToBase64String(hash); var sign = rsaFormatter.CreateSignature(hash); var base64Sign = Convert.ToBase64String(sign); var signData = new SignData { Data = data, PublicKey = base64Blob, Hash = base64Hash, Sign = base64Sign }; return(new SerializationHelper <SignData>().Serialize(signData)); }
private void DynamicSignCommand(IPlayer player, string command, string[] args) { if (!player.HasPermission(permAdmin)) { player.Reply(Lang("Not allowed", player.Id, command)); return; } RaycastHit hit; Signage sign = null; var basePlayer = player.Object as BasePlayer; if (Physics.Raycast(basePlayer.eyes.HeadRay(), out hit, 2f)) { sign = hit.transform.GetComponentInParent <Signage>(); } if (sign == null) { player.Reply(Lang("No signs found", player.Id)); return; } if (storedData.Signs.ContainsKey(sign.net.ID)) { player.Reply(Lang("Already a dynamic sign", player.Id)); return; } CreateSign(player, sign, args.Length >= 1 ? args[0] : "death"); var info = new SignData(sign); storedData.Signs.Add(sign.net.ID, info); Interface.Oxide.DataFileSystem.WriteObject(Name, storedData); }
public override void Read(BinaryReader br) { dataHead = new NodeBoundData(br); flag = br.ReadUInt32(); distance = br.ReadByte(); roadNum = br.ReadUInt32(); matNum = br.ReadUInt32(); startIndex = br.ReadUInt32(); endIndex = br.ReadUInt32(); dataRight = new RoadData(br); dataLeft = new RoadData(br); centerNum = br.ReadUInt16(); tangent = br.ReadSingle(); unknown = br.ReadUInt32(); signCount = br.ReadUInt32(); if (signCount > 0) { signs = new SignData[signCount]; for (int i = 0; i < signCount; i++) { signs[i] = new SignData(br); } } brushCount = br.ReadUInt32(); if (brushCount > 0) { brushs = new BrushData[brushCount]; for (int i = 0; i < brushCount; i++) { brushs[i] = new BrushData(br); } } }
//INFO: метод для тестирования public string SignN3Gost(string data, string mimeType) { var storeCurrentUser = new X509Store(StoreName.My, StoreLocation.CurrentUser); storeCurrentUser.Open(OpenFlags.ReadOnly); var coll = storeCurrentUser.Certificates .Find(X509FindType.FindByThumbprint, "4d 19 79 84 52 9a 80 4a c4 86 3a 82 6a 8d ab 85 3f 95 e5 01", false)[0]; //b8 be f8 22 e8 63 2a 74 d4 2e 58 df 91 9c 2f e3 75 ea e1 e4 просрочен //4d 19 79 84 52 9a 80 4a c4 86 3a 82 6a 8d ab 85 3f 95 e5 01 var gost = (Gost3410CryptoServiceProvider)coll.PrivateKey; var base64Blob = Convert.ToBase64String(coll.Export(X509ContentType.Cert)); var gostSignatureFormatter = new GostSignatureFormatter(gost); gostSignatureFormatter.SetHashAlgorithm("Gost3411"); var hash = Md5Helper.GetGost3411Hash(data); var base64Hash = Convert.ToBase64String(hash); var sign = gostSignatureFormatter.CreateSignature(hash); var base64Sign = Convert.ToBase64String(sign); var signData = new SignData { Data = data, MIMEType = mimeType, PublicKey = base64Blob, Hash = base64Hash, Sign = base64Sign }; return(new SerializationHelper <SignData>().Serialize(signData)); }
public static byte[] Sign(SignData signData, Key ecKey) { string json = JsonConvert.SerializeObject(signData); byte[] bytes = Encoding.UTF8.GetBytes(json); return(Sign(bytes, ecKey)); }
void SignChatCmd(BasePlayer player) { if (!HasPermission(player, "deathsigns.admin")) { PrintToChat(player, NoPermission); return; } // Check for sign to use RaycastHit hit; Signage sign = null; if (Physics.Raycast(player.eyes.HeadRay(), out hit, 2f)) { sign = hit.transform.GetComponentInParent <Signage>(); } if (sign == null) { PrintToChat(player, NoSignsFound); return; } if (storedData.Signs.ContainsKey(sign.net.ID)) { PrintToChat(player, "Already a death sign!"); return; } // Create sign image var text = $"{storedData.Deaths}+{(storedData.Deaths == 1 ? "death" : "deaths")}"; const string bgColor = "ffffff"; const string textColor = "000000"; const int textSize = 80; const int width = 350; const int height = 150; var url = $"http://placeholdit.imgix.net/~text?txtsize={textSize}&txt={text}&w={width}&h={height}"; uWeb.Add(url, player, sign); // Store updated data var info = new SignData(sign); storedData.Signs.Add(sign.net.ID, info); Interface.Oxide.DataFileSystem.WriteObject(Name, storedData); // Lock sign to prevent player edits sign.SetFlag(BaseEntity.Flags.Locked, true); sign.SendNetworkUpdate(); }
public string Notice(string sourceID, NoticeRequest1006 sendData) { string data = JsonUtils.Serialize(sendData); TxtLoger.SavaLogToTXT("推送,前data为:" + data, "a"); var signData = new SignData(sourceID); string signStr = signData.Sign(data); var obj = new { data = Base64Utils.EncodeBase64String(data), signdata = Base64Utils.EncodeBase64String(signStr), }; TxtLoger.SavaLogToTXT("obj是 数据是:" + obj.ToJson(), "a"); return(JsonUtils.Serialize(obj)); }
public byte[] Sign(ProtoMessage message, Wallet wallet, TransactionOption options) { SignData signData = new SignData(); signData.ChainId = wallet.ChainId; signData.AccountNumber = wallet.AccountNumber.ToString(); signData.Sequence = wallet.Sequence.ToString(); signData.Msgs = new List <ProtoMessage>() { message }; signData.Memo = options.Memo; signData.Source = options.Source; signData.Data = options.Data; return(CryptoUtility.Sign(signData, wallet.EcKey)); }
public async Task <IActionResult> SignUp(SignData signData) { User user = await UserService.SignupAsync(signData); if (user == null) { return(Problem("No user was created")); } else if (user.Email == null) { return(Conflict("Account already exists")); } Task task = UserService.SendVerificationMailAsync(user); return(Ok("Check for verification mail")); }
protected void Page_Load(object sender, EventArgs e) { string MerId = Request["MerId"]; //商户号 string OrdId = Request["OrderNo"]; //订单号 string TransAmt = Request["Amount"]; //订单金额 string CuryId = Request["CurrencyCode"]; //货币代码 string TransDate = Request["TransDate"]; //订单日期 string TransType = Request["TransType"]; //交易类型 string Priv1 = Request["Priv1"]; //备注 string GateId = Request["GateId"]; //网关 string status = Request["status"]; //status表示交易状态只有"1001"表示支付成功,其他状态均表示未成功的交易。因此验证签名数据通过后,还需要判定交易状态代码是否为"1001" string CheckValue = Request["checkvalue"]; //签名数据 try { logger.Info(Request.UserHostAddress + "请求:" + Request.Form.ToString()); bool res = SignData.check(MerId, OrdId, TransAmt, CuryId, TransDate, TransType, status, CheckValue); if (res) { //验证签名数据通过后,一定要判定交易状态代码是否为"1001",实现代码请商户自行编写 if (status.Equals("1001")) { logger.Info("订单支付成功,通知来自银联支付(订单号:" + OrdId + ")"); //TODO:支付成功后的处理 } else { logger.Info("服务器签名验证成功,通知来自银联支付,未支付:" + OrdId); } } } catch (Exception ex) { logger.Error("验证失败", ex); throw ex; } finally { logger.Flush(); } }
protected override List<Map> OnLoadMaps() { var maps = new List<Map>(); var blocks = Blocks.Of(BotBits); for (var x = 1; x < blocks.Width - MapWidth; x++) { for (var y = 1; y < blocks.Height - MapHeight; y++) { var block = blocks.At(x, y).Foreground.Block; if (block.Type != ForegroundType.Text || !block.Text.ToLower().StartsWith("scan:")) continue; var data = new SignData(block.Text.Substring(5).Trim(), Room.Of(BotBits).Owner); maps.Add(new Map(blocks, new Rectangle(x, y + 1, MapWidth, MapHeight), data.Name, data.Creators)); } } return maps; }
//public ActionResult Index() //{ // BaseRequest baseRequest; // var verifyResult = Verify(out baseRequest); // //loger.Info(string.Format("请求数据验证结果:编号:{0};信息:{1}", (int)verifyResult.Code, verifyResult.ErrorMessage)); // if (verifyResult.IsPass) // { // var response = Excute(baseRequest); // Notice(response, baseRequest.SourceID); // } // else // { // if (verifyResult.Code != EnumPlatform.EResponseCode.不存在此机构) // { // var response = BaseResponse.CreateBaseResponse(verifyResult.Code, verifyResult.ErrorMessage, null); // Notice(response, baseRequest.SourceID); // }; // } // ViewBag.aa = baseRequest.SourceID; // ViewBag.bb = baseRequest.BizCode; // //return Json(JsonUtils.Serialize(verifyResult)); // //return View(JsonUtils.Serialize(verifyResult)); // return View(); //} /// <summary> /// 返回数据给第三方 /// </summary> /// <param name="response"></param> /// <param name="sourceId"></param> private void Notice(BaseResponse response, string sourceId) { if (sourceId == null) { sourceId = "10001"; } var responseData = JsonUtils.Serialize(response); var signData = new SignData(sourceId); var signstr = signData.Sign(responseData); //loger.Info(string.Format("处理结果数据(base64编码前):{0}", responseData)); //loger.Info(string.Format("处理结果较验码(base64编码前):{0}", signstr)); var httpMessage = new HttpMessage { data = Base64Utils.EncodeBase64String(responseData), signdata = Base64Utils.EncodeBase64String(signstr) }; TxtLoger.SavaLogToTXT("data=" + Base64Utils.EncodeBase64String(responseData) + " ,signdata=" + Base64Utils.EncodeBase64String(signstr), "a"); //var responseStr = JsonUtils.Serialize(httpMessage); //WriteResponse(httpMessage.ToString()); WriteResponse(JsonUtils.Serialize(httpMessage)); }
protected override List <Map> OnLoadMaps() { var maps = new List <Map>(); var blocks = Blocks.Of(BotBits); for (var x = 1; x < blocks.Width - MapWidth; x++) { for (var y = 1; y < blocks.Height - MapHeight; y++) { var block = blocks.At(x, y).Foreground.Block; if (block.Type != ForegroundType.Text || !block.Text.ToLower().StartsWith("scan:")) { continue; } var data = new SignData(block.Text.Substring(5).Trim(), Room.Of(BotBits).Owner); maps.Add(new Map(blocks, new Rectangle(x, y + 1, MapWidth, MapHeight), data.Name, data.Creators)); } } return(maps); }
void SignChatCmd(BasePlayer player) { if (!HasPermission(player, "charitysigns.admin")) { PrintToChat(player, NoPermission); return; } // Check for sign to use RaycastHit hit; Signage sign = null; if (Physics.Raycast(player.eyes.HeadRay(), out hit, 2f)) { sign = hit.transform.GetComponentInParent <Signage>(); } if (sign == null) { PrintToChat(player, NoSignsFound); return; } if (eventData.Signs.ContainsKey(sign.net.ID)) { PrintToChat(player, "Already a charity sign!"); return; } CreateSign(player, sign); // Store updated data var info = new SignData(sign); eventData.Signs.Add(sign.net.ID, info); Interface.Oxide.DataFileSystem.WriteObject(Name, eventData); }
public async Task <IActionResult> ChangePassword(SignData signData) { if (!ModelState.IsValid) { return(BadRequest()); } User user = await UserService.CheckCredentials(signData.Email, signData.Password); if (user == null) { return(Unauthorized("Invalid user or password")); } else if (user.IsBlocked) { return(Unauthorized("Account is blocked after too many failed attempts. Ask a manager to unblock it")); } if (!user.IsVerified) { return(Unauthorized("User not verified. Request sign-in to get verification mail sent again")); } else { user.Password = signData.NewPassword; int result = await UserService.UpdateUserAsync(user); if (result == 1) { return(Ok("Password has been changed")); } else { return(Problem("Password could not be changed")); } } }
public async Task <User> SignupAsync(SignData signData) { User user = new User() { Email = signData.Email, //PwdHash = Utils.GetMd5Hash(signData.Password), Password = signData.Password, IsVerified = false, SignInFailCount = 0 }; if (!UsersExist()) // First user is admin { user.Role = Roles.ADMIN; } else { user.Role = Roles.USER; } int result = await InsertUserAsync(user); if (result == 1) { return(user); } if (result == -1) { user.Email = null; return(user); } else { return(null); } }
static void WriteTable(string[] words) { if (lasthash == null) { Console.WriteLine("get block hash first."); return; } WriteTask write = new WriteTask(); //必须添加上一个块的hash,要不然服务器不会接受的 write.extData = new System.Collections.Generic.Dictionary <string, byte[]>(); write.extData["lasthash"] = lasthash; //createtable 123; //write.CreateTable(new TableInfo(new byte[] { 0x01, 0x02, 0x03 }, "hello world", "", DBValue.Type.String)); write.Put(new byte[] { 0x01, 0x02, 0x03 }, "123".ToBytes_UTF8Encode(), DBValue.FromValue(DBValue.Type.String, "balabala")); var srcdata = write.ToBytes(); var wiftest = "L2CmHCqgeNHL1i9XFhTLzUXsdr5LGjag4d56YY98FqEi4j5d83Mv";//对应地址 AdsNmzKPPG7HfmQpacZ4ixbv9XJHJs2ACz 作为服务器配置的writer var prikey = ThinNeo.Helper_NEO.GetPrivateKeyFromWIF(wiftest); var pubkey = ThinNeo.Helper_NEO.GetPublicKey_FromPrivateKey(prikey); var address = ThinNeo.Helper_NEO.GetAddress_FromPublicKey(pubkey); SignData signdata = SignData.Sign(prikey, srcdata); var b = signdata.VerifySign(address, srcdata); Console.WriteLine("sign result=" + b); var msg = client.Post_write(srcdata, signdata); Console.WriteLine("post write result block[" + msg.blockid + "] = " + msg.blockhash.ToString_Hex()); }
//public async Task<IHttpActionResult> Get() { // return Ok("成功"); //} public async Task <IHttpActionResult> Post([FromBody] N_BuildPostVm model) { if (!ModelState.IsValid) { throw new Exception("请求参数不正确"); } Dictionary <string, object> _dictData = new Dictionary <string, object>(); _dictData.Add("TimeStamp", model.TimeStamp); _dictData.Add("Url", model.Url); _dictData.Add("ProjectId", model.ProjectId); _dictData.Add("Unit", model.Unit); var _sign = SignData.Md5SignDict("1234567890", _dictData); if (_sign != model.Sign) { throw new Exception("签名不正确"); } //验证通过,下载Qiniu上面的zip文件 string _savePath = Path.Combine(Constants.Temp, Path.GetFileName(model.Url)); WebClient myWebClient = new WebClient(); myWebClient.DownloadFile(model.Url, _savePath); //判断文件是否存在 if (!IOUtils.FileExists(_savePath)) { //表示文件下载失败 throw new Exception(model.Url + " 下载失败"); } //解压文件 ZipFile.ExtractToDirectory(_savePath, Constants.Temp); //删除zip文件 FileUtils.DeleteFile(_savePath); string _sourcePath = Path.Combine(Constants.Temp, model.ProjectId, model.Unit); string _targetPath = Path.Combine(Constants.RootPath, model.ProjectId, model.Unit); if (!IOUtils.DirExists(_targetPath)) { IOUtils.CreateDir(_targetPath); } FileUtils.CopyDir(_sourcePath, _targetPath); FileUtils.DeleteDir(Path.Combine(Constants.Temp, model.ProjectId)); //判断是否存在build.sh脚本文件,如果有就执行 string shellFilePath = Path.Combine(_targetPath, Constants.ScripteFile); if (IOUtils.FileExists(shellFilePath)) { int _code = CMDUtils.Execute(shellFilePath); if (_code == 0) { //_logEngin.Debug("build " + _slnFile + " Success"); } else { //_logEngin.Debug("build " + _slnFile + " Fail"); } } return(Ok()); }
/// <summary> /// Initializes a new instance of the <see cref="SignPostBlock"/> class. /// </summary> public SignPostBlock() { Data = new SignData(); }
public void SignDataTest() { InputOutput input = new InputOutput { Address = "tbnb18086qc9yxtk5ufddple8upf0k3072vvagpm2ml", Coins = new List <Token> { new Token { Denom = "PND-943", Amount = 100000000 } } }; InputOutput output = new InputOutput { Address = "tbnb18086qc9yxtk5ufddple8upf0k3072vvagpm2ml", Coins = new List <Token> { new Token { Denom = "PND-943", Amount = 100000000 } } }; TransferMessage transferMessage = new TransferMessage { Inputs = new List <InputOutput> { input }, Outputs = new List <InputOutput> { output } }; SignData signData = new SignData { ChainId = "Binance-Chain-Nile", AccountNumber = "667519", Sequence = "0", Memo = "", Msgs = new TransferMessage[] { transferMessage }, Source = "3", Data = null }; //JsonSerializer serializer = new JsonSerializer(); string json = JsonConvert.SerializeObject(signData); // bytes = [123, 34, 97, 99, 99, 111, 117, 110, 116, 95, 110, 117, 109, 98, 101, 114, 34, 58, 34, 54, 54, 55, 53, 49, 57, 34, 44, 34, 99, 104, 97, 105, 110, 95, 105, 100, 34, 58, 34, 66, 105, 110, 97, 110, 99, 101, 45, 67, 104, 97, 105, 110, 45, 78, 105, 108, 101, 34, 44, 34, 100, 97, 116, 97, 34, 58, 110, 117, 108, 108, 44, 34, 109, 101, 109, 111, 34, 58, 34, 34, 44, 34, 109, 115, 103, 115, 34, 58, 91, 123, 34, 105, 110, 112, 117, 116, 115, 34, 58, 91, 123, 34, 97, 100, 100, 114, 101, 115, 115, 34, 58, 34, 116, 98, 110, 98, 49, 56, 48, 56, 54, 113, 99, 57, 121, 120, 116, 107, 53, 117, 102, 100, 100, 112, 108, 101, 56, 117, 112, 102, 48, 107, 51, 48, 55, 50, 118, 118, 97, 103, 112, 109, 50, 109, 108, 34, 44, 34, 99, 111, 105, 110, 115, 34, 58, 91, 123, 34, 97, 109, 111, 117, 110, 116, 34, 58, 49, 48, 48, 48, 48, 48, 48, 48, 48, 44, 34, 100, 101, 110, 111, 109, 34, 58, 34, 80, 78, 68, 45, 57, 52, 51, 34, 125, 93, 125, 93, 44, 34, 111, 117, 116, 112, 117, 116, 115, 34, 58, 91, 123, 34, 97, 100, 100, 114, 101, 115, 115, 34, 58, 34, 116, 98, 110, 98, 49, 56, 48, 56, 54, 113, 99, 57, 121, 120, 116, 107, 53, 117, 102, 100, 100, 112, 108, 101, 56, 117, 112, 102, 48, 107, 51, 48, 55, 50, 118, 118, 97, 103, 112, 109, 50, 109, 108, 34, 44, 34, 99, 111, 105, 110, 115, 34, 58, 91, 123, 34, 97, 109, 111, 117, 110, 116, 34, 58, 49, 48, 48, 48, 48, 48, 48, 48, 48, 44, 34, 100, 101, 110, 111, 109, 34, 58, 34, 80, 78, 68, 45, 57, 52, 51, 34, 125, 93, 125, 93, 125, 93, 44, 34, 115, 101, 113, 117, 101, 110, 99, 101, 34, 58, 34, 48, 34, 44, 34, 115, 111, 117, 114, 99, 101, 34, 58, 34, 51, 34, 125] byte[] bytes = Encoding.UTF8.GetBytes(json); byte[] hash; using (SHA256 sha256 = SHA256.Create()) { // hash = [-124, 96, -11, -122, -27, -7, 103, -38, -29, 0, -34, 45, 98, -83, 32, 16, -11, 108, -8, -88, -66, -80, 106, 14, -13, 34, -115, 99, -94, -124, -101, -117] hash = sha256.ComputeHash(bytes); } Wallet wallet = Wallet.FromPrivateKey("f0e87ed55fa3d86f62b38b405cbb5f732764a7d5bc690da45a32aa3f2fc81a36", BinanceDexEnvironment.TEST_NET); //string resultB = wallet.EcKey.SignMessage(bytes); //string resultS = wallet.EcKey.SignMessage(json); uint256 hash256 = Hashes.Hash256(bytes); uint256 uint256 = new uint256(hash, false); uint256 uint256le = new uint256(hash, true); //uint256 uint256 = new uint256("8460f586e5f967dae300de2d62ad2010f56cf8a8beb06a0ef3228d63a2849b8b"); // message for GenerateSignature [-124, 96, -11, -122, -27, -7, 103, -38, -29, 0, -34, 45, 98, -83, 32, 16, -11, 108, -8, -88, -66, -80, 106, 14, -13, 34, -115, 99, -94, -124, -101, -117] ECDSASignature signature = wallet.EcKey.Sign(uint256le, false); byte[] signatureBytes = new byte[64]; signature.R.ToByteArrayUnsigned().CopyTo(signatureBytes, 0); signature.S.ToByteArrayUnsigned().CopyTo(signatureBytes, 32); // r = 61420091277463284201584464261002339752469911249959494312431854777400008021097 // s = 9337502753576151745268672761590576963567913315001541648793269425462248583710 // signature result = [-121, -54, -118, 43, 107, -25, 50, -112, -101, 34, -63, -121, -111, -90, 109, -72, -95, -42, 55, -87, -108, -42, -21, -99, -2, -74, 13, -106, 99, -34, -108, 105, 20, -92, -42, -38, 116, -51, 15, 44, -17, -29, -119, -53, -119, -51, 58, -48, -38, -92, 39, -99, -64, 119, -81, 112, -97, -103, 112, -91, -71, -119, -78, 30] //byte[] resultBytes = Encoders.Base64.DecodeData(resultB); }
static void BuildThreadChild() { while (true) { //请求http获取打包任务 long _cDate = DateTime.Now.ToFileTime(); Dictionary <string, object> _dictData = new Dictionary <string, object>(); _dictData.Add("TimeStamp", _cDate); var _sign = SignData.Md5SignDict(_configBean.SecurityKey, _dictData); string _postDataStr = "TimeStamp=" + _cDate + "&Sign=" + _sign; string _result = HttpUtils.HttpGet(Constants.GET_BUILD_TASK, _postDataStr); //如果取到任务 if (_result != null && _result.Length > 0 && !"null".Equals(_result)) { BuildTaskBean _buildBean = new BuildTaskBean(); try { JObject _buildConfigObj = JObject.Parse(_result); _buildBean.TaskId = _buildConfigObj.GetValue("Id").ToString(); _buildBean.ProjectId = _buildConfigObj.GetValue("ProjectId").ToString(); _buildBean.ProjectName = _buildConfigObj.GetValue("ProjectName").ToString(); _buildBean.BranchName = _buildConfigObj.GetValue("BranchName").ToString(); } catch (Exception ex) { LogUtils.Error(null, new Exception("解析打包任务数据请求失败 " + _result)); LogUtils.Error(null, ex); throw; } LogEngin _logEngin = new LogEngin(_buildBean.ProjectName + " 项目打包", _buildBean.TaskId); //根据TaskID创建一个临时目录 string _projectTempDir = Path.Combine(Constants.Temp, _buildBean.TaskId, _buildBean.ProjectName); FileUtils.CreateDir(_projectTempDir); _logEngin.Info("创建 " + _projectTempDir + " 临时目录"); //////////////////下载源代码 try { SourceCodeBean _sourceCodeBean = DownloadSourceCode(_logEngin, _buildBean); ////////////////build源代码 BuildSource(_logEngin, _buildBean, _sourceCodeBean, _projectTempDir); } catch (Exception ex) { ////////build失败 _logEngin.Error(ex); _logEngin.IsSuccess = false; } //上传日志文件 string _log = _logEngin.ToHtml(); string _logPath = Path.Combine(Constants.Temp, _buildBean.TaskId + ".html"); IOUtils.WriteUTF8String(_logPath, _log); string _logUrl = UploadLogFile(_logEngin, _logPath); //反馈打包结果 _cDate = DateTime.Now.ToFileTime(); _dictData.Clear(); int _state = (_logEngin.IsSuccess ? 2 : 1); _dictData.Add("TimeStamp", _cDate); _dictData.Add("Id", _buildBean.TaskId); _dictData.Add("State", _state); _dictData.Add("LogUrl", _logUrl); _sign = SignData.Md5SignDict(_configBean.SecurityKey, _dictData); JObject _postDataJson = new JObject(); _postDataJson.Add("Id", _buildBean.TaskId); _postDataJson.Add("State", _state); _postDataJson.Add("LogUrl", _logUrl); _postDataJson.Add("TimeStamp", _cDate); _postDataJson.Add("Sign", _sign); HttpUtils.HttpPut(Constants.GET_BUILD_TASK, _postDataJson.ToString()); Console.WriteLine("Build完成"); } else //没有取到任务,隔段时间再去取 { Thread.Sleep(_configBean.GetBuildTaskInterval * 1000); } } }
//把build文件在Qiniu上面的地址分发给每台服务器 public static void Dispatcher(LogEngin _logEngin, string _projectName, string _environment, string _zipUrl) { //读取当前环境下面的Environment.config文件,获取需要部署的服务器列表,然后循环调用各自服务器的接口 string _environmentConfig = Path.Combine(Constants.CurrentConfigProjects, _projectName, _environment, "Environment.config"); if (!IOUtils.FileExists(_environmentConfig)) { LogUtils.Error(null, new Exception(_environmentConfig + "文件不存在,配置有问题")); return; } string _environmentConfigContent = IOUtils.GetUTF8String(_environmentConfig); try { JObject _environmentConfigObj = JObject.Parse(_environmentConfigContent); foreach (var _item in _environmentConfigObj) { string _unit = _item.Key; //哪个模块 JArray _serviceIds = JArray.Parse(_item.Value.ToString()); //发布到哪些服务器 //循环调用接口发送数据 foreach (string _serviceId in _serviceIds) { string _serviceCofnigPath = Path.Combine(Constants.TargetServices, _serviceId, "TargetService.config"); if (!IOUtils.FileExists(_serviceCofnigPath)) { //表示文件目录不存在 配置有问题 _logEngin.Error(new Exception(_serviceId + " 对应的配置不存在,配置有问题")); continue; } string _serviceCofnigContent = IOUtils.GetUTF8String(_serviceCofnigPath); try { JObject _serviceCofnigObj = JObject.Parse(_serviceCofnigContent); string _host = _serviceCofnigObj.GetValue("Host").ToString(); string _port = _serviceCofnigObj.GetValue("Port").ToString(); //string _sign = _serviceCofnigObj.GetValue("Sign").ToString(); //调用接口,参数 七牛地址,Unit名称 //http://localhost:56905/doAutoDeploy/AutoDeploy_N_Notify string _url = "http://" + _host + ":" + _port + Constants.NOTIFY_DEPLOY; long _cDate = DateTime.Now.ToFileTime(); Dictionary <string, object> _dictData = new Dictionary <string, object>(); _dictData.Add("TimeStamp", _cDate); _dictData.Add("Url", _zipUrl); _dictData.Add("ProjectId", _projectName); _dictData.Add("Unit", _unit); var _sign = SignData.Md5SignDict(_configBean.SecurityKey, _dictData); string _postDataStr = "ProjectId=" + _projectName + "&Unit=" + _unit + "&Url=" + _zipUrl + "&TimeStamp=" + _cDate + "&Sign=" + _sign; try { HttpUtils.HttpPost(_url, _postDataStr); } catch (Exception _ex) { _logEngin.Error(new Exception(_url + " 通知服务器失败! \n" + _ex)); continue; } } catch (Exception _ex) { _logEngin.Error(new Exception(_serviceCofnigPath + " 配置文件内容有误! \n" + _ex)); continue; } } } } catch (Exception _ex) { throw new Exception(_environmentConfig + " 配置文件内容有误! \n" + _ex); } }
static void DeployThreadChild() { while (true) { //请求http获取部署任务 long _cDate = DateTime.Now.ToFileTime(); Dictionary <string, object> _dictData = new Dictionary <string, object>(); _dictData.Add("TimeStamp", _cDate); var _sign = SignData.Md5SignDict(_configBean.SecurityKey, _dictData); string _postDataStr = "TimeStamp=" + _cDate + "&Sign=" + _sign; string _result = HttpUtils.HttpGet(Constants.GET_DEPLOY_TASK, _postDataStr); //如果取到任务 if (_result != null && _result.Length > 0 && !"null".Equals(_result)) { //如果取到任务 DeployTaskBean _deployBean = new DeployTaskBean(); try { JObject _buildConfigObj = JObject.Parse(_result); _deployBean.Id = _buildConfigObj.GetValue("Id").ToString(); _deployBean.TaskId = _buildConfigObj.GetValue("BuildId").ToString(); _deployBean.ProjectName = _buildConfigObj.GetValue("ProjectName").ToString(); _deployBean.BranchName = _buildConfigObj.GetValue("BranchName").ToString(); _deployBean.Environment = _buildConfigObj.GetValue("Environment").ToString(); _deployBean.UpgradeType = _buildConfigObj.GetValue("UpgradeType").ToString();; _deployBean.AutoUpgrade = Boolean.Parse(_buildConfigObj.GetValue("AutoUpgrade").ToString()); } catch (Exception ex) { LogUtils.Error(null, new Exception("解析部署任务数据请求失败 " + _result)); LogUtils.Error(null, ex); throw; } LogEngin _logEngin = new LogEngin("部署", _deployBean.TaskId); try { string _taskTempDir = Path.Combine(Constants.Temp, _deployBean.TaskId); string _projectTempDir = Path.Combine(_taskTempDir, _deployBean.ProjectName); //E:\AutoBuildHome\SourceFile\myProjct\project1\master ////////////////////根据UnitConfig Copy 文件 if (_sourceCodeRootDirs.ContainsKey(_deployBean.TaskId)) { CopyFileByUnitConfig(_logEngin, _deployBean, _sourceCodeRootDirs[_deployBean.TaskId].ToString(), _projectTempDir); string _zipSourceDir = _projectTempDir; ArrayList _modifyFiles = new ArrayList(); ///////////////////判断是否增量升级 if (_deployBean.AutoUpgrade) { //MD5比较文件是否修改 string _sourcePath = Path.Combine(Constants.Temp, _deployBean.TaskId, _deployBean.ProjectName); string _targetPath = Path.Combine(Constants.CurrentVersion, _deployBean.ProjectName); ArrayList _files = new ArrayList(); FileUtils.GetFiles(new DirectoryInfo(_sourcePath), _files); string _outTempDir = Path.Combine(_taskTempDir, "upgrade"); FileUtils.CreateDir(_outTempDir); foreach (string _file in _files) { string _oldFile = _file.Replace(_sourcePath, _targetPath); //文件存在就MD5比较 if (IOUtils.FileExists(_oldFile)) { string _newMD5 = MD5Utils.MD5File(_file); string _oldMD5 = MD5Utils.MD5File(_oldFile); if (!_newMD5.Equals(_oldMD5)) { _logEngin.Info("不一样的文件:" + _file); _modifyFiles.Add(_file); string _outPath = _file.Replace(_taskTempDir, _outTempDir); FileUtils.CopyDirOrFile(_file, _outPath); } } else { _logEngin.Info("新增文件:" + _file); _modifyFiles.Add(_file); string _outPath = _file.Replace(_taskTempDir, _outTempDir); FileUtils.CopyDirOrFile(_file, _outPath); } } if (_modifyFiles.Count > 0) { _zipSourceDir = Path.Combine(_outTempDir, _deployBean.ProjectName); } else { _logEngin.Error(new Exception("选择增量升级但无文件改动,部署失败")); } } if (!_deployBean.AutoUpgrade || _modifyFiles.Count > 0) { //压缩文件 string _buildZip = _deployBean.TaskId + ".zip"; _logEngin.Info("压缩文件 " + _buildZip); string _zipPath = Path.Combine(Constants.Temp, _deployBean.TaskId, _buildZip); ZipFile.CreateFromDirectory(_zipSourceDir, _zipPath, CompressionLevel.Fastest, true); _logEngin.Info(" 压缩 " + _projectTempDir + " 目录,生成" + _buildZip + " 文件"); _logEngin.Info(" 上传 " + _buildZip + " 文件到七牛"); ////////////////////压缩build包,并上传到七牛云 _deployBean.DeployQiniuUrl = UploadZip(_logEngin, _deployBean.TaskId, _deployBean.ProjectName, _zipPath, _buildZip); } //删除临时目录 FileUtils.DeleteDir(Path.Combine(Constants.Temp, _deployBean.TaskId)); } else { throw new Exception("deployed 失败: 不存在 " + _deployBean.TaskId + " build 任务!"); } } catch (Exception _ex) { ////////build失败 _logEngin.Error(_ex); _logEngin.IsSuccess = false; } ////////////////文件上传成功,把文件上传路径传给服务器 _logEngin.Info("本地Deployed完成通知服务器"); ///// _logEngin.Info("组装资源文件完成,通知部署服务器去Qiniu下载资源文件"); Console.WriteLine("组装资源文件完成,通知部署服务器去Qiniu下载资源文件"); if (_logEngin.IsSuccess && _deployBean.DeployQiniuUrl != null && _deployBean.DeployQiniuUrl.Length > 0) { _sourceCodeRootDirs.Remove(_deployBean.TaskId); Dispatcher(_logEngin, _deployBean.ProjectName, _deployBean.Environment, _deployBean.DeployQiniuUrl); } //上传日志文件 string _log = _logEngin.ToHtml(); string _logPath = Path.Combine(Constants.Temp, _deployBean.TaskId + "_deploy.html"); IOUtils.WriteUTF8String(_logPath, _log); string _logUrl = UploadLogFile(_logEngin, _logPath); //请求http获取打包任务 _cDate = DateTime.Now.ToFileTime(); _dictData.Clear(); int _state = (_logEngin.IsSuccess ? 2 : 1); _dictData.Add("TimeStamp", _cDate); _dictData.Add("Id", _deployBean.Id); _dictData.Add("State", _state); _dictData.Add("Url", _deployBean.DeployQiniuUrl); _dictData.Add("LogUrl", _logUrl); _sign = SignData.Md5SignDict(_configBean.SecurityKey, _dictData); JObject _postDataJson = new JObject(); _postDataJson.Add("Id", _deployBean.Id); _postDataJson.Add("State", _state); _postDataJson.Add("Url", _deployBean.DeployQiniuUrl); _postDataJson.Add("LogUrl", _logUrl); _postDataJson.Add("TimeStamp", _cDate); _postDataJson.Add("Sign", _sign); HttpUtils.HttpPut(Constants.GET_DEPLOY_TASK, _postDataJson.ToString()); } else //没有取到任务,隔段时间再去取 { Thread.Sleep(_configBean.GetBuildTaskInterval * 1000); } } }
private static void SetData(this Sign sign, SignData data) { sign.m_nview.GetZDO().Set("text", data.serialized); }