public static void Main(string[] args) { string INPUT_FILE_PATH = @"C:\Users\Mim\Desktop\rr.txt.aes"; string INPUT_FILE_PATH2 = @"../../../AES.EncryptDecrypt/fileReader/input.txt"; string OUTPUT_FILE_PATH = @"C:\Users\Mim\Desktop"; Parameter par = new Parameter(); par.Key = "Thats my Kung Fu"; par.InitialVector = "ABCDEFGHIPQRSTUV"; par.Type = "d"; par.Mode = "ecb"; par.InputFilePath = INPUT_FILE_PATH; par.OutputFolderPath = OUTPUT_FILE_PATH; FileInfo fileInfo = new FileInfo(INPUT_FILE_PATH); var enc = new AESAlgorithm(par); enc.Execute(); Console.Read(); }
public async Task <Result> PreTest([FromBody] PreTestPatams testPatams) { try { var sw = Stopwatch.StartNew(); var appinfo = _appService.GetAppCache(testPatams.AppKey); if (appinfo == null) { return new Result { Status = false, Message = TaskResultStatus.AppKeyError.ToString() } } ; var json = AESAlgorithm.Decrypt(testPatams.PreData, appinfo.AppSecret); //var p= _serializer.Deserialize<PreTestModel>(json); // var dto = p.MapTo<PreTestDto>(); var dto = new PreTestDto(); var pArr = json.Split("&", StringSplitOptions.RemoveEmptyEntries); dto.AppKey = pArr[0]; dto.AppSecret = pArr[1]; dto.MerchantNo = pArr[2]; var rlt = await _preTestService.PreTest(dto); sw.Stop(); Logger.Info($"pretest time:{sw.ElapsedMilliseconds}"); return(rlt); } catch (Exception ex) { Logger.Error("预验失败", ex); return(new Result { Status = false }); } }
public IHttpActionResult ResetPassword(int id) { try { var user = UserInfo.GetOne(id); if (user == null) { return(Failure("未找到该用户")); } user.Password = AESAlgorithm.Encrypto("123456"); UserInfo.Update(user); SystemLog.Add(new SystemLog { Action = "Logout", LogContent = user.Name + "-重置密码", CreateTime = DateTime.Now, UserID = user.ID, RoleID = user.RoleID, DepartmentID = user.DepartmentID, ClientIP = GetIP(), UserName = user.Name, RealName = user.RealName }); return(Success()); } catch (Exception ex) { logger.Error(ex); return(Failure("执行异常")); } }
static void Main(string[] args) { Console.Read(); HttpPost.send(); return; string salt = ""; string textNormal = "hola_"; string textEncrip = ""; salt = Guid.NewGuid().ToString(); textEncrip = RijndaelManagedEncryption.EncryptRijndael(textNormal, salt); textNormal = RijndaelManagedEncryption.DecryptRijndael(textEncrip, salt); Console.WriteLine("---------------------------------------"); Console.WriteLine("salt:" + salt); Console.WriteLine("textEncrip:" + textEncrip); Console.WriteLine("textNormal:" + textNormal); Console.WriteLine("---------------------------------------"); Console.WriteLine("Usando AESAlgorithm:"); textEncrip = AESAlgorithm.Encrypt(textNormal); //string otherTextEncript = AESAlgorithm.Encrypt("hola_"); Console.WriteLine("textNormal:" + textNormal); Console.WriteLine("textEncrip:" + textEncrip); Console.WriteLine("textDecrip:" + AESAlgorithm.Decrypt(textEncrip)); // Error padding code Base64 erroneo a proposito Console.WriteLine("textDecrip2:" + AESAlgorithm.Decrypt("pw7qE1E4o6/1QAKSPv8Jwg==")); Console.Read(); }
private void txt_weixinendportwcf_TextChanged(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txt_weixinendportwcf.Text)) { txt_weixinepPW.Text = AESAlgorithm.AESEncrypt(txt_weixinendportwcf.Text); } }
public Member GetCurrentUserInfo(string userName) { Member member = db.Members.Where(u => u.Name == userName).FirstOrDefault(); member.PassWord = AESAlgorithm.DecryptAES256(member.PassWord); return(member); }
private void ObjCardReader_CardNoGeted(object sender, SeatManage.ISystemTerminal.IPOS.CardEventArgs e) { StopRead(); if (!string.IsNullOrEmpty(e.CardNo)) { Dispatcher.Invoke(new Action(() => { viewModel.CardNo = e.CardNo; string AESCode = string.Format("schoolNo={0}&clientNo={1}&cardNo={2}", viewModel.ClientObject.ClientSetting.ClientNo.Substring(0, viewModel.ClientObject.ClientSetting.ClientNo.Length - 2), viewModel.ClientObject.ClientSetting.ClientNo, e.CardNo); Bitmap bitmap = QRCode.GetDimensionalCode(AESAlgorithm.AESEncrypt(AESCode, "SeatManage_WeiCharCode"), 6, 8); IntPtr hBitmap = bitmap.GetHbitmap(); BitmapSource bitmapImage = new BitmapImage(); try { bitmapImage = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } finally { DeleteObject(hBitmap); } imgCode.Fill = new ImageBrush(bitmapImage); })); } else { SeatManage.SeatManageComm.WriteLog.Write("读卡出现错误:" + e.ErrorInfo); } //System.Threading.Thread.Sleep(2000); StartRead(); }
private void txt_SeverWCFConnString_TextChanged(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txt_SeverWCFConnString.Text)) { txt_SeverWCFConnString_PW.Text = AESAlgorithm.AESEncrypt(txt_SeverWCFConnString.Text); } }
protected void Page_Load(object sender, EventArgs e) { try { string LoginID = Session["LoginID"].ToString(); string path = Server.MapPath("~/QRCodeImages/" + LoginID + ".jpg"); if (!File.Exists(path)) { string schoolNo = ConfigurationManager.AppSettings["SchoolNo"].ToString(); string AESCode = string.Format("schoolNo={0}&clientNo={1}&cardNo={2}", schoolNo, "001", LoginID); Bitmap bitmap = QRCode.GetDimensionalCode(AESAlgorithm.AESEncrypt(AESCode, "SeatManage_WeiCharCode"), 6, 8); // string filename = Guid.NewGuid().ToString(); path = Server.MapPath("~/QRCodeImages/" + LoginID + ".jpg"); bitmap.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg); bitmap.Dispose(); } Image1.ImageUrl = "/QRCodeImages/" + LoginID + ".jpg"; } catch (Exception ex) { throw new Exception("登录会话过期,请重新登录"); } }
public IHttpActionResult AddCabinet(Cabinet cabinet) { try { string valiate = ValiateCabinetModel(cabinet); if (!string.IsNullOrEmpty(valiate)) { return(Failure(valiate)); } if (Cabinet.GetByName(cabinet.Name) != null) { return(Failure("该名称已经被使用")); } if (Cabinet.GetByMac(cabinet.AndroidMac) != null) { return(Failure("该硬件编码已经被使用")); } if (!UserController.LoginDictionary.ContainsKey(GetCookie("token"))) { return(Logout()); } UserInfo userCookie = UserController.LoginDictionary[GetCookie("token")]; if (userCookie == null) { return(Logout()); } SystemLog.Add(new SystemLog { Action = "AddCabinet", LogContent = userCookie.Name + "-新增保险柜-" + cabinet.Name, CreateTime = DateTime.Now, UserID = userCookie.ID, RoleID = userCookie.RoleID, DepartmentID = userCookie.DepartmentID, ClientIP = GetIP(), UserName = userCookie.Name, RealName = userCookie.RealName }); cabinet.CreateTime = DateTime.Now; cabinet.IsOnline = false; if (!string.IsNullOrEmpty(cabinet.FirstContactPassword)) { cabinet.FirstContactPassword = AESAlgorithm.Encrypto(cabinet.FirstContactPassword); } if (!string.IsNullOrEmpty(cabinet.SecondContactPassword)) { cabinet.SecondContactPassword = AESAlgorithm.Encrypto(cabinet.SecondContactPassword); } Cabinet.Add(cabinet); return(Success(true)); } catch (Exception ex) { _logger.Error(ex); return(Failure("新增失败")); } }
public static bool ReadConfig(ref WebConfigSetting config) { doc = new XmlDocument(); string fileDircetoryPath = Path.GetDirectoryName(Application.StartupPath); string filePath = string.Format("{0}\\SeatManageWebV5\\Web.config", fileDircetoryPath); if (File.Exists(filePath)) { doc.Load(filePath); foreach (XmlNode node in doc.ChildNodes) { if (node.Name == "configuration") { foreach (XmlNode nodeA in node.ChildNodes) { if (nodeA.Name == "connectionStrings") { foreach (XmlNode nodeB in nodeA.ChildNodes) { if (nodeB.Attributes != null && nodeB.Attributes["name"].Value == "EndpointAddress") { config.ConnString = AESAlgorithm.AESDecrypt(nodeB.Attributes["connectionString"].Value); break; } } } else if (nodeA.Name == "appSettings") { foreach (XmlNode nodeB in nodeA.ChildNodes) { if (nodeB.Attributes != null && nodeB.Attributes["key"].Value == "ChangePassWord") { if (nodeB.Attributes["value"].Value == "open") { config.IsChangePW = true; } else { config.IsChangePW = false; } break; } } } } break; } } return(true); } else { return(false); } }
public static bool SaveConfig(WebConfigSetting config) { try { doc = new XmlDocument(); string fileDircetoryPath = Path.GetDirectoryName(Application.StartupPath); string filePath = string.Format("{0}\\SeatManageWebV2\\Web.config", fileDircetoryPath); doc.Load(filePath); foreach (XmlNode node in doc.ChildNodes) { if (node.Name == "configuration") { foreach (XmlNode nodeA in node.ChildNodes) { if (nodeA.Name == "connectionStrings") { foreach (XmlNode nodeB in nodeA.ChildNodes) { if (nodeB.Attributes != null && nodeB.Attributes["name"].Value == "EndpointAddress") { nodeB.Attributes["connectionString"].Value = AESAlgorithm.AESEncrypt(config.ConnString); break; } } } else if (nodeA.Name == "appSettings") { foreach (XmlNode nodeB in nodeA.ChildNodes) { if (nodeB.Attributes != null && nodeB.Attributes["key"].Value == "ChangePassWord") { if (config.IsChangePW) { nodeB.Attributes["value"].Value = "open"; } else { nodeB.Attributes["value"].Value = "true"; } break; } } } } break; } } doc.Save(filePath); return(true); } catch { return(false); } }
/// <summary> /// Obtient des données chiffrées. /// </summary> /// <param name="_data">Données à chiffrer</param> /// <returns>Byte[] : Donnée chiffrées.</returns> private static byte[] GetCipheredData(string _data) { string data = _data; byte[] passwordByte = Encoding.UTF8.GetBytes(VaultDatabase.UserPassword); byte[] dataByte = Encoding.UTF8.GetBytes(data); // Chiffre les données. byte[] cipheredData = AESAlgorithm.EncryptData(passwordByte, dataByte); return(cipheredData); }
// decript button private void Button_Click_2(object sender, RoutedEventArgs e) { Parameter par = new Parameter(); par.Key = keyTextBox.Text; par.InitialVector = InitialVectorTextBox.Text; par.Type = "d"; par.Mode = mode.SelectedIndex == 0 ? "ecb" : "cbc"; par.InputFilePath = filePathTextBox.Text; par.OutputFolderPath = outputFolderPathTextbox.Text; var enc = new AESAlgorithm(par); Task.Run(() => { enc.Execute(); }); }
private void button3_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txt_Connstring_PW.Text)) { MessageBox.Show("输入的密文不能为空!"); return; } try { this.txt_ConnString.Text = AESAlgorithm.AESDecrypt(this.txt_Connstring_PW.Text); } catch (Exception ex) { MessageBox.Show(string.Format("解密出错:{0}", ex.Message)); } }
public IHttpActionResult ChangePassword(string password) { if (string.IsNullOrEmpty(password)) { return(Failure("密码不为空")); } if (password?.Length <= 8) { return(Failure("密码必须是大于8位")); } if (!Regex.IsMatch(password[0].ToString(), @"^[A-Za-z]")) { return(Failure("密码必须字母开头")); } try { if (!UserController.LoginDictionary.ContainsKey(GetCookie("token"))) { return(Logout()); } UserInfo user = UserController.LoginDictionary[GetCookie("token")]; if (user == null) { return(Logout()); } var us = UserInfo.GetOne(user.ID); us.Password = AESAlgorithm.Encrypto(password); UserInfo.Update(us); SystemLog.Add(new SystemLog { Action = "Logout", LogContent = user.Name + "-更新密码", CreateTime = DateTime.Now, UserID = user.ID, RoleID = user.RoleID, DepartmentID = user.DepartmentID, ClientIP = GetIP(), UserName = user.Name, RealName = user.RealName }); return(Success()); }catch (Exception ex) { logger.Error(ex); return(Failure("修改失败")); } }
/// <summary> /// 通过获取服务器时间检查网络是否通畅,获取成功,返回true,否则返回false。 /// </summary> /// <returns></returns> private bool CheckNetWork() { ShowMessage = "正在连接远程服务……"; if (!CheckInternet.CheckLocal()) { ShowMessage = "连接网络失败,请检查网卡状态或网线是否接好!"; return(false); } if (ConfigurationManager.ConnectionStrings["EndpointAddress"] != null) { string endpointAddress = AESAlgorithm.AESDecrypt(ConfigurationManager.ConnectionStrings["EndpointAddress"].ConnectionString); //net.tcp://192.168.1.100:8201/ string straddress = endpointAddress.Replace("net.tcp://", ""); straddress = straddress.Substring(0, straddress.Length - 1); if (!CheckInternet.CheckPort(straddress.Split(':')[0], straddress.Split(':')[1])) { ShowMessage = "服务器连接失败,请检查服务器设置或网络配置!"; return(false); } string pingip = ConfigurationManager.AppSettings["PingIP"]; IPAddress ip; if (ConfigurationManager.AppSettings["PingServer"] != null && ConfigurationManager.AppSettings["PingServer"] == "1" && IPAddress.TryParse(pingip, out ip)) { CheckInternet.PingIp(pingip); } } else { ShowMessage = "获取服务器地址失败,请检查终端配置!"; return(false); } try { DateTime dt = ServiceDateTime.Now; } catch (Exception ex) { WriteLog.Write("连接数据传输服务失败:" + ex.Message); ShowMessage = "连接远程服务遇到错误,请检查服务器服务是否启动。"; return(false); } return(true); }
/// <summary> /// Déchiffre une liste de données. /// </summary> /// <param name="_cipheredData">Liste de données</param> /// <returns>List : Réussite -> Liste des données déchiffrées. Echec -> Valeur null.</returns> private static List <string> PlainData(List <byte[]> _cipheredData) { List <byte[]> cipheredData = _cipheredData; List <string> plainData = new List <string>(); byte[] passwordByte = Encoding.UTF8.GetBytes(VaultDatabase.UserPassword); // Déchiffre une liste de données. foreach (byte[] element in _cipheredData) { byte[] decryptedData = AESAlgorithm.DecryptData(passwordByte, element); plainData.Add(Encoding.UTF8.GetString(decryptedData).Replace("\0", string.Empty)); } return(plainData); }
/// <summary> /// "phoneNum": "17621826129" //"operatorType": "CT" /// </summary> /// <param name="params"></param> /// <returns></returns> public async Task <RespResult> GetMobile(Params @params) { try { var nonce = _guid.Create().ToString("N"); var dateTime = DateTimeOffset.UtcNow; var timeStamp = DateTimeOffset.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"); var appInfo = ObjectContainer.Resolve <IAppService>().GetAppCache(@params.AppKey); var dataContent = AESAlgorithm.Decrypt(@params.DataContent, appInfo.MessageSecret); @params.DataContent = AESAlgorithm.Encrypt(dataContent, appInfo.MsgSecret); var url = _config.GetValue("OneKeyLogin:Url", "https://feiyan.xinyan-ai.com/ocl/oclOrder/v1/getMobile"); var respResult = await Send(@params, nonce, timeStamp, appInfo, url); if (!respResult.success) { return(respResult); } var cmd = new SendCompleteCommand(); CreateCompleteCommand(@params, nonce, dateTime, appInfo, respResult, cmd); //计费 await Balance(appInfo); //redis await _redisHelper.StringIncrementAsync(RedisKeyName.CreateUserAmountKey(appInfo.UserId), -1); var entity = new ExpenseDetailEntity(); CreateEntity(cmd, entity); //交易明细写数据库 await ExpenseDetail(appInfo, entity); //await _mediator.Publish(cmd); return(respResult); } catch (Exception ex) { Logger.Error("GetMobile:", ex); Logger.Error($"json:{Serializer.Serialize(@params)}"); return(new RespResult { errorCode = TaskResultStatus.SystemError.ToString(), errorMsg = "系统错误", result = null, success = false }); } }
public ActionResult Index(string msg) { msg = AESAlgorithm.AESDecrypt(msg.Replace(" ", "+"));//解密参数 //string path = Server.MapPath("/App_Data/" + Guid.NewGuid().ToString() + ".txt");//将参数写入文件 //StreamWriter sw = new StreamWriter(path); //sw.Write(msg.Replace("&", "\r\n"));//TextBox2中的文本是可以编辑后的。 //sw.Close(); //sw.Dispose(); NameValueCollection param = UrlCommon.GetQueryString(msg);//获取参数 string SchoolNum = param["SchoolNum"].ToString(); string StudentNo = param["StudentNo"].ToString(); tb_User user = DbSession.Default.From <tb_User>().Where(tb_User._.SchoolNo == SchoolNum && tb_User._.StudentNo == StudentNo).ToFirst(); string MsgType = param["MsgType"].ToString(); switch (MsgType) { case "UserOperation": var UserOperation = new UserOperation() { first = new TemplateDataItem(user.Name + " 您好"), keyword1 = new TemplateDataItem(param["Room"].ToString()), keyword2 = new TemplateDataItem(param["SeatNo"].ToString()), keyword3 = new TemplateDataItem(param["AddTime"].ToString()), remark = new TemplateDataItem(param["Msg"].ToString()) }; TemplateApi.SendTemplateMessage(WeiXinApi.GetToken(), user.OpenId, "At7HOxsJ5CW81OV81hipLglDV21O46UVU9Gm_nToXGQ", "#7B68EE", GetAppSettings.SysURL + "/User/SeatState", UserOperation); break; default: var UserOperation1 = new UserOperation() { first = new TemplateDataItem(user.Name + " 您好"), keyword1 = new TemplateDataItem(param["Room"].ToString()), keyword2 = new TemplateDataItem(param["SeatNo"].ToString()), keyword3 = new TemplateDataItem(param["AddTime"].ToString()), remark = new TemplateDataItem(param["Msg"].ToString()) }; TemplateApi.SendTemplateMessage(WeiXinApi.GetToken(), user.OpenId, "At7HOxsJ5CW81OV81hipLglDV21O46UVU9Gm_nToXGQ", "#7B68EE", GetAppSettings.SysURL + "/User/SeatState", UserOperation1); break; } return(Content("0")); }
public static bool SaveLeaveClientConfig(LeaveClientBesicConfig config) { doc = new XmlDocument(); string fileDircetoryPath = AppDomain.CurrentDomain.BaseDirectory; string filePath = string.Format("{0}LeaveClient.exe.config", fileDircetoryPath); if (File.Exists(filePath)) { try { doc.Load(filePath); XmlNodeList nodes = doc.SelectNodes("//configuration/connectionStrings/add"); foreach (XmlNode node in nodes) { if (node.Attributes["name"].Value == "EndpointAddress") { node.Attributes["connectionString"].Value = AESAlgorithm.AESEncrypt(config.WCFConnString); break; } } nodes = doc.SelectNodes("//configuration/appSettings/add"); foreach (XmlNode node in nodes) { if (node.Attributes["key"].Value == "windowState") { node.Attributes["value"].Value = config.SetUpMode; } else if (node.Attributes["key"].Value == "LeaveState") { node.Attributes["value"].Value = config.LeaveMode; } } doc.Save(filePath); return(true); } catch { return(false); } } else { return(false); } }
public ScanCodeParamModel(string ciphertext) { string plainText = AESAlgorithm.UrlDecode(ciphertext); string[] strArr = plainText.Split('&'); for (int i = 0; i < strArr.Length; i++) { string[] itemArr = strArr[i].Split('='); switch (itemArr[0]) { case "readingRoomNum": readingRoomNum = itemArr[1]; break; case "seatNum": seatNum = itemArr[1]; break; } } }
private void btnRead_Click(object sender, RoutedEventArgs e) { if (txt_cardno.Text != "") { string AESCode = string.Format("schoolNo={0}&clientNo={1}&cardNo={2}", viewModel.ClientObject.ClientSetting.ClientNo.Substring(0, viewModel.ClientObject.ClientSetting.ClientNo.Length - 2), viewModel.ClientObject.ClientSetting.ClientNo, txt_cardno.Text); Bitmap bitmap = QRCode.GetDimensionalCode(AESAlgorithm.AESEncrypt(AESCode, "SeatManage_WeiCharCode"), 6, 8); IntPtr hBitmap = bitmap.GetHbitmap(); BitmapSource bitmapImage = new BitmapImage(); try { bitmapImage = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } finally { DeleteObject(hBitmap); } imgCode.Fill = new ImageBrush(bitmapImage); } }
public static void CreatSingleSeatQRCode(string readingRoomNo, string roomName, string seatNo) { try { string rootPath = System.Web.HttpContext.Current.Server.MapPath("~/SeatQRCode/"); if (Directory.Exists(rootPath)) { string subPath = System.Web.HttpContext.Current.Server.MapPath("~/SeatQRCode/" + readingRoomNo + "/"); if (!Directory.Exists(subPath)) { Directory.CreateDirectory(subPath); } string schoolNo = ConfigurationManager.AppSettings["SchoolNo"].ToString(); string AESCode = string.Format("schoolNo={0}&readingRoomNo={1}&seatNo={2}", schoolNo, readingRoomNo, seatNo); Bitmap bitmap = QRCode.GetDimensionalCode(AESAlgorithm.AESEncrypt(AESCode, "SeatManage_WeiCharCode"), 6, 8); //string tempPath = System.Web.HttpContext.Current.Server.MapPath("~/SeatQRCode/temp/GetDateString()/" + readingRoomNo + "/"); //Directory.CreateDirectory(tempPath); //bitmap.Save(tempPath + seatNo + ".jpg"); string imagePath = subPath + seatNo + ".jpg"; Image img = bitmap; Image bg = CreateImage("阅览室:" + roomName + " 座位编号:" + seatNo, true, 16); CombinImage(bg, img, imagePath, 0, -50); bitmap.Dispose(); bg.Dispose(); img.Dispose(); } else { WriteLog.Write("找不到" + rootPath + "文件夹,或者权限不足,请联系管理员"); } } catch (Exception ex) { WriteLog.Write(ex.ToString()); } }
private string GetConnSting() { string comm = ""; XmlDocument doc = new XmlDocument(); string fileDircetoryPath = AppDomain.CurrentDomain.BaseDirectory; string filePath = string.Format("{0}ServiceHostTimerHost.exe.config", fileDircetoryPath); if (File.Exists(filePath)) { doc.Load(filePath); XmlNodeList nodes = doc.SelectNodes("//configuration/connectionStrings/add"); foreach (XmlNode node in nodes) { if (node.Attributes["name"].Value == "EndpointAddress") { comm = AESAlgorithm.AESDecrypt(node.Attributes["connectionString"].Value); } } } return(comm); }
public IActionResult Update(dynamic member) { Member updateMember = new Member(); StringBuilder errorMessage = new StringBuilder(); errorMessage = updateMember.Validation(member.member); if (errorMessage.Length != 0) { ModelState.AddModelError("errorMessage", errorMessage.ToString()); return(BadRequest(ModelState)); } updateMember.BirthDay = member.member.BirthDay; updateMember.Email = member.member.Email; updateMember.MobilePhone = member.member.MobilePhone; updateMember.Name = member.member.Name; updateMember.PassWord = AESAlgorithm.EncryptAES256((string)member.member.Password); updateMember.Id = member.member.Id; worldTripRepository.Update(updateMember); return(Ok()); }
/// <summary> /// 二维码显示 /// </summary> void viewModel_CodeChange() { Dispatcher.Invoke(new Action(() => { string url = viewModel.ClientObject.CodeUrl + "?param="; string AESCode = string.Format("schoolNo={0}&clientNo={1}&codeTime={2}", viewModel.ClientObject.ClientSetting.ClientNo.Substring(0, viewModel.ClientObject.ClientSetting.ClientNo.Length - 2), viewModel.ClientObject.ClientSetting.ClientNo, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); Bitmap bitmap = QRCode.GetDimensionalCode(url + AESAlgorithm.AESEncrypt(AESCode, "SeatManage_WeiCharCode"), 6, 8); IntPtr hBitmap = bitmap.GetHbitmap(); BitmapSource bitmapImage = new BitmapImage(); try { bitmapImage = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } finally { DeleteObject(hBitmap); } imgCode.Fill = new ImageBrush(bitmapImage); })); }
/// <summary> /// 导出 /// </summary> /// <returns></returns> public bool Save() { if (string.IsNullOrEmpty(_SavePath.Trim())) { ErrorMessage = "保存地址不能为空!"; return(false); } if (string.IsNullOrEmpty(_Url.Trim())) { ErrorMessage = "保存地址不能为空!"; return(false); } try { string codeURL = _Url + "?param="; string AESCode = "seatNum={0}&readingRoomNum={1}"; string savePath = _SavePath + _RoomInfo.No + "_" + _RoomInfo.Name + "\\"; if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } foreach (KeyValuePair <string, SeatManage.ClassModel.Seat> seat in _RoomInfo.SeatList.Seats) { Bitmap dCode = QRCode.GetDimensionalCode(codeURL + AESAlgorithm.UrlEncode(string.Format(AESCode, seat.Value.SeatNo, _RoomInfo.No))); Graphics dNum = Graphics.FromImage(dCode); dNum.DrawRectangle(new Pen(Color.White, 60), 141, 141, 60, 60); StringFormat sf = new StringFormat(); sf.Alignment = StringAlignment.Center; dNum.DrawString(seat.Value.ShortSeatNo, new Font("黑体", 46, FontStyle.Bold), Brushes.Black, 172, 141, sf); dNum.Save(); dCode.Save(savePath + seat.Key + ".jpg", ImageFormat.Jpeg); } return(true); } catch (Exception ex) { ErrorMessage = "导出失败," + ex.Message; return(false); } }
private void CreatConfig(string commstring) { XmlDocument docx = new XmlDocument(); XmlDeclaration dec = docx.CreateXmlDeclaration("1.0", "utf-8", null); docx.AppendChild(dec); XmlElement root = docx.CreateElement("configuration");//创建根节点 XmlElement elementx = docx.CreateElement("connectionStrings"); XmlElement addelement = docx.CreateElement("add"); addelement.SetAttribute("name", "EndpointAddress"); addelement.SetAttribute("connectionString", AESAlgorithm.AESEncrypt(commstring)); elementx.AppendChild(addelement); root.AppendChild(elementx); XmlElement setelement = docx.CreateElement("startup"); XmlElement supelement = docx.CreateElement("supportedRuntime"); supelement.SetAttribute("version", "v4.0"); supelement.SetAttribute("sku", ".NETFramework,Version=v4.0"); setelement.AppendChild(supelement); root.AppendChild(setelement); docx.AppendChild(root); docx.Save(Process.GetCurrentProcess().MainModule.FileName + ".config"); }
public static bool SaveConfig(HostConfig hostconfig) { try { doc = new XmlDocument(); string fileDircetoryPath = AppDomain.CurrentDomain.BaseDirectory; string filePath = string.Format("{0}ServiceHostMonitorService.exe.config", fileDircetoryPath); doc.Load(filePath); XmlNodeList nodes = doc.SelectNodes("//configuration/connectionStrings/add"); foreach (XmlNode node in nodes) { if (node.Attributes["name"].Value == "ConnectionString") { node.Attributes["connectionString"].Value = "Data Source=" + hostconfig.DBIP + ";Initial Catalog=" + hostconfig.DBName + ";Persist Security Info=True" + ";User ID=" + hostconfig.DBUser + ";Password="******"name"].Value == "EndpointAddress") { node.Attributes["connectionString"].Value = AESAlgorithm.AESEncrypt(hostconfig.WCFString); } else if (node.Attributes["name"].Value == "AdvertServiceEndpointAddress") { node.Attributes["connectionString"].Value = AESAlgorithm.AESEncrypt(hostconfig.AdrWcfString); } else if (node.Attributes["name"].Value == "ip") { node.Attributes["connectionString"].Value = hostconfig.AdvSocketString; } } nodes = doc.SelectNodes("//configuration/system.serviceModel/services/service/host/baseAddresses/add"); foreach (XmlNode node in nodes) { string[] sp = node.Attributes["baseAddress"].Value.Split('/'); node.Attributes["baseAddress"].Value = hostconfig.WCFString + sp[sp.Length - 2] + "/"; } nodes = doc.SelectNodes("//configuration/appSettings/add"); foreach (XmlNode node in nodes) { if (node.Attributes["key"].Value == "ServiceAssembly" && (node.Attributes["value"].Value == "SeatService.MonitorService.MonitorService,SeatService.MonitorService" || node.Attributes["value"].Value == "SeatService.StatisticsService.StatisticsService,SeatService.StatisticsService" || node.Attributes["value"].Value == "SeatService.SyncService.SyncService,SeatService.SyncService" || node.Attributes["value"].Value == "SeatManage.WCFService.WcfHost,SeatManage.WCFService" || node.Attributes["value"].Value == "AMS.DataTransfer.DataTransferService,AMS.DataTransfer")) { XmlNode fnode = doc.SelectSingleNode("//configuration/appSettings"); fnode.RemoveChild(node); } } foreach (string server in hostconfig.HostServer) { //if (server == "WcfHost") //{ // XmlNode node = doc.SelectSingleNode("//configuration/appSettings"); // XmlElement element = doc.CreateElement("add"); // element.SetAttribute("key", "ServiceAssembly"); // element.SetAttribute("value", "SeatManage.WCFService.WcfHost,SeatManage.WCFService"); // node.AppendChild(element); //} //else if (server == "MonitorService") { XmlNode node = doc.SelectSingleNode("//configuration/appSettings"); XmlElement element1 = doc.CreateElement("add"); element1.SetAttribute("key", "ServiceAssembly"); element1.SetAttribute("value", "SeatService.MonitorService.MonitorService,SeatService.MonitorService"); node.AppendChild(element1); node = doc.SelectSingleNode("//configuration/appSettings"); XmlElement element2 = doc.CreateElement("add"); element2.SetAttribute("key", "ServiceAssembly"); element2.SetAttribute("value", "SeatService.StatisticsService.StatisticsService,SeatService.StatisticsService"); node.AppendChild(element2); node = doc.SelectSingleNode("//configuration/appSettings"); XmlElement element3 = doc.CreateElement("add"); element3.SetAttribute("key", "ServiceAssembly"); element3.SetAttribute("value", "SeatService.SyncService.SyncService,SeatService.SyncService"); node.AppendChild(element3); } else if (server == "DataTransferService") { XmlNode node = doc.SelectSingleNode("//configuration/appSettings"); XmlElement element = doc.CreateElement("add"); element.SetAttribute("key", "ServiceAssembly"); element.SetAttribute("value", "AMS.DataTransfer.DataTransferService,AMS.DataTransfer"); node.AppendChild(element); } } //XmlNode nodeso = doc.SelectSingleNode("//configuration/appSettings"); //XmlElement elementso = doc.CreateElement("add"); //elementso.SetAttribute("key", "ServiceAssembly"); //elementso.SetAttribute("value", "SMS.SeatTcpServer.SeatBespeakTcpProxy,SMS.SeatTcpServer"); //nodeso.AppendChild(elementso); foreach (XmlNode node in nodes) { if (node.Attributes["key"] == null) { continue; } if (node.Attributes["key"].Value == "SaveFilePath") { node.Attributes["value"].Value = hostconfig.MediaFilePath; } else if (node.Attributes["key"].Value == "LogUploadTime") { node.Attributes["value"].Value = hostconfig.UploadTime; } else if (node.Attributes["key"].Value == "Interval") { node.Attributes["value"].Value = hostconfig.LoopTime; } else if (node.Attributes["key"].Value == "SchoolNo") { node.Attributes["value"].Value = hostconfig.SchoolNo; } } doc.Save(filePath); XmlDocument docx = new XmlDocument(); XmlDeclaration dec = docx.CreateXmlDeclaration("1.0", "utf-8", null); docx.AppendChild(dec); XmlElement root = docx.CreateElement("configuration");//创建根节点 XmlElement elementx = docx.CreateElement("connectionStrings"); XmlElement addelement = docx.CreateElement("add"); addelement.SetAttribute("name", "EndpointAddress"); addelement.SetAttribute("connectionString", AESAlgorithm.AESEncrypt(hostconfig.WCFString)); elementx.AppendChild(addelement); root.AppendChild(elementx); XmlElement setelement = docx.CreateElement("startup"); XmlElement supelement = docx.CreateElement("supportedRuntime"); supelement.SetAttribute("version", "v4.0"); supelement.SetAttribute("sku", ".NETFramework,Version=v4.0"); setelement.AppendChild(supelement); root.AppendChild(setelement); docx.AppendChild(root); docx.Save(Process.GetCurrentProcess().MainModule.FileName + ".config"); return(true); } catch { return(false); } }