public void GetItem(string key) { int retries = MAX_RETRIES; while (retries > 0) { try { if (Database.Instance.Multiplexer.IsConnected) { var redisValue = Database.Instance.StringGet(key); var message = redisValue.IsNullOrEmpty ? NoValueFound : Success; logger.Info($"Geting item {key} : {Success} (from {MAX_RETRIES - retries + 1})"); break; } else { retries--; if (retries == 0) { logger.Info($"Get failed...{MAX_RETRIES} retries"); } } } catch (Exception e) { retries--; if (retries == 0) { logger.Error(e, $"{e.Message}, {e.StackTrace}"); } } } }
public void GetItem(string key) { try { var redisValue = Database.Instance.StringGet(key); var message = redisValue.IsNullOrEmpty ? NoValueFound : Success; logger.Info($"Geting item {key} : {Success}"); } catch (Exception e) { logger.Error(e, e.Message); } }
private void SessionUpdated(object session, Boolean toKillProcesses) { Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, (DispatcherOperationCallback) delegate(object o) { try { AppLogger.Debug("SessionUpdated()", "Enter"); if (toKillProcesses) { ToKillProcesses(); } SessionHandler.UpdateBySessionMessage(session); if (IsActiveSession) { State = STATES.Session; } else if (State != STATES.NotSession) { State = STATES.FinishingSession; } AppLogger.Debug("SessionUpdated()", "Finish"); } catch (Exception ex) { AppLogger.Error("SessionUpdated()", "Error: " + ex.Message + ". State is " + State); } return(null); }, null); }
public IHttpActionResult Delete(int id) { try { var emp = _unitOfWork.Employees.GetById(id); if (emp == null) { return(NotFound()); } _unitOfWork.Employees.Remove(emp); if (_unitOfWork.Complete() > 0) { var result = _unitOfWork.Employees.GetAll(); //Mapping var mappedResult = _mapper.Map <IEnumerable <ModelEmployee> >(result); AppLogger.Info("Delete employee successful. From: Employees using Web API"); return(Ok(mappedResult)); } else { AppLogger.Error("Delete employee error. From: Employees using Web API"); return(InternalServerError()); } } catch (Exception ex) { AppLogger.Error("Delete employee error. From: Employees using Web API"); return(InternalServerError(ex)); } }
public IHttpActionResult Put(int id, ModelEmployee model) { try { var emp = _unitOfWork.Employees.GetById(id); if (emp == null) { return(NotFound()); } //(Source,Destination) _mapper.Map(model, emp); if (_unitOfWork.Complete() > 0) { AppLogger.Info("Update employee successful. From: Employees using Web API"); return(Ok(_mapper.Map <ModelEmployee>(emp))); } else { AppLogger.Error("Update employee error. From: Employees using Web API"); return(InternalServerError()); } } catch (Exception ex) { AppLogger.Error("Update employee error. From: Employees using Web API"); return(InternalServerError(ex)); } }
public ResultRecommend GetRecommendInfo(QueryGetRecommend query) { var result = new ResultRecommend { Exception = new MyException(), RecommendList = new List <RecommendUser>() }; try { var realSsid = new EncryDecry().Md5Decrypt(query.Ssid); var arr = HelpTool.GetSession(realSsid); if (arr.Length < 3) { result.Exception.Exmsg = "not found"; result.Exception.Success = true; return(result); } var user = arr.GetValue(2).ToString(); var recommendList = _userRecommend.GetAllRecommend(user); foreach (var rec in recommendList) { result.RecommendList.Add(new RecommendUser { User = rec.User }); } result.Exception.Success = true; } catch (Exception ex) { result.Exception.Success = false; AppLogger.Error($"{ex.Message} {ex.StackTrace}"); } return(result); }
public ResultModifyAddress IsReg(QueryUserExists query) { var result = new ResultModifyAddress { Exception = new MyException() }; try { var realSsid = new EncryDecry().Md5Decrypt(query.Ssid); var arr = GetSession(realSsid); if (arr.Length < 3) { result.Exception.Exmsg = "not found"; result.Exception.Success = true; return(result); } var findIt = _user.SearchUser(arr.GetValue(2).ToString()); if (findIt != null) { result.Address = _userInfo.GeTbUserInfos($"{findIt.Id}")?[0].Address; } result.Exception.Success = true; return(result); } catch (Exception ex) { AppLogger.Error($"{ex.Message} {ex.StackTrace}"); result.Exception.Success = false; } return(result); }
public ResultRmUserCartgo AddBuyCnt(QueryAddBuyCnt query) { var result = new ResultRmUserCartgo { Exception = new MyException() }; try { if (!ValidateUserSsid(query.Ssid)) { result.Exception.Success = false; return(result); } var realSsid = new EncryDecry().Md5Decrypt(query.Ssid); var sessionArr = GetSession(realSsid); if (sessionArr.Length == 3) { realSsid = sessionArr.GetValue(2).ToString(); } _userCartgo.AddBuyCnt(realSsid, query.Code, query.Cnt); result.Exception.Success = true; }catch (Exception ex) { result.Exception.Success = false; AppLogger.Error($"{ex.Message} {ex.StackTrace}"); } return(result); }
private void SaveSettings() { try { var brokerAccount = DataManager.Broker.ActiveAccounts.FirstOrDefault(p => p.IsDefault); if (brokerAccount != null) { Settings.DefaultBrokerAccount = brokerAccount.UserName; Settings.DefaultBrokerName = brokerAccount.BrokerName; } else { Settings.DefaultBrokerAccount = string.Empty; Settings.DefaultBrokerName = string.Empty; } Settings.AutoLoginBrokerAccounts = true; var data = ProtoSerializer.Serialize(Settings); File.WriteAllBytes(PathManager.SettingsFileName, data); } catch (Exception ex) { AppLogger.Error(ex, "Failed save settings"); } }
public IHttpActionResult Get([FromUri] SuggestionQuery query) { if (query == null) { throw new NullQueryStringException(); } query.Validate(); Coordinates sourceCoordinates = query.Coordinates(); IEnumerable <GeoDataEntry> results = null; try { if (sourceCoordinates == null) { results = DataProvider.Search(query?.Q, query.MaxResults); } else { results = DataProvider.SearchNear(query?.Q, new BoundingBox(sourceCoordinates, Defaults.defaultRadiusKm), query.MaxResults); } } catch (Exception ex) { AppLogger.Error("error querying hospitals", ex); throw new DataProviderException(ex); } return(Ok(ResultsMapper.Map(results, query, new LinkBuilder(this)))); }
public void Process(ArraySegment <byte> data) { var count = data.Count; var buf = data.Array; const int leastLen = 1; if (buf == null || count < leastLen) { AppLogger.Error($"corruted SetFilter result,received len: {count}"); return; } count = (count - 1) / 2; var lst = new List <int>(count); var startIdx = data.Offset + 1; for (var i = 0; i < count; i++) { var index0 = i * 2 + startIdx; var flag0 = buf[index0]; var flag1 = buf[index0 + 1]; var code = BitDataConverter.ImpedanceCode(flag0, flag1); lst.Add(code); } CommitMultiImpedance(lst); AppLogger.Debug($"TestMultiImpedanceHandler: Data Processed"); }
public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { var exception = error as GeneralInternalException; if (exception == null) { // log exception AppLogger.Error(error); var serverInternalFault = new FaultException("Internal Server Error!"); MessageFault messageFault = serverInternalFault.CreateMessageFault(); fault = Message.CreateMessage(version, messageFault, null); } else { var generalInternalFault = new FaultException <GeneralInternalFault>(new GeneralInternalFault() { FaultCode = exception.FaultCode }); MessageFault messageFault = generalInternalFault.CreateMessageFault(); fault = Message.CreateMessage(version, messageFault, null); } }
private void Send() { try { if (!SendHeart()) { return; } var sendObj = new SaleRegClient { RegClient = true, ClientId = _index }; var str = JsonConvert.SerializeObject(sendObj); var lenStr = str.Length.ToString(); lenStr = string.Join("", lenStr.Reverse()); for (var i = 0; i <= 6 - lenStr.Length; i++) { lenStr += "0"; } lenStr = string.Join("", lenStr.Reverse()); _socket.Send(Encoding.UTF8.GetBytes(lenStr)); //Thread.Sleep(2000); _socket.Send(Encoding.UTF8.GetBytes(str)); } catch (Exception ex) { AppLogger.Error($"{ex.Message} {ex.StackTrace}"); } }
public void ReceiveMessageWcs() { int?curDataLength = null; var sb = new StringBuilder(); while (true) { try { var myClientSocket = (Socket)_socket; HandleRecev(myClientSocket, ref sb, ref curDataLength); if (sb.Length > 0) { continue; } var result = new byte[BufferSize]; try { var dataCount = myClientSocket.Receive(result); } catch (Exception ex) { AppLogger.Error($"ReceiveMessageWcs {ex.Message}", new Exception(ex.Message)); continue; } var receiveStr = Encoding.UTF8.GetString(result); receiveStr = receiveStr.Replace("\0", string.Empty); sb.Append(receiveStr); } catch (Exception ex) { AppLogger.Error($"{ex.Message} {ex.StackTrace}", ex); } } }
private bool SendHeart() { var heart = new HeartMessage { Heart = true }; var str = JsonConvert.SerializeObject(heart); try { var lenStr = str.Length.ToString(); lenStr = string.Join("", lenStr.Reverse()); for (var i = 0; i <= 6 - lenStr.Length; i++) { lenStr += "0"; } lenStr = string.Join("", lenStr.Reverse()); _socket.Send(Encoding.UTF8.GetBytes(lenStr)); //Thread.Sleep(2000); _socket.Send(Encoding.UTF8.GetBytes(str)); } catch (Exception ex) { AppLogger.Error($"{ex.Message} {ex.StackTrace}"); return(false); } return(true); }
private static void SubscribeForegroundApp() { Thread.Sleep(ForgroundAppSubscribeInterval.Add(ForgroundAppSubscribeInterval)); while (true) { try { RefreshFFXIVIsActive(); } catch (ThreadAbortException) { return; } catch (Exception ex) { AppLogger.Error("Happened exception from Foreground App subscriber.", ex); Thread.Sleep(ForgroundAppSubscribeInterval.Add(ForgroundAppSubscribeInterval)); } finally { Thread.Sleep(ForgroundAppSubscribeInterval); } } }
public IHttpActionResult SubmitLog([FromBody] LoggingMessage logging) { switch (logging.LogType) { case 1: Devicelog.Info(null, logging.PrepareLogMessage()); break; case 2: Devicelog.Warn(null, logging.PrepareLogMessage()); break; case 3: Devicelog.Debug(null, logging.PrepareLogMessage()); break; case 4: Devicelog.Error(logging.ExceptionObj, logging.PrepareLogMessage()); break; default: Devicelog.Info(null, logging.PrepareLogMessage()); break; } return(Ok(new { Status = Constants.WebApiStatusOk, data = "Success" })); }
public void GetCurrentUserCount() { while (true) { Thread.Sleep(10000); var total = 0; try { var server = Connection.GetServer(_redisCfg, 6379); var db = Connection.GetDatabase(); var keys = server.Keys(); foreach (var key in keys.AsQueryable()) { var value = db.StringGet(key).ToString(); var arr = value.Split('_'); if (!arr[0].Equals("1999")) { continue; } total++; } } catch (Exception ex) { AppLogger.Error($"{ex.Message} {ex.StackTrace}"); } UpdateUi.UpdateLoginUser(total); } }
public void Update(string id, Country entity) { try { Country obj = FindById(id); if (obj != null) { if (entity.CountryCode == obj.CountryCode) { entity.ModificationDate = DateTimeOffset.Now; _context.Entry(entity).State = EntityState.Modified; _context.SaveChanges(); } else { throw new NonEqualObjectException(); } } else { throw new NonObjectFoundException(); } } catch (Exception ex) { AppLogger.Error(ex.Message, ex); throw; } }
public void DelSession() { var oldTime = DateTime.Now; while (true) { Thread.Sleep(1000); try { if (DateTime.Now.Hour != 0 || DateTime.Now.Minute != 10) { continue; } var server = Connection.GetServer(_redisCfg, 6379); var db = Connection.GetDatabase(); var keys = server.Keys(); foreach (var key in keys.AsQueryable()) { var value = db.StringGet(key).ToString(); var arr = value.Split('_'); if (!arr[0].Equals("1999")) { continue; } db.KeyDelete(key); } } catch (Exception ex) { AppLogger.Error($"{ex.Message} {ex.StackTrace}"); } } }
public ResultAddPostInfo AddPostInfo(QueryAddPostInfo query) { var result = new ResultAddPostInfo { Exception = new MyException() }; try { var realSsid = new EncryDecry().Md5Decrypt(query.Ssid); var arr = GetSession(realSsid); if (arr.Length < 3 || ValidatePostInfo(query) != 0) { result.Exception.Exmsg = "not found 标题或内容超过规定"; result.Exception.Success = true; return(result); } var postInfo = new Tb_PostInfo { CreateTime = DateTime.Now, UserId = arr.GetValue(2).ToString(), Title = query.Title, PostText = query.PostText, IsShow = 1, ViewCount = 1 }; _postInfo.AddPostInfo(postInfo); result.Exception.Success = true; } catch (Exception ex) { result.Exception.Success = false; AppLogger.Error($"{ex.Message} {ex.StackTrace}"); } return(result); }
public ActionResult Create(ModelEmployeeMvc emp) { try { if (ModelState.IsValid) { using (db) { DynamicParameters param = new DynamicParameters(); param.Add("@firstName", emp.FirstName); param.Add("@lastName", emp.LastName); param.Add("@contactNumber", emp.ContactNumber); param.Add("@email", emp.Email); param.Add("@address", emp.Address); db.Open(); db.Execute("AddNewEmployee", param, commandType: CommandType.StoredProcedure); AppLogger.Info("Insert new employee. From: Employees using Dapper"); db.Close(); return(RedirectToAction("Index")); } } return(View()); } catch (Exception ex) { AppLogger.Error("Insert new employee error. From: Employees using Dapper"); return(View(ex)); } }
private void UpdateCartOrderInfo(string uName, string realSessionId) { using (var scope = new TransactionScope()) { try { var cartgo = _cartGodal.GetCartGoByUser(realSessionId); if (cartgo != null) { cartgo.UserId = uName; _cartGodal.UpdateCartGoInfo(cartgo, realSessionId); var order = _cartGodal.GetOrderByUser(realSessionId); if (order != null) { order.UserId = uName; _cartGodal.UpdateOrder(order); } } scope.Complete(); } catch (Exception ex) { AppLogger.Error($"{ex.Message} {ex.StackTrace}"); } } }
//发送一次心跳 private bool SendHeart(int clientId) { Socket yes = null; lock (_lock) { if (_salesClientDict.ContainsKey(clientId)) { yes = _salesClientDict[clientId]; } } if (yes == null) { return(false); } else { var client = yes; var heart = new { Heart = true }; var str = JsonConvert.SerializeObject(heart); try { var head = CreateSendJson(str); client.Send(Encoding.UTF8.GetBytes(head)); client.Send(Encoding.UTF8.GetBytes(str)); } catch (Exception ex) { AppLogger.Error($"{ex.Message} {ex.StackTrace}"); return(false); } return(true); } }
public async Task <IActionResult> Index(ForgotPasswordVM model) { logger.Trace("POST Index()"); if (!ModelState.IsValid) { logger.Trace("Model is not valid - displaying form"); return(View(model)); } var user = await userManager.FindByEmailAsync(model.Email); if (user == null) { logger.Trace("User {0} does not exist - pretending to send notification", model.Email); ViewBag.CallbackUrl = "/"; return(View("CheckEmail")); } if (!(await userManager.IsEmailConfirmedAsync(user))) { logger.Trace("User {0} has not confirmed yet - redirecting to registration", model.Email); return(RedirectToAction("Index", "RegisterAccount")); } logger.Trace("Generating code for password reset"); var code = await userManager.GeneratePasswordResetTokenAsync(user); logger.Trace("Code = {0}", code); var callbackUrl = Url.Action("Callback", "ForgotPassword", new { userId = user.Id, code = code, area = "Account" }, protocol: Context.Request.Scheme); logger.Trace("Callback URL = {0}", code); if (!WebConfiguration.Instance.DevelopmentMode) { logger.Trace("In Prod Mode - initiating email confirmation"); var notified = await Notifier.Instance.SendResetPasswordLinkAsync(user, callbackUrl); if (!notified.Successful) { logger.Error("Notification to {0} failed", model.Email); ModelState.AddModelError("", "Could not send reset password link"); return(View(model)); } } ViewBag.CallbackUrl = callbackUrl; return(View("CheckEmail")); }
public void Process(ArraySegment <byte> data) { var count = data.Count; var buf = data.Array; const int leastLen = 1 + 1 + 3 + 3 + 3; if (buf == null || count < leastLen) { AppLogger.Error($"corruted sample data,received len: {count}"); return; } var extraBlockCount = (count - leastLen + 2) / 3; var startIdx = data.Offset; startIdx++; var order = buf[startIdx]; startIdx++; /* * var chan1 = new ArraySegment<byte>(buf, startIdx, 3); * startIdx += 3; * var chan2 = new ArraySegment<byte>(buf, startIdx, 3); * startIdx += 3; * var chan3 = new ArraySegment<byte>(buf, startIdx, 3); * startIdx += 3; * * AppLogger.Debug($"sample data received,order:{order},ch1:{chan1.Show()},ch2:{chan2.Show()},ch3:{chan3.Show()}"); * * var endInd = data.Offset + count; * var blocks = new List<ArraySegment<byte>>(extraBlockCount + 3); * blocks.Add(chan1); * blocks.Add(chan2); * blocks.Add(chan3); * * if (extraBlockCount > 0) * { * for (var i = 0; i < extraBlockCount; i++) * { * if (startIdx + 3 <= endInd) * blocks.Add(new ArraySegment<byte>(buf, startIdx, 3)); * else * blocks.Add(new ArraySegment<byte>(buf, startIdx, data.Offset + count - startIdx)); * * startIdx += 3; * } * AppLogger.Debug($"extra {extraBlockCount} channel data:{blocks.Show()}"); * } */ CommitStartStop(true); var dataSeg = new ArraySegment <byte>(buf, startIdx, (extraBlockCount + 3) * 3); var disIntBuf = BitDataConverter.ConvertFromPlatform(dataSeg, bufferManager); _dataStream?.OnNext((order, disIntBuf, dataSeg)); bufferManager.ReturnBuffer(disIntBuf.Array); }
public ActionResult Login(SSO.DataModel.LoginRequsetModel request) { DataModel.LoginResposeModel serviceResponse = new DataModel.LoginResposeModel(); request.RequestDateTime = DateTimeOffset.UtcNow; request.RequestIpAddress = Request.UserHostAddress; try { //call the service to do the login serviceResponse = AuthService.Login(request); //Validate the service call result if (serviceResponse.IsAuthorized) { AuthenticationProperties options = new AuthenticationProperties(); options.AllowRefresh = true; options.IsPersistent = true; options.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(1); //Add the authorized user to the OWIN middleware var claims = new[] { new Claim(ClaimTypes.Name, request.Username), new Claim(ClaimTypes.Role, serviceResponse.UserLevel.ToString()), new Claim("AcessToken", string.Format("Bearer {0}", serviceResponse.AccessToken)), }; var identity = new ClaimsIdentity(claims, "ApplicationCookie"); Request.GetOwinContext().Authentication.SignIn(options, identity); } } catch (Exception e) { serviceResponse.ErrorMessage = "Failed to login user in service"; AppLogger.Error(e, serviceResponse.ErrorMessage); } //Based on the user level, redirect to the proper page if (serviceResponse.UserLevel == 1) { return(Json(Url.Action("Index", "Admin"))); } else if (serviceResponse.UserLevel == 2) { return(Json(Url.Action("Index", "Normal"))); } else { return(Json("User Not Found|")); } }
private void Send( string tts) { var server = Config.Instance.TTSServerAddress; var port = Config.Instance.TTSServerPort; if (string.IsNullOrEmpty(server)) { AppLogger.Error("TTS Server address is empty."); return; } if (port > 65535 || port < 1) { AppLogger.Error("TTS Server port is invalid."); return; } if (server.ToLower() == "localhost") { server = "127.0.0.1"; } try { lock (this) { using (var tcp = new TcpClient(server, port)) using (var ns = tcp.GetStream()) using (var buffer = new MemoryStream()) using (var bw = new BinaryWriter(buffer)) { var messageAsBytes = Encoding.UTF8.GetBytes(tts); bw.Write(BoyomiCommand); bw.Write((short)Config.Instance.TTSSpeed); bw.Write(BoyomiTone); bw.Write((short)Config.Instance.TTSVolume); bw.Write(BoyomiVoice); bw.Write(BoyomiTextEncoding); bw.Write(messageAsBytes.Length); bw.Write(messageAsBytes); bw.Flush(); ns.Write(buffer.ToArray(), 0, (int)buffer.Length); ns.Flush(); } } } catch (Exception ex) { AppLogger.Error("Exception occurred when sending to the TTS server.", ex); } }
//启动监控 public void StartDispatcher() { try { _dispatcherCore.StartRun(); } catch (Exception ex) { AppLogger.Error($"{ex.Message} {ex.StackTrace}"); } }
/// <summary> /// Decorated Handle /// </summary> public override async Task Handle(TEvent @event) { try { await Decorated.Handle(@event); } catch (Exception ex) { _logger.Error(ex); throw; } }