/// <summary> /// Handler=Save /// </summary> /// <returns></returns> public async Task <IActionResult> OnPostSaveAsync([FromBody] MessagesExtendDto messagesExtendDto) { SenparcTrace.Log($"messagesExtendDto----{messagesExtendDto.ToJson()}"); if (messagesExtendDto == null) { return(Ok(false)); } MessagesDto messagesDto = new MessagesDto { Id = messagesExtendDto.Id, Title = messagesExtendDto.Title, Content = messagesExtendDto.Content, Method = messagesExtendDto.Method, Type = messagesExtendDto.Type, Status = messagesExtendDto.Status }; var strategy = _messagesService.BaseData.BaseDB.BaseDataContext.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async() => { await _messagesService.BeginTransactionAsync(async() => { var messages = await _messagesService.CreateOrUpdateAsync(messagesDto); await messageDetailService.InsertMessageUserAsync(messages.Id, messagesExtendDto.RelationUser); }); }); return(Ok(true)); }
public void LogTest() { //直接调用此方法不会记录到log文件中,而是输出到系统日志中 var keyword = Guid.NewGuid().ToString();//随机字符串 SenparcTrace.Log($"添加Log:{keyword}"); //Assert.IsTrue(UnitTestHelper.CheckKeywordsExist(_logFilePath,keyword)); }
/// <summary> /// 删除消息 /// </summary> /// <param name="userId"></param> /// <param name="messageDetailId"></param> /// <returns></returns> public async Task <bool> ApiDeleteMessage(string userId, string messageDetailId) { var seh = new SenparcExpressionHelper <MessageDetail>(); SenparcTrace.Log($"userId-----{userId},messageDetailId----${messageDetailId}"); seh.ValueCompare.AndAlso(!string.IsNullOrEmpty(userId), _ => _.UserId.Equals(userId)); seh.ValueCompare.AndAlso(!string.IsNullOrEmpty(messageDetailId), _ => _.Id.Equals(messageDetailId)); var where = seh.BuildWhereExpression(); await base.DeleteAllAsync(where); return(true); }
/// <summary> /// 获取消息 /// </summary> /// <param name="userId"></param> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <returns></returns> public async Task <IEnumerable <MessageDetailDto> > ApiGetList(string userId, int pageIndex, int pageSize) { List <MessageDetailDto> selectListItems = null; var seh = new SenparcExpressionHelper <MessageDetail>(); SenparcTrace.Log($"userId-----{userId}"); seh.ValueCompare.AndAlso(!string.IsNullOrEmpty(userId), _ => _.UserId.Equals(userId)); var where = seh.BuildWhereExpression(); List <MessageDetail> messageDetails = (await base.GetObjectListAsync(pageIndex, pageSize, where, "AddTime Desc")).ToList(); selectListItems = base.Mapper.Map <List <MessageDetailDto> >(messageDetails); return(selectListItems); }
/// <summary> /// 清除未读消息 /// </summary> /// <param name="userId"></param> /// <returns></returns> public async Task <bool> ApiClearNotReadMessage(string userId) { var seh = new SenparcExpressionHelper <MessageDetail>(); SenparcTrace.Log($"userId-----{userId}"); seh.ValueCompare.AndAlso(!string.IsNullOrEmpty(userId), _ => _.UserId.Equals(userId)); seh.ValueCompare.AndAlso(true, _ => _.IsRead.Equals(2)); var where = seh.BuildWhereExpression(); List <MessageDetail> lstMsgDetails = (await base.GetFullListAsync(where, "AddTime Desc")).ToList(); for (int i = 0; i < lstMsgDetails.Count; i++) { lstMsgDetails[i].IsRead = 1; } await base.SaveObjectListAsync(lstMsgDetails); return(true); }
public override async Task <ICacheLock> LockAsync() { var key = _mamcachedStrategy.GetFinalKey(_resourceName); var lockResult = await RetryLockAsync(key, _retryCount, _retryDelay, async() => { try { var ttl = base.GetTotalTtl(_retryCount, _retryDelay); #if NET45 var storeResult = await Task.Factory.StartNew(() => _mamcachedStrategy.Cache.Store(StoreMode.Add, key, new object(), TimeSpan.FromMilliseconds(ttl))).ConfigureAwait(false); if (storeResult) #else if (await _mamcachedStrategy.Cache.StoreAsync(StoreMode.Add, key, new object(), TimeSpan.FromMilliseconds(ttl))) #endif { base.LockSuccessful = true; return(true);//取得锁 } else { base.LockSuccessful = false; return(false);//已被别人锁住,没有取得锁 } //if (_mamcachedStrategy._cache.Get(key) != null) //{ // return false;//已被别人锁住,没有取得锁 //} //else //{ // _mamcachedStrategy._cache.Store(StoreMode.set, key, new object(), new TimeSpan(0, 0, 10));//创建锁 // return true;//取得锁 //} } catch (Exception ex) { SenparcTrace.Log("Memcached同步锁发生异常:" + ex.Message); return(false); } } ).ConfigureAwait(false); return(lockResult); }
/// <summary> /// 立即等待并抢夺锁 /// </summary> /// <returns></returns> public override ICacheLock Lock() { int currentRetry = 0; int maxRetryDelay = (int)_retryDelay.TotalMilliseconds; while (currentRetry++ < _retryCount) { #region 尝试获得锁 var getLock = false; try { lock (lookPoolLock) { if (LockPool.ContainsKey(_resourceName)) { getLock = false;//已被别人锁住,没有取得锁 } else { LockPool.Add(_resourceName, new object()); //创建锁 getLock = true; //取得锁 } } } catch (Exception ex) { SenparcTrace.Log("本地同步锁发生异常:" + ex.Message); getLock = false; } #endregion if (getLock) { LockSuccessful = true; return(this);//取得锁 } Thread.Sleep(_rnd.Next(maxRetryDelay)); } LockSuccessful = false; return(this); }
public override bool Lock(string resourceName, int retryCount, TimeSpan retryDelay) { int currentRetry = 0; int maxRetryDelay = (int)retryDelay.TotalMilliseconds; while (currentRetry++ < retryCount) { #region 尝试获得锁 var getLock = false; try { lock (lookPoolLock) { if (LockPool.ContainsKey(resourceName)) { getLock = false;//已被别人锁住,没有取得锁 } else { LockPool.Add(resourceName, new object()); //创建锁 getLock = true; //取得锁 } } } catch (Exception ex) { SenparcTrace.Log("本地同步锁发生异常:" + ex.Message); getLock = false; } #endregion if (getLock) { return(true);//取得锁 } Thread.Sleep(_rnd.Next(maxRetryDelay)); } return(false); }
public void LogTest() { //直接调用此方法不会记录到log文件中,而是输出到系统日志中 var keyword = Guid.NewGuid().ToString();//随机字符串 SenparcTrace.Log($"添加Log:{keyword}"); var dt1 = SystemTime.Now; while (SystemTime.DiffTotalMS(dt1) < 600) { //等待队列执行 } SenparcMessageQueue.OperateQueue(); Console.WriteLine(SenparcMessageQueue.MessageQueueDictionary.Count); Console.WriteLine(ThreadUtility.AsynThreadCollection.Count); //Assert.IsTrue(UnitTestHelper.CheckKeywordsExist(_logFilePath,keyword)); }
public override ICacheLock Lock() { var key = _mamcachedStrategy.GetFinalKey(_resourceName); var lockResult = RetryLock(key, _retryCount, _retryDelay, () => { try { var ttl = base.GetTotalTtl(_retryCount, _retryDelay); if (_mamcachedStrategy.Cache.Store(StoreMode.Add, key, new object(), TimeSpan.FromMilliseconds(ttl))) { base.LockSuccessful = true; return(true);//取得锁 } else { base.LockSuccessful = false; return(false);//已被别人锁住,没有取得锁 } //if (_mamcachedStrategy._cache.Get(key) != null) //{ // return false;//已被别人锁住,没有取得锁 //} //else //{ // _mamcachedStrategy._cache.Store(StoreMode.set, key, new object(), new TimeSpan(0, 0, 10));//创建锁 // return true;//取得锁 //} } catch (Exception ex) { SenparcTrace.Log("Memcached同步锁发生异常:" + ex.Message); return(false); } } ); return(lockResult); }
public override bool Lock(string resourceName, int retryCount, TimeSpan retryDelay) { var key = _mamcachedStrategy.GetFinalKey(resourceName); var successfull = RetryLock(key, retryCount /*暂时不限制*/, retryDelay, () => { try { if (_mamcachedStrategy.Cache.Store(StoreMode.Add, key, new object(), new TimeSpan(0, 0, 10))) { return(true);//取得锁 } else { return(false);//已被别人锁住,没有取得锁 } //if (_mamcachedStrategy._cache.Get(key) != null) //{ // return false;//已被别人锁住,没有取得锁 //} //else //{ // _mamcachedStrategy._cache.Store(StoreMode.set, key, new object(), new TimeSpan(0, 0, 10));//创建锁 // return true;//取得锁 //} } catch (Exception ex) { SenparcTrace.Log("Memcached同步锁发生异常:" + ex.Message); return(false); } } ); return(successfull); }
/// <summary> /// 记录系统日志 /// </summary> /// <param name="messageFormat"></param> /// <param name="param"></param> public static void Log(string messageFormat, params object[] param) { SenparcTrace.Log(messageFormat.FormatWith(param)); }
public ActionResult Post(PostModel postModel) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, _senparcWeixinSetting.Token)) { return(Content("参数错误!")); } #region 打包 PostModel 信息 postModel.Token = _senparcWeixinSetting.Token; //根据自己后台的设置保持一致 postModel.EncodingAESKey = ""; //根据自己后台的设置保持一致 postModel.AppId = _senparcWeixinSetting.WeixinAppId; //根据自己后台的设置保持一致 #endregion //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制 var maxRecordCount = 10; //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new ScfMessageHandler(Request.GetRequestMemoryStream(), postModel, maxRecordCount); #region 设置消息去重 /* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。 * 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的RequestMessage*/ messageHandler.OmitRepeatedMessage = true;//默认已经开启,此处仅作为演示,也可以设置为false在本次请求中停用此功能 #endregion try { #region 记录 Request 日志 var logPath = ServerUtility.ContentRootMapPath(string.Format("~/logs/mp/{0}/", DateTime.Now.ToString("yyyy-MM-dd"))); if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); } //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。 messageHandler.RequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_{1}_{2}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName, messageHandler.RequestMessage.MsgType))); if (messageHandler.UsingEncryptMessage) { messageHandler.EcryptRequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_Ecrypt_{1}_{2}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName, messageHandler.RequestMessage.MsgType))); } #endregion //执行微信处理过程 messageHandler.Execute(); #region 记录 Response 日志 //测试时可开启,帮助跟踪数据 //if (messageHandler.ResponseDocument == null) //{ // throw new Exception(messageHandler.RequestDocument.ToString()); //} if (messageHandler.ResponseDocument != null) { messageHandler.ResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_{1}_{2}.txt", _getRandomFileName(), messageHandler.ResponseMessage.ToUserName, messageHandler.ResponseMessage.MsgType))); } if (messageHandler.UsingEncryptMessage && messageHandler.FinalResponseDocument != null) { //记录加密后的响应信息 messageHandler.FinalResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_Final_{1}_{2}.txt", _getRandomFileName(), messageHandler.ResponseMessage.ToUserName, messageHandler.ResponseMessage.MsgType))); } #endregion //return Content(messageHandler.ResponseDocument.ToString());//v0.7- //return new WeixinResult(messageHandler);//v0.8+ return(new FixWeixinBugWeixinResult(messageHandler));//为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可 } catch (Exception ex) { #region 异常处理 SenparcTrace.Log($"MessageHandler错误:{ex.Message}"); using (TextWriter tw = new StreamWriter(ServerUtility.ContentRootMapPath("~/App_Data/Error_" + _getRandomFileName() + ".txt"))) { tw.WriteLine("ExecptionMessage:" + ex.Message); tw.WriteLine(ex.Source); tw.WriteLine(ex.StackTrace); //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message); if (messageHandler.ResponseDocument != null) { tw.WriteLine(messageHandler.ResponseDocument.ToString()); } if (ex.InnerException != null) { tw.WriteLine("========= InnerException ========="); tw.WriteLine(ex.InnerException.Message); tw.WriteLine(ex.InnerException.Source); tw.WriteLine(ex.InnerException.StackTrace); } tw.Flush(); tw.Close(); } return(Content("")); #endregion } }
public virtual ActionResult Post(NeuCharAppPostModel postModel, string neucharAppId) { postModel.Token = Token; postModel.AppId = neucharAppId;// $"NeuCharApp:AppId:{neucharAppId}"; if (postModel.Signature != CheckSignatureWeChat.GetSignature(postModel)) { return(Content("参数错误!")); } //postModel.EncodingAESKey = EncodingAESKey;//根据自己后台的设置保持一致 //postModel.AppId = AppId;//根据自己后台的设置保持一致 NeuCharAppMessageHandler messageHandler = null; try { #if NET45 messageHandler = new NeuCharAppMessageHandler(Request.InputStream, postModel); #else messageHandler = new NeuCharAppMessageHandler(Request.GetRequestMemoryStream(), postModel); #endif messageHandler.SaveRequestMessageLog(); //记录 Request 日志(可选) messageHandler.Execute(); //执行微信处理过程(关键) messageHandler.SaveResponseMessageLog(); //记录 Response 日志(可选) var responseText = messageHandler.TextResponseMessage ?? ""; return(Content(responseText)); } catch (Exception ex) { #region 异常处理 SenparcTrace.Log($"NeuCharAppMessageHandler错误:{ex.Message}"); var logPath = Path.Combine(messageHandler.GetLogPath(), $"Error_{_getRandomFileName()}.txt"); using (TextWriter tw = new StreamWriter(logPath)) { tw.WriteLine("ExecptionMessage:" + ex.Message); tw.WriteLine(ex.Source); tw.WriteLine(ex.StackTrace); //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message); if (messageHandler.ResponseDocument != null) { tw.WriteLine(messageHandler.ResponseDocument.ToString()); } if (ex.InnerException != null) { tw.WriteLine("========= InnerException ========="); tw.WriteLine(ex.InnerException.Message); tw.WriteLine(ex.InnerException.Source); tw.WriteLine(ex.InnerException.StackTrace); } tw.Flush(); tw.Close(); } return(Content("")); #endregion } }