コード例 #1
0
        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}");
                    }
                }
            }
        }
コード例 #2
0
 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);
     }
 }
コード例 #3
0
ファイル: Locker.cs プロジェクト: temsss/CyberLock
 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);
 }
コード例 #4
0
        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));
            }
        }
コード例 #5
0
        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));
            }
        }
コード例 #6
0
        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);
        }
コード例 #7
0
        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);
        }
コード例 #8
0
        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);
        }
コード例 #9
0
        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");
            }
        }
コード例 #10
0
        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))));
        }
コード例 #11
0
            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");
            }
コード例 #12
0
        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);
            }
        }
コード例 #13
0
ファイル: Class1.cs プロジェクト: jk464479460/target
        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}");
            }
        }
コード例 #14
0
ファイル: Class1.cs プロジェクト: jk464479460/target
        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);
                }
            }
        }
コード例 #15
0
ファイル: Class1.cs プロジェクト: jk464479460/target
        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);
        }
コード例 #16
0
        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);
                }
            }
        }
コード例 #17
0
        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" }));
        }
コード例 #18
0
ファイル: UserStatistics.cs プロジェクト: jk464479460/target
        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);
            }
        }
コード例 #19
0
 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;
     }
 }
コード例 #20
0
ファイル: UserStatistics.cs プロジェクト: jk464479460/target
        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}");
                }
            }
        }
コード例 #21
0
ファイル: PostInfo.cs プロジェクト: jk464479460/target
        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);
        }
コード例 #22
0
        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));
            }
        }
コード例 #23
0
 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}");
         }
     }
 }
コード例 #24
0
        //发送一次心跳
        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);
            }
        }
コード例 #25
0
        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"));
        }
コード例 #26
0
            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);
            }
コード例 #27
0
        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|"));
            }
        }
コード例 #28
0
ファイル: BoyomiClient.cs プロジェクト: nyahaass/RINGS
        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);
            }
        }
コード例 #29
0
 //启动监控
 public void StartDispatcher()
 {
     try
     {
         _dispatcherCore.StartRun();
     }
     catch (Exception ex)
     {
         AppLogger.Error($"{ex.Message} {ex.StackTrace}");
     }
 }
コード例 #30
0
 /// <summary>
 /// Decorated Handle
 /// </summary>
 public override async Task Handle(TEvent @event)
 {
     try
     {
         await Decorated.Handle(@event);
     }
     catch (Exception ex)
     {
         _logger.Error(ex);
         throw;
     }
 }