public async Task <string> LoginCustomer(Customer obj) { string token = ""; Md5Helper md = new Md5Helper(); obj.UserPwd = md.ToMd5(obj.UserPwd); Customer model = _loginBll.ShowCustomer(obj); if (model != null) { JWTHelper jwt = new JWTHelper(); Dictionary <string, object> pairs = new Dictionary <string, object>(); pairs.Add("UserId", model.UserId); pairs.Add("UserName", model.UserName); pairs.Add("UserPwd", model.UserPwd); token = jwt.GetToken(pairs, 30000); return(await Task.Run(() => { return token; })); } else { return(null); } }
public ActionResult GetFansStaticInfo(int User_ID) { try { if (User_ID <= 0) { return(FailNoLogin()); } string cacheKey = Md5Helper.Hash("FansStaticInfo" + User_ID); FansStaticInfoEntity fansStaticInfo = redisCache.Read <FansStaticInfoEntity>(cacheKey, 7); if (fansStaticInfo == null) { fansStaticInfo = dm_userIBLL.GetFansStaticInfo(User_ID); redisCache.Write <FansStaticInfoEntity>(cacheKey, fansStaticInfo, DateTime.Now.AddMinutes(5), 7); } return(Success("获取成功!", fansStaticInfo)); } catch (Exception ex) { return(FailException(ex)); } }
public ActionResult StudentLogin(string name, string pwd) { try { var Pwd = Md5Helper.MD5Encoding(pwd, 123); var result = student_BLL.StudentLogin(name, Pwd); if (result != null) { FormsAuthentication.SetAuthCookie(name, true); GetOnline(name); CookiesHelper.SetCookie("SId", HttpUtility.UrlEncode(JsonConvert.SerializeObject(result)), DateTime.Now.AddDays(7)); return(Redirect("~/Exam/Index")); } return(Redirect("/Exam/Login")); } catch (Exception ex) { ErrorLog.WriteLog(ex); return(null); } }
public List <Order> getOrderFromSUP(ref int getOrderTime) { getOrderTime = time; List <Order> orderSet = new List <Order>(); try { string sign = Md5Helper.GetMD5String_utf8(merchantID + key); string postData = string.Format("MerchantID={0}&Sign={1}&ProductNo={2}&Count={3}&Status={4}", merchantID, sign, "", count, "0"); System.Net.CookieContainer cookie = new System.Net.CookieContainer(); WriteLog.Write("方法:getOrderFromSUP 获取订单参数:" + postData, LogPathFile.Other); string result = PostAndGet.HttpGetString(getOrderurl, postData, ref cookie); WriteLog.Write("方法:getOrderFromSUP 获取订单信息:" + result, LogPathFile.Other); string State = Regex.Match(result, @"<State>(.*?)</State>").Groups[0].Value; string State_Info = Regex.Match(result, @"<State_Info>(.*?)</State_Info>").Groups[0].Value; if (State.Contains("0") && State_Info.Contains("成功")) { assignmentOrder(orderSet, result); } } catch (Exception ex) { WriteLog.Write("方法:getOrderFromSUP异常,信息:" + ex.Message + ex.StackTrace, LogPathFile.Exception); } return(orderSet); }
public ActionResult ConvertLinkByJD(int user_id, string skuid, string couponlink) { try { string appid = CheckAPPID(); string cacheKey = Md5Helper.Hash(user_id.ToString() + skuid + "2"); JDLinkInfo jDLinkInfo = redisCache.Read <JDLinkInfo>(cacheKey, 7L); dm_basesettingEntity dm_BasesettingEntity = dM_BaseSettingIBLL.GetEntityByCache(appid); if (jDLinkInfo == null) { JDApi jDApi = new JDApi(dm_BasesettingEntity.jd_appkey, dm_BasesettingEntity.jd_appsecret, dm_BasesettingEntity.jd_sessionkey); dm_userEntity dm_UserEntity = dm_userIBLL.GetEntityByCache(user_id); if (dm_UserEntity.jd_pid.IsEmpty()) { #region 自动分配京东pid dm_UserEntity = dM_PidIBLL.AutoAssignJDPID(dm_UserEntity); #endregion } couponlink = HttpUtility.UrlEncode(couponlink); jDLinkInfo = jDApi.ConvertUrl(skuid, dm_UserEntity.jd_site.ToString(), dm_UserEntity.jd_pid, couponlink); if (jDLinkInfo != null) { redisCache.Write(cacheKey, jDLinkInfo, DateTime.Now.AddHours(2.0), 7L); } } return(Success("获取成功!", jDLinkInfo)); } catch (Exception ex) { return(FailException(ex)); } }
/// <summary> /// 淘宝高佣转链 /// </summary> /// <param name="userid">用户id</param> /// <param name="originid">商品id</param> /// <param name="couponid">优惠券id</param> /// <returns></returns> public ActionResult ConvertLinkByTB(int userid, string originid, string couponid) { try { string appid = CheckAPPID(); string cacheKey = Md5Helper.Hash(userid.ToString() + originid + couponid); PrivilegeLinkResult ConvertLinkResult = redisCache.Read <PrivilegeLinkResult>(cacheKey, 7L); if (ConvertLinkResult == null) { dm_userEntity dm_UserEntity = dm_userIBLL.GetEntityByCache(userid); if (dm_UserEntity.tb_relationid.IsEmpty()) { return(NoRelationID("渠道未备案!")); } dm_basesettingEntity dm_BasesettingEntity = dM_BaseSettingIBLL.GetEntityByCache(appid); DTK_ApiManage dTK_ApiManage = new DTK_ApiManage(dm_BasesettingEntity.dtk_appkey, dm_BasesettingEntity.dtk_appsecret); DTK_Privilege_LinkRequest dTK_Privilege_LinkRequest = new DTK_Privilege_LinkRequest(); dTK_Privilege_LinkRequest.version = "v1.1.1"; dTK_Privilege_LinkRequest.goodsId = originid; dTK_Privilege_LinkRequest.pid = dm_BasesettingEntity.tb_relation_pid; dTK_Privilege_LinkRequest.channelId = dm_UserEntity.tb_relationid.ToString(); dTK_Privilege_LinkRequest.couponId = couponid; DTK_Privilege_LinkResponse dTK_Privilege_LinkResponse = dTK_ApiManage.GetPrivilegeLink(dTK_Privilege_LinkRequest); if (dTK_Privilege_LinkResponse.code != 0) { return(Fail(dTK_Privilege_LinkResponse.msg)); } ConvertLinkResult = dTK_Privilege_LinkResponse.data; redisCache.Write(cacheKey, ConvertLinkResult, DateTime.Now.AddHours(1.0), 7L); } return(Success("转链成功!", ConvertLinkResult)); } catch (Exception ex) { return(FailException(ex)); } }
public ActionResult GetTBTopicList(int userid, int type = 0, string pageId = "1", int pageSize = 20) { try { string appid = CheckAPPID(); string cacheKey = Md5Helper.Hash("TBTopicList" + type + pageId + pageSize); List <TB_TopicItem> tB_TopicItems = redisCache.Read <List <TB_TopicItem> >(cacheKey, 7L); if (tB_TopicItems == null) { dm_userEntity dm_UserEntity = dm_userIBLL.GetEntityByCache(userid); if (dm_UserEntity.tb_relationid.IsEmpty()) { return(NoRelationID("渠道未备案!")); } dm_basesettingEntity dm_BasesettingEntity = dM_BaseSettingIBLL.GetEntityByCache(appid); DTK_ApiManage dTK_ApiManage = new DTK_ApiManage(dm_BasesettingEntity.dtk_appkey, dm_BasesettingEntity.dtk_appsecret); DTK_TB_Topic_ListRequest dTK_TB_Topic_ListRequest = new DTK_TB_Topic_ListRequest(); dTK_TB_Topic_ListRequest.version = "v1.2.0"; dTK_TB_Topic_ListRequest.type = type; dTK_TB_Topic_ListRequest.pageId = pageId; dTK_TB_Topic_ListRequest.pageSize = pageSize; dTK_TB_Topic_ListRequest.channelID = long.Parse(dm_UserEntity.tb_relationid.ToString()); DTK_TB_Topic_ListResponse dTK_TB_Topic_ListResponse = dTK_ApiManage.GettTBTopicList(dTK_TB_Topic_ListRequest); if (dTK_TB_Topic_ListResponse.code != 0) { return(Fail(dTK_TB_Topic_ListResponse.msg)); } tB_TopicItems = dTK_TB_Topic_ListResponse.data; redisCache.Write(cacheKey, tB_TopicItems, DateTime.Now.AddDays(1.0), 7L); } return(SuccessList("获取成功!", tB_TopicItems)); } catch (Exception ex) { return(FailException(ex)); } }
public void Append_WithOverCapacity_IncreaseMemoryMappedFileCapacity() { //Arrange var datas = new[] { Guid.NewGuid().ToByteArray(), Guid.NewGuid().ToByteArray(), Guid.NewGuid().ToByteArray() }; var capacity = datas.Sum(d => d.Length) - 16; //Action using (var storage = new FileStorage(_storageFilePath, capacity)) { foreach (var data in datas) { storage.Append(new MemoryStream(data)); } } //Assert using (var storage = new FileStorage(_storageFilePath, capacity)) { var offset = DefaultSizes.CursorHolderSize; foreach (var data in datas) { using (var resultStream = storage.Get(new IndexData { Offset = offset, Md5Hash = null, Size = data.Length })) { byte[] hash1, hash2; Md5Helper.ComputeHashes(data, resultStream, out hash1, out hash2); Assert.IsTrue(hash1.SequenceEqual(hash2)); } offset += SizeOfGuid; } } }
public ActionResult GetSonChildDetail(int User_ID, int PageNo = 1, int PageSize = 20) { try { if (User_ID <= 0) { return(FailNoLogin()); } dm_userEntity dm_UserEntity = dm_userIBLL.GetEntityByCache(User_ID); if (dm_UserEntity.IsEmpty()) { return(Fail("用户信息异常!")); } else { string cacheKey = Md5Helper.Hash("SonChildDetail" + User_ID + PageNo + PageSize); DataTable dataTable = redisCache.Read(cacheKey, 7); if (dataTable == null) { dataTable = dm_UserRelationIBLL.GetMySonChildDetail(User_ID, PageNo, PageSize); if (dataTable.Rows.Count >= PageSize) { redisCache.Write(cacheKey, dataTable, DateTime.Now.AddMinutes(5), 7); } else { redisCache.Write(cacheKey, dataTable, DateTime.Now.AddSeconds(30), 7); } } return(SuccessList("获取成功!", dataTable)); } } catch (Exception ex) { return(FailException(ex)); } }
private bool UserLogin() { if (string.IsNullOrEmpty(user.Text) || string.IsNullOrEmpty(pass.Password)) { return(false); } AccountModel acount = new AccountModel(); AccountDao ado = new AccountDao(DbHelper.GetConnection()); acount.UName = user.Text; ICollection <AccountModel> datas = new List <AccountModel>(); datas = ado.SelectData(0, 1, acount); if (datas.Count <= 0) { MessageBox.Show("账号密码不正确,请确定!"); return(false); } acount.UPass = Md5Helper.MD5Encrypt32(pass.Password); int result = acount.UPass.CompareTo(datas.ElementAt(0).UPass); if (result != 0) { MessageBox.Show("密码错误!"); return(false); } GlobeInfo.gUserInfo.UId = datas.ElementAt(0).UId; GlobeInfo.gUserInfo.UserName = datas.ElementAt(0).UserName; GlobeInfo.gUserInfo.UName = datas.ElementAt(0).UName; GlobeInfo.gUserInfo.ULevel = datas.ElementAt(0).ULevel; GlobeInfo.gUserInfo.UState = datas.ElementAt(0).UState; return(true); }
public void CompleteCheckout_GatewayOrderDetailsReturnNullObject_Test() { var requestid = 1; var randomKey = Guid.NewGuid().ToString("N"); var key = Md5Helper.GetMd5Hash(requestid + randomKey + randomKey + requestid); Mock <CheckoutRequest> requestMock = new Mock <CheckoutRequest>(); requestMock.Object.errorurl = "https://www.store1.com/error.asp?error=100"; requestMock.Object.username = "******"; requestMock.Object.password = "******"; _completeOrderService.Setup(x => x.GetCurrentRequest(It.IsAny <int>())).Returns(requestMock.Object); _completeOrderService.Setup(x => x.UpdateRequest(It.IsAny <int>(), It.IsAny <Status>())).Returns(true); _completeOrderService.Setup(x => x.CompleteOrder(It.IsAny <int>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CheckoutRequest>(), It.IsAny <GatewayOrderDetails>())).Returns(true); Mock <GatewayToken> gatewayAuthToken = new Mock <GatewayToken>(); gatewayAuthToken.Object.token = Guid.NewGuid().ToString("N"); gatewayAuthToken.Object.expiration_date = DateTime.Now.AddDays(1).ToString(); _gatewayAuthenticationService.Setup(m => m.GetGatewayToken(It.IsAny <string>(), It.IsAny <string>())).Returns(gatewayAuthToken.Object); _gatewayChekoutService.Setup(x => x.GetGatewayOrderDetails(It.IsAny <string>(), It.IsAny <GatewayToken>())).Returns(() => null); var actResult = _checkoutController.CompleteCheckout(requestid, randomKey, key); Assert.IsNotNull(actResult); Assert.IsInstanceOf <RedirectResult>(actResult); var httpResult = actResult as RedirectResult; Assert.IsNotNull(httpResult); Assert.AreEqual("https://www.store1.com/error.asp?error=100", httpResult.Url); }
private void InsertListTest(int toatl = 10) { Console.WriteLine("\r\n开始测试批量插入数据...\r\n"); List <UserEntity> list = new List <UserEntity>(); for (int i = 1; i < toatl; i++) { string key = Guid.NewGuid().ToString().Replace("-", ""); string md5 = Md5Helper.Md5("123456"); string realPassword = Md5Helper.Md5(DESEncryptHelper.Encrypt(md5, key)); UserEntity user = new UserEntity { Id = Guid.NewGuid().ToString().Replace("-", ""), Account = "dashixiong" + i, NickName = "大师兄" + i, Birthday = DateTime.Now.AddDays(-1000), Secretkey = key, Password = realPassword }; user.Create(); list.Add(user); } Console.WriteLine("\r\n初始化数据完成...\r\n"); string time = Stopwatch(() => { _userBll.AddUser(list); }); Console.WriteLine("执行结束,耗时:" + time); }
/// <summary> /// 5.4 订单提交接口(数娱产品) /// </summary> /// <param name="order"></param> /// <returns></returns> string setPostDate2(Order order) { string mrch_no = merchantID; // 商户代号 商户代号 是 20 string request_time = DateTime.Now.ToString("yyyyMMddHHmmss"); // 请求时间 格式:yyyyMMddHHmmss 是 14 string client_order_no = order.OrderInsideID; // 商户订单号 商户订单号,商户自己生成,保证唯一。最大长度不超过32位 是 32 string account = order.TargetAccount; // 业务号码 充值号码 是 20 string product_code = ""; // 产品编码 产品编码 是 10 string buy_num = (order.BuyAmount * 100).ToString(); // 购买数量 正常商品,传递数量1;任意充商品,传递具体购买数量; 是 3 string other_param = ""; // 其他参数 其他参数,可传空值 是 128 string notify_url = "http://116.62.44.48/NotifyFromZhiXin.aspx"; // 回调地址 回调地址 若为空值,则平台不发起异步通知 是 128 string sign = ""; // 签名数据 数字签名 是 32 //if (other_param.Contains(":")) //{ // other_param = "115.239.168.199"; //} if (order.AreaName.Contains("安卓")) { product_code = "I18901-1"; } else if (order.AreaName.Contains("苹果") || order.AreaName.Contains("IOS")) { product_code = "I18902-1"; } string md5str = "account" + account + "buy_num" + buy_num + "client_order_no" + client_order_no + "mrch_no" + mrch_no + "notify_url" + notify_url + "other_param" + other_param + "product_code" + product_code + "request_time" + request_time + key; sign = Md5Helper.MD5Encrypt(md5str); string json = "{\"mrch_no\":\"" + mrch_no + "\",\"request_time\":\"" + request_time + "\",\"client_order_no\":\"" + client_order_no + "\",\"account\":\"" + account + "\",\"product_code\":\"" + product_code + "\",\"buy_num\":\"" + buy_num + "\",\"other_param\":\"" + other_param + "\",\"notify_url\":\"" + notify_url + "\",\"sign\":\"" + sign + "\"}"; return(json); }
public HttpResponseMessage CheckLogin(string system, string account, string password) { LogEntity logEntity = new LogEntity { CategoryId = (int)CategoryType.Login, OperateTypeId = ((int)OperationType.Login).ToString(), OperateType = OperationType.Login.GetEnumDescription(), OperateAccount = account, OperateUserId = account, Module = system }; try { //验证账户 UserEntity userEntity = new UserBLL().CheckLogin(account, password); //生成票据 string ticket = Md5Helper.MD5(CommonHelper.GetGuid(), 32); //写入票据 CacheFactory.Cache().WriteCache(userEntity, ticket, DateTimeHelper.Now.AddHours(8)); //写入日志 logEntity.ExecuteResult = 1; logEntity.ExecuteResultJson = "登录成功"; logEntity.WriteLog(); return(Success("登录成功", ticket)); } catch (Exception ex) { logEntity.ExecuteResult = -1; logEntity.ExecuteResultJson = ex.Message; logEntity.WriteLog(); return(Error(ex.Message)); } }
public ActionResult GetPartnersChildDetail(int user_id, int PageNo = 1, int PageSize = 20) { try { dm_userEntity dm_UserEntity = dm_userIBLL.GetEntityByCache(user_id); if (dm_UserEntity.IsEmpty()) { return(Fail("用户信息异常!")); } if (dm_UserEntity.partnersstatus == 0) { return(Fail("当前非合伙人,无法看团队粉丝")); } else { string cacheKey = Md5Helper.Hash("PartnersChildDetail" + user_id + PageNo + PageSize); DataTable dataTable = redisCache.Read(cacheKey, 7); if (dataTable == null) { dataTable = dm_UserRelationIBLL.GetPartnersChildDetail(dm_UserEntity.partners, PageNo, PageSize); if (dataTable.Rows.Count >= PageSize) { redisCache.Write(cacheKey, dataTable, DateTime.Now.AddHours(3), 7); } else { redisCache.Write(cacheKey, dataTable, DateTime.Now.AddMinutes(5), 7); } } return(SuccessList("获取成功!", dataTable)); } } catch (Exception ex) { return(FailException(ex)); } }
public ActionResult GetMyReviceTask(int User_ID, int PageNo = 1, int PageSize = 20, int TaskStatus = -1) { try { if (User_ID <= 0) { return(FailNoLogin()); } string cacheKey = "MyReviceTask" + Md5Helper.Hash(User_ID + "" + PageNo + "" + PageSize + "" + TaskStatus); DataTable dataTable = redisCache.Read(cacheKey, 7); if (dataTable == null) { dataTable = dm_Task_ReviceIBLL.GetMyReviceTask(User_ID, TaskStatus, new Pagination { page = PageNo, rows = PageSize, sidx = "revice_time", sord = "desc" }); /* 接受任务需要实时显示 此处先把缓存去掉 2020-08-04 * int datarow = dataTable.Rows.Count; * if (datarow > 0) * { * if (datarow < PageSize) * { * redisCache.Write(cacheKey, dataTable, DateTime.Now.AddMinutes(5), 7); * } * else * { * redisCache.Write(cacheKey, dataTable, DateTime.Now.AddMinutes(10), 7); * } * }*/ } return(SuccessList("获取成功!", dataTable)); } catch (Exception ex) { return(FailException(ex)); } }
public async Task <ActionResult> ChangePassword(string oldPwd, string newPwd, string confirmNewPwd) { //获取当前登陆的id,cookie的id需要解密 string userCookieId = ""; string message; if (Request.Cookies["userId"] != null) { if (!JwtHelper.GetJwtDecode(Request.Cookies["userId"].Value, out userCookieId, out message)) { return(Json(new { status = "fail", result = message, code = 401 }, JsonRequestBehavior.AllowGet)); } } string userId = Session["userId"] == null ? userCookieId : Session["userId"].ToString();//优先获取session的id if (userId == null || userId.Trim() == "") { return(Json(new { status = "fail", result = "获取用户信息失败,请检查登陆状态" }, JsonRequestBehavior.AllowGet)); } if (oldPwd == null || newPwd == null || confirmNewPwd == null || oldPwd.Trim() == "" || newPwd.Trim() == "" || confirmNewPwd.Trim() == "") { return(Json(new { status = "fail", result = "提交的数据不可为空" }, JsonRequestBehavior.AllowGet)); } if (newPwd != confirmNewPwd)//防止js验证不生效(被禁用),这里在补充验证 { return(Json(new { status = "fail", result = "新密码与确认新密码不一致,请重试!" }, JsonRequestBehavior.AllowGet)); } IUserManager userManager = new UserManager(); oldPwd = Md5Helper.Md5(oldPwd); confirmNewPwd = Md5Helper.Md5(confirmNewPwd); if (!await userManager.ChangePassword(Guid.Parse(userId), oldPwd, confirmNewPwd)) { return(Json(new { status = "fail", result = "旧密码错误,请重试!" }, JsonRequestBehavior.AllowGet)); } return(Json(new { status = "ok", result = "修改成功!" }, JsonRequestBehavior.AllowGet)); }
public ActionResult SubmitResetPassword(string password, string oldPassword, string verifyCode) { verifyCode = Md5Helper.Encrypt(verifyCode.ToLower(), 16); if (Session["session_verifycode"].IsEmpty() || verifyCode != Session["session_verifycode"].ToString()) { return(Fail("验证码错误,请重新输入")); } UserInfo userInfo = LoginUserInfo.Get(); if (userInfo.isSystem) { return(Fail("当前账户不能修改密码")); } bool res = userIBLL.RevisePassword(password, oldPassword); if (!res) { return(Fail("原密码错误,请重新输入")); } Session.Abandon(); Session.Clear(); OperatorHelper.Instance.EmptyCurrent(); return(Success("密码修改成功,请牢记新密码。\r 将会自动安全退出。")); }
/// <summary> /// 解密数据 /// </summary> /// <param name="text"></param> /// <param name="sKey"></param> /// <returns></returns> public static string Decrypt(string text, string sKey) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); int len = text.Length / 2; byte[] inputByteArray = new byte[len]; for (int x = 0; x < len; x++) { int i = Convert.ToInt32(text.Substring(x * 2, 2), 16); inputByteArray[x] = (byte)i; } des.Key = Encoding.ASCII.GetBytes(Md5Helper.Md5(sKey).Substring(0, 8)); des.IV = Encoding.ASCII.GetBytes(Md5Helper.Md5(sKey).Substring(0, 8)); System.IO.MemoryStream ms = new System.IO.MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return(Encoding.Default.GetString(ms.ToArray())); }
/// <summary> /// HttpClient实现Post请求 /// </summary> public PageResult PostService <T>(T request, string url) { var data = Base64Helper.ObjectToBase64Encode(request); var context = _userKey + data; var sign = Md5Helper.Md5Encrypt32(context); var securityType = "MD5"; var str = JsonHelper.ObjectToJson(new PageResult { Data = data, Sign = sign, SecurityType = securityType }); url += "?data=" + data + "&sign=" + sign + "&securityType=" + securityType; var responseContent = Post(str, url); if (!string.IsNullOrEmpty(responseContent)) { var result = JsonHelper.JsonToObject <PageResult>(responseContent); return(result); } return(new PageResult()); }
public ActionResult SubmitResetPassword(string password, string oldPassword, string verifyCode) { var user = UserService.GetEntity <UserEntryDto>(SessionManager.Instance.Current().UserId); verifyCode = Md5Helper.MD5(verifyCode.ToLower(), 16); if (Session["session_verifycode"].IsEmpty() || verifyCode != Session["session_verifycode"].ToString()) { return(Error("验证码错误,请重新输入")); } oldPassword = Md5Helper.MD5(DESEncrypt.Encrypt(oldPassword, user.Secretkey).ToLower(), 32).ToLower(); if (oldPassword != user.Password) { return(Error("原密码错误,请重新输入")); } if (SessionManager.Instance.Current().IsSystem) { return(Error("当前账户不能修改密码")); } UserService.RevisePassword(user.Id, password.ToLower()); Session.Abandon(); Session.Clear(); return(Success("密码修改成功,请牢记新密码。\r 将会自动安全退出。")); }
private static string GetKeyFromContent( Dictionary <SectionId, List <Tuple <long, string, DateTime> > > tupleBySections) { var allKeys = new StringBuilder(); foreach (SectionId key in tupleBySections.Keys) { List <Tuple <long, string, DateTime> > tuple = tupleBySections[key]; if (allKeys.Length > 0) { allKeys.Append("_"); } List <long> ids = tuple.Select(e => e.Item1).ToList(); string keyPart = key + "-" + ids.Min() + "-" + ids.Max() + "-" + ids.Count() + "-" + tuple.Select(e => e.Item3).Max().Ticks; allKeys.Append(keyPart); } var md5Helper = new Md5Helper(); string result = md5Helper.GetHash(allKeys.ToString()); return(result); }
/// <summary> /// 增加或更新通知 /// </summary> /// <param name="notice"></param> /// <returns></returns> public ResultModel AddOrUpdateNotice(Notice notice) { ResultModel result = new ResultModel(); try { if (string.IsNullOrWhiteSpace(notice.NoticeId)) { notice.NoticeId = Md5Helper.getMd5Hash(notice.TaskId);//如果没有ID自动生成 } _cicadaDbContext.Notices.AddOrUpdate(notice); _cicadaDbContext.SaveChanges(); result.Code = 200; result.Msg = notice.NoticeId; } catch (Exception ex) { result.Code = 500; result.Msg = ex.Message; } return(result); }
public static bool CompareSpecial(object obj1, object obj2) { BinaryFormatter binaryFormatter = new BinaryFormatter(); //把对象放到流中 MemoryStream inputStream1; MemoryStream inputStream2; using (inputStream1 = new MemoryStream()) { binaryFormatter.Serialize(inputStream1, obj1); } using (inputStream2 = new MemoryStream()) { binaryFormatter.Serialize(inputStream2, obj2); } //把流转换成字节数组,得到md5字符串 string md5_1 = Md5Helper.MD5Encrypt(inputStream1.ToArray()); string md5_2 = Md5Helper.MD5Encrypt(inputStream2.ToArray()); return(md5_1 == md5_2); }
/// <summary> /// Загрузить новую версию шаблона /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void loadBtn_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = ".docx | *.docx"; if (ofd.ShowDialog() != DialogResult.OK) { return; } ofd.Multiselect = false; if (File.Exists(ofd.FileName) && templateTypesCB.SelectedItem is TemplateType) { byte[] fileBytes; try { fileBytes = File.ReadAllBytes(ofd.FileName); } catch (Exception ex) { MessageBox.Show($"Ошибка загрузки файла: {ex.Message}"); return; } TemplateFile file = new TemplateFile { FileData = fileBytes, HashMd5 = Md5Helper.GetMd5Hash(fileBytes), TemplateType = (templateTypesCB.SelectedItem as TemplateType), WhoUpload = GlobalSettings.LoginUser }; _templateRepository.Add(file); RefreshTemplateData(); } }
public LoginState Login(string name, string pwd, out int type) { type = -1; ManagerInfo mi = miDal.GetByName(name); if (mi == null) { return(LoginState.NameError); } else { //Username and password is correct? if (mi.MPwd.Equals(Md5Helper.EncryptString(pwd))) { type = mi.MType; return(LoginState.Ok); } else { return(LoginState.PwdError); } } }
public IActionResult Registration([FromBody] SysUserInfo model) { RespondResult result = new RespondResult(); model.Id = Guid.NewGuid().ToString(); model.CreateTime = DateTime.Now; model.UpdateTime = null; model.Password = Md5Helper.Md5(model.Password); int resultcount = systemUserService.AddUser(model); //用户注册失败 if (resultcount == 0) { result.is_success = false; result.msg = "注册失败"; result.result = null; } var tokenStr = AuthConfiguer.GetJWT(model, _jwtSettings); result.is_success = true; result.msg = "注册成功"; result.result = tokenStr; return(Ok(result)); }
protected void btnProses_Click(object sender, EventArgs e) { if (cbSetuju.Checked) { Anggota dataAnggotaBaru = new Anggota(); dataAnggotaBaru.IdAnggota = tbIdentitas.Text; dataAnggotaBaru.NamaAnggota = tbNama.Text; dataAnggotaBaru.AlamatAnggota = tbAlamat.Text; dataAnggotaBaru.NomorKontakAnggota = tbKontak.Text; dataAnggotaBaru.PasswordAnggota = Md5Helper.KonversiKeMd5(tbSandi.Text); dataAnggotaBaru.SurelAnggota = tbSurel.Text; PengendaliDataAnggota.TambahAnggotaBaru(dataAnggotaBaru); tbIdentitas.Text = ""; tbNama.Text = ""; tbAlamat.Text = ""; tbKontak.Text = ""; tbSandi.Text = ""; tbKonfSandi.Text = ""; tbSurel.Text = ""; Response.Write("<script>alert(\"Pendaftaran Berhasil!\");</script>"); Response.AddHeader("REFRESH", "1;URL=Default.aspx"); //Response.Redirect("~/Default.aspx"); } }
public void TestSaltMd5() { var salt = "!*@&(!&$!"; var md5 = Md5Helper.Md5String("abcdefg", salt); Console.WriteLine(md5); Assert.IsNotNullOrEmpty(md5); Assert.AreEqual(32, md5.Length); var md5File = Md5Helper.Md5File("nunit.framework.dll", salt); Console.WriteLine(md5File); Assert.IsNotNullOrEmpty(md5File); Assert.AreEqual(32, md5File.Length); var md5Nosalt = Md5Helper.Md5String("abcdefg"); Assert.AreNotEqual(md5, md5Nosalt); var md5FileNoSalt = Md5Helper.Md5File("nunit.framework.dll"); Assert.AreNotEqual(md5File, md5FileNoSalt); }
public void Supervise(HttpContext context, string jsonDate) { #region ** 参数验证 ** JsonData jd_data = JsonMapper.ToObject(jsonDate); if (jd_data == null || jd_data.Count < 1) { throw new PMSException("参数不能为空"); } string HotelCode = CommonUse.ParamVal(jd_data, "HotelCode", "酒店编号", true, true); string sign = CommonUse.ParamVal(jd_data, "Sign", "签名", true, true); string sign_new = Md5Helper.MD5(HotelCode, 32); if (sign.ToLower() != sign_new.ToLower()) { throw new PMSException("签名验证失败!"); } string[] keyValue = DESEncrypt.Decrypt(HotelCode).Split(','); if (keyValue.Length < 2) { throw new PMSException("错误的酒店编号,请核对后重试"); } int pageIndex = CommonHelper.GetInt(CommonUse.ParamVal(jd_data, "PageIndex", "当前页", true, true)); int DataType = CommonHelper.GetInt(CommonUse.ParamVal(jd_data, "DataType", "数据类型", false, false)); #endregion string adminHotelId = keyValue[0]; string hotelId = keyValue[1]; string userId = keyValue[2]; if (DataType > 1)//数据类型不为0表示为数据查询数据库读取 { adminHotelId = "1010142"; hotelId = "0"; } if (!DataFactory.CheckSqlIsOpen(adminHotelId, CommonHelper.GetInt(hotelId)))//数据库是否能连接 { throw new PMSException("数据库连接失败,请验证网络是否正常"); } int PageSize = 20; int doCount = 0; int more = 0; JsonData jd = new JsonData(); //返回JsonData JsonData jdData = new JsonData(); //DataTable值 #region ** 获取数据值 ** try { StringBuilder sql = new StringBuilder(); sql.Append(@" SELECT rq , jglb , xh , jglr FROM XX_JGXJCX "); IList <SqlParam> lParam = new List <SqlParam>(); if (DataType > 1) { sql.Append(" WHERE jdid = @jdid "); lParam.Add(new SqlParam("@jdid", DataType)); } sql.Append(" ORDER BY rq DESC "); DataTable dt = DataFactory.SqlDataBase(adminHotelId, hotelId).GetDataTableBySQL(sql); if (dt != null && dt.Rows.Count > 0) { doCount = dt.Rows.Count; int pi_ps = (pageIndex - 1) * PageSize; int pi_dc = pi_ps + PageSize; if (pi_dc > doCount) { pi_dc = doCount; } more = doCount - pi_dc;//更多剩余数 more = more > 0 ? more : 0; if (pi_dc > doCount) { pi_dc = doCount; } for (int i = pi_ps; i < pi_dc; i++) { JsonData jdList = new JsonData(); // jdList["Time"] = dt.Rows[i]["rq"].ToString(); //时间 jdList["Type"] = dt.Rows[i]["jglb"].ToString();; //类型 jdList["Operator"] = "00" + dt.Rows[i]["xh"].ToString(); //操作人 jdList["Content"] = dt.Rows[i]["jglr"].ToString(); //操作内容 jdData.Add(jdList); } } } catch { } #endregion jd["code"] = 1; jd["count"] = doCount; //数量 jd["more"] = more; //更多剩余数 jd["data"] = jdData.IsArray ? jdData : false; string json = jd.ToJson(); // 统一输出 PMSResponse.WirterString(json); }