コード例 #1
0
 /// <summary>
 ///     开始日志监测
 /// </summary>
 /// <param name="data"></param>
 private static void BeginMonitor(RouteData data)
 {
     if (!LogRecorder.LogMonitor)
     {
         return;
     }
     try
     {
         LogRecorder.BeginMonitor(data.Uri.ToString());
         LogRecorder.BeginStepMonitor("HTTP");
         var args = new StringBuilder();
         args.Append("Headers:");
         args.Append(JsonConvert.SerializeObject(data.Headers));
         LogRecorder.MonitorTrace(args.ToString());
         LogRecorder.MonitorTrace($"Method:{data.HttpMethod}");
     }
     catch (Exception e)
     {
         LogRecorder.MonitorTrace(e.Message);
         LogRecorder.Exception(e);
     }
     finally
     {
         LogRecorder.EndStepMonitor();
     }
 }
コード例 #2
0
 /// <summary>
 /// 结束处理
 /// </summary>
 /// <param name="request"></param>
 /// <param name="response"></param>
 /// <param name="cancellationToken"></param>
 private void OnEnd(HttpRequestMessage request, HttpResponseMessage response, CancellationToken cancellationToken)
 {
     using (IocScope.CreateScope())
     {
         if (!response.IsSuccessStatusCode)
         {
             HttpStatusCode statusCode = response.StatusCode;
             if (statusCode != HttpStatusCode.NotFound && statusCode != HttpStatusCode.MethodNotAllowed)
             {
                 ;
             }
         }
         for (int index = Handlers.Count - 1; index >= 0; index--)
         {
             IHttpSystemHandler handler = Handlers[index];
             try
             {
                 handler.OnEnd(request, cancellationToken, response);
             }
             catch (Exception ex)
             {
                 LogRecorder.Exception(ex);
             }
         }
     }
 }
コード例 #3
0
 /// <summary>
 ///     开始计数
 /// </summary>
 /// <returns></returns>
 private static void EndMonitor(RouteData data)
 {
     if (!LogRecorder.LogMonitor)
     {
         return;
     }
     try
     {
         if (!string.IsNullOrWhiteSpace(data.Uri.Query))
         {
             LogRecorder.MonitorTrace($"Query:{data.Uri.Query}");
         }
         if (!string.IsNullOrWhiteSpace(data.Form))
         {
             LogRecorder.MonitorTrace($"Form:{data.Form}");
         }
         if (!string.IsNullOrWhiteSpace(data.Context))
         {
             LogRecorder.MonitorTrace("Context:" + data.Context);
         }
         LogRecorder.MonitorTrace($"Status : {data.Status}");
         LogRecorder.MonitorTrace($"Result:{data.ResultMessage}");
     }
     catch (Exception e)
     {
         LogRecorder.MonitorTrace(e.Message);
         LogRecorder.Exception(e);
     }
     finally
     {
         LogRecorder.EndMonitor();
     }
 }
コード例 #4
0
 private Task <HttpResponseMessage> DoEnd(Task <HttpResponseMessage> t1, HttpRequestMessage request, CancellationToken cancellationToken)
 {
     try
     {
         t1.Wait(cancellationToken);
         HttpResponseMessage result;
         if (t1.IsCanceled)
         {
             LogRecorder.MonitorTrace("操作被取消");
             result = request.ToResponse(ApiResult.Error(-7, "服务器正忙", "操作被取消"));
             LogRecorder.EndMonitor();
             return(Task <HttpResponseMessage> .Factory.StartNew(() => result, cancellationToken));
         }
         if (t1.IsFaulted)
         {
             LogRecorder.MonitorTrace(t1.Exception?.Message);
             LogRecorder.Exception(t1.Exception);
             result = request.ToResponse(ApiResult.Error(-1, "未知错误", t1.Exception?.Message));
         }
         else
         {
             result = t1.Result;
         }
         return(Task <HttpResponseMessage> .Factory.StartNew(delegate
         {
             OnEnd(request, result, cancellationToken);
             return result;
         }, cancellationToken));
     }
     finally
     {
         IocHelper.DisposeScope();
     }
 }
コード例 #5
0
ファイル: MyPageBase.cs プロジェクト: 5118234/EntityModel
        /// <summary>
        ///     页面操作处理入口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            CurrentPageName = GetFriendPageUrl();
            LogRecorder.BeginMonitor(CurrentPageName);
            LogRecorder.MonitorTrace(Request.Url.AbsolutePath);

            LogRequestInfo();
            try
            {
                ProcessRequest();
            }
            catch (Exception exception)
            {
                LogRecorder.EndStepMonitor();
                LogRecorder.BeginStepMonitor("Exception");
                LogRecorder.MonitorTrace(exception.Message);
                LogRecorder.Exception(exception);
                Debug.WriteLine(exception);
                OnFailed(exception);
                LogRecorder.EndStepMonitor();
            }
            LogRecorder.BeginStepMonitor("Result");
            OnResult();
            LogRecorder.EndStepMonitor();
            LogRecorder.EndMonitor();
        }
コード例 #6
0
        private IDatabase CreateClient(int db)
        {
            Monitor.Enter(LockObj);
            try
            {
                if (_client == null)
                {
                    return(_client = connect.GetDatabase(db));
                }

                if (_db == db)
                {
                    return(_client);
                }

                _client = connect.GetDatabase(db);
                _db     = db;
                return(_client);
            }
            catch (Exception ex)
            {
                LogRecorder.Exception(ex, ConnectString);
                throw;
            }
            finally
            {
                Monitor.Exit(LockObj);
            }
        }
コード例 #7
0
        /// <summary>
        ///     通过Post调用
        /// </summary>
        /// <param name="apiName"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        public ApiValueResult Post(string apiName, string form)
        {
            LogRecorder.BeginStepMonitor("内部API调用" + ToUrl(apiName));
            string ctx = string.IsNullOrEmpty(Bearer) ? null : $"Bearer {Bearer}";

            LogRecorder.MonitorTrace(ctx);
            LogRecorder.MonitorTrace("Arguments:" + form);
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ToUrl(apiName));

            req.Method      = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.Headers.Add(HttpRequestHeader.Authorization, ctx);
            try
            {
                using (Stream rs = req.GetRequestStream())
                {
                    byte[] formData = Encoding.UTF8.GetBytes(form);
                    rs.Write(formData, 0, formData.Length);
                }
            }
            catch (Exception ex)
            {
                LogRecorder.Exception(ex);
                LogRecorder.EndStepMonitor();
                return(ErrorResult(-3));
            }
            using (MonitorScope.CreateScope("Caller Remote"))
            {
                return(GetResult(req));
            }
        }
コード例 #8
0
 /// <summary>
 /// 构造
 /// </summary>
 public StackExchangeRedis()
 {
     if (connect == null)
     {
         connect = ConnectionMultiplexer.Connect(ConnectString);
     }
     else
     {
         try
         {
             connect.GetDatabase().Ping();
         }
         catch (Exception e1)
         {
             LogRecorder.Exception(e1, "StackExchangeRedis.ctor");
             try
             {
                 connect.Close();
                 connect.Dispose();
             }
             catch (Exception e)
             {
                 LogRecorder.Exception(e, "StackExchangeRedis.ctor");
             }
             connect = ConnectionMultiplexer.Connect(ConnectString);
         }
     }
 }
コード例 #9
0
ファイル: LogSubscribe.cs プロジェクト: ym1100/MicroZero
        /// <inheritdoc />
        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public override void Handle(PublishItem args)
        {
            try
            {
                List <RecordInfo> items = JsonConvert.DeserializeObject <List <RecordInfo> >(args.Content);
                foreach (var info in items)
                {
                    StringBuilder code = new StringBuilder();

                    code.AppendLine("<table style='width:99%'><col style='width:120px'/><col/><col style='width:120px'/><col/>");
                    code.AppendLine($"<tr style='border-bottom: silver 1px solid;padding: 4px'><td>类型</td><td>{info.TypeName}</td><td>序号</td><td>{info.Index}</td></tr>");
                    code.AppendLine($"<tr style='border-bottom: silver 1px solid;padding: 4px'><td>标识</td><td>{info.RequestID}</td><td>时间</td><td>{DateTime.Now}({info.Time})</td></tr>");
                    code.AppendLine($"<tr style='border-bottom: silver 1px solid;padding: 4px'><td>机器</td><td>{info.Machine}</td><td>用户</td><td>{info.User}</td></tr>");
                    code.AppendLine("</table>");
                    switch (info.Type)
                    {
                    case LogType.Monitor:
                        FormatMonitor(code, info);
                        break;

                    default:
                        code.Append($"<div>{info.Message.Replace("\n", "<br/>")}</div>");
                        break;
                    }
                    WebSocketPooler.Instance?.Publish("Log", code.ToString());
                }
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e);
            }
        }
コード例 #10
0
ファイル: StepTackProxy.cs プロジェクト: ym1100/MicroZero
        private void OnEnd(Task task)
        {
            lock (this)
            {
                // ReSharper disable PossibleNullReferenceException
                var item = task.AsyncState as TackStepItem;
                if (item.StepKey != StepKey)
                {
                    return;
                }
                // ReSharper restore PossibleNullReferenceException
                _task = null;
                switch (task.Status)
                {
                case TaskStatus.Faulted:
                    LogRecorder.Exception(task.Exception);
                    Status = CommandStatus.Faulted;
                    break;

                default:
                    Status = CommandStatus.Succeed;
                    break;
                }
                Dispatcher.BeginInvoke(new Action(Exist));
            }
        }
コード例 #11
0
        /// <summary>
        ///     通过Post调用
        /// </summary>
        /// <param name="apiName"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        public ApiValueResult <string> Post(string apiName, string form)
        {
            LogRecorder.BeginStepMonitor("内部API调用" + ToUrl(apiName));

            var ctx = string.IsNullOrEmpty(Bearer) ? null : $"Bearer {Bearer}";

            LogRecorder.MonitorTrace(ctx);
            LogRecorder.MonitorTrace("Arguments:" + form);

            var req = (HttpWebRequest)WebRequest.Create(ToUrl(apiName));

            req.Method      = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.Headers.Add(HttpRequestHeader.Authorization, ctx);

            try
            {
                using (var rs = req.GetRequestStream())
                {
                    var formData = Encoding.UTF8.GetBytes(form);
                    rs.Write(formData, 0, formData.Length);
                }
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e);
                LogRecorder.EndStepMonitor();
                return(ApiValueResult <string> .ErrorResult(ErrorCode.NetworkError));
            }

            return(GetResult(req));
        }
コード例 #12
0
        private static void station_join(string station, string content)
        {
            if (String.IsNullOrEmpty(content))
            {
                return;
            }
            StationConfig cfg;

            try
            {
                cfg = JsonConvert.DeserializeObject <StationConfig>(content);
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e);
                return;
            }
            cfg.State = StationState.Run;
            if (StationProgram.Configs.ContainsKey(station))
            {
                StationProgram.Configs[station] = cfg;
            }
            else
            {
                StationProgram.Configs.Add(station, cfg);
            }
            if (StationProgram.Stations.ContainsKey(station))
            {
                StationProgram.Stations[station].Config = cfg;
                StationProgram.WriteLine($"{station} is join");
                StationEvent?.Invoke(cfg, new StationEventArgument("station_join", cfg));
                ZeroStation.Run(StationProgram.Stations[station]);
            }
        }
コード例 #13
0
        private static void station_install(string station, string content)
        {
            if (String.IsNullOrEmpty(content))
            {
                return;
            }
            StationConfig cfg;

            try
            {
                cfg = JsonConvert.DeserializeObject <StationConfig>(content);
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e);
                return;
            }
            cfg.State = StationState.None;
            if (StationProgram.Configs.ContainsKey(station))
            {
                StationProgram.Configs[station] = cfg;
            }
            else
            {
                StationProgram.Configs.Add(station, cfg);
            }
            StationEvent?.Invoke(cfg, new StationEventArgument("station_install", cfg));
        }
コード例 #14
0
        /// <summary>
        ///     开始时的处理
        /// </summary>
        /// <returns>如果返回内容不为空,直接返回,后续的处理不再继续</returns>
        Task <HttpResponseMessage> IHttpSystemHandler.OnBegin(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (!LogRecorder.LogMonitor)
            {
                return(null);
            }
            LogRecorder.BeginMonitor(request.RequestUri.ToString());
            try
            {
                var args = new StringBuilder();
                args.Append("Headers:");
                foreach (var head in request.Headers)
                {
                    args.Append($"【{head.Key}】{head.Value.LinkToString('|')}");
                }
                LogRecorder.MonitorTrace(args.ToString());
                LogRecorder.MonitorTrace($"Method:{request.Method}");

                LogRecorder.MonitorTrace($"QueryString:{request.RequestUri.Query}");

                RecordRequestToCode(request);
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e);
            }
            return(null);
        }
コード例 #15
0
ファイル: BearerHandler.cs プロジェクト: wondial/EntityModel
        /// <summary>
        ///     检查设备标识
        /// </summary>
        /// <returns>
        ///     0:表示通过验证,可以继续
        ///     1:令牌为空
        ///     2:令牌是伪造的
        /// </returns>
        private int CheckDeviceId(string token)
        {
            if (Request.RequestUri.LocalPath == "/v1/oauth/getdid")
            {
                return(ErrorCode.Success);
            }

            IBearValidater            checker = IocHelper.Create <IBearValidater>();
            ApiResult <LoginUserInfo> result;

            try
            {
                result = checker.ValidateDeviceId(token);
            }
            catch (Exception ex)
            {
                LogRecorder.Exception(ex);
                return(ErrorCode.Success);
            }
            if (!result.Success)
            {
                return(result.Status.ErrorCode);
            }
            CreateApiContext(result.ResultData, token);
            LogRecorder.MonitorTrace("Authorization:匿名用户");
            return(ErrorCode.Success);
        }
コード例 #16
0
ファイル: HttpHandler.cs プロジェクト: cuiopen/ZeroNet
        Task <HttpResponseMessage> DoEnd(Task <HttpResponseMessage> t1, HttpRequestMessage request, CancellationToken cancellationToken)
        {
            t1.Wait(cancellationToken);
            HttpResponseMessage result;

            if (t1.IsCanceled)
            {
                LogRecorder.MonitorTrace("操作被取消");
                result = request.ToResponse(ApiResult.Error(ErrorCode.Ignore, "服务器正忙", "操作被取消"));
                LogRecorder.EndAllStepMonitor();
                LogRecorder.EndMonitor();
                return(Task <HttpResponseMessage> .Factory.StartNew(() => result, cancellationToken));
            }
            if (t1.IsFaulted)
            {
                LogRecorder.MonitorTrace(t1.Exception?.Message);
                LogRecorder.Exception(t1.Exception);
                result = request.ToResponse(ApiResult.Error(ErrorCode.UnknowError, "未知错误", t1.Exception?.Message));
            }
            else
            {
                result = t1.Result;
            }

            /*
             * result.ContinueWith((task, state) => , null,
             *  TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.ExecuteSynchronously);
             */
            return(Task <HttpResponseMessage> .Factory.StartNew(() =>
            {
                OnEnd(request, result, cancellationToken);
                return result;
            }, cancellationToken));
        }
コード例 #17
0
 private bool Request(string msg, ref int retry)
 {
     if (++retry > 5)
     {
         LogRecorder.Error($"数据事件服务(EntityEvent)无法连接!\r\n{msg}");
         return(false);
     }
     try
     {
         lock (this)
         {
             _socket.Request(msg);
         }
         return(true);
     }
     catch (Exception e)
     {
         LogRecorder.Exception(e);
         StationProgram.WriteLine($"【EntityEvent】publish error =>{e.Message}");
         retry++;
         Thread.Sleep(10);
         CreateSocket();
         return(Request(msg, ref retry));
     }
 }
コード例 #18
0
        /// <summary>
        /// 结束处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="cancellationToken"></param>
        private void OnEnd(HttpRequestMessage request, HttpResponseMessage response, CancellationToken cancellationToken)
        {
            if (!response.IsSuccessStatusCode)
            {
                //https://www.cnblogs.com/fengsiyi/archive/2013/05/27/3101404.html
                switch (response.StatusCode)
                {
                case HttpStatusCode.NotFound:    //指示请求的资源不在服务器上。
                    break;

                case HttpStatusCode.MethodNotAllowed:    //指示请求的资源上不允许请求方法(POST 或   GET)。
                    break;

                case HttpStatusCode.UnsupportedMediaType:    //指示请求是不支持的类型。
                    break;
                }
            }
            for (var index = Handlers.Count - 1; index > 0; index++)
            {
                var handler = Handlers[index];
                try
                {
                    handler.OnEnd(request, cancellationToken, response);
                }
                catch (Exception e)
                {
                    LogRecorder.Exception(e);
                }
            }
            ContextHelper.Remove("ApiContext");
        }
コード例 #19
0
        /// <summary>
        /// 协议错误
        /// </summary>
        /// <param name="exception"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        private string ProtocolError(WebException exception, ref WebExceptionStatus status)
        {
            try
            {
                var codes = exception.Message.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries);
                if (codes.Length == 3)
                {
                    if (int.TryParse(codes[1], out var s))
                    {
                        switch (s)
                        {
                        case 404:
                            return(ToErrorString(ErrorCode.NetworkError, "页面不存在", "页面不存在"));

                        case 503:
                            return(ToErrorString(ErrorCode.NetworkError, "拒绝访问", "页面不存在"));
                            //default:
                            //    return ToErrorString(ErrorCode.NetworkError, $"错误{s}", exception.Message);
                        }
                    }
                }
                var msg = ReadResponse(exception.Response);
                RuntimeWaring.Waring(Host, ApiName, msg);
                return(msg); //ToErrorString(ErrorCode.NetworkError, "未知错误", );
            }
            catch (Exception e)
            {
                status = WebExceptionStatus.UnknownError;
                LogRecorder.Exception(e);
                return(ToErrorString(ErrorCode.NetworkError, "未知错误", e.Message));
            }
        }
コード例 #20
0
        private static void OnBehaviorActionPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var eb = d as DependencyBehavior <TDependency>;

            if (eb == null || !eb._isAttached || Equals(e.OldValue, e.NewValue))
            {
                return;
            }
            try
            {
                BehaviorAction <TDependency> action = e.OldValue as BehaviorAction <TDependency>;
                if (action != null && action.DetachAction != null)
                {
                    action.DetachAction(eb.AssociatedObject);
                }
                action = e.NewValue as BehaviorAction <TDependency>;
                if (action != null && action.AttachAction != null)
                {
                    action.AttachAction(eb.AssociatedObject);
                }
            }
            catch (Exception exception)
            {
                LogRecorder.Exception(exception);
            }
        }
コード例 #21
0
        /// <summary>
        /// 重载
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            using (MonitorScope.CreateScope(request.RequestUri.ToString()))
            {
                foreach (var handler in Handlers)
                {
                    try
                    {
                        var task = handler.OnBegin(request, cancellationToken);
                        if (task == null)
                        {
                            continue;
                        }
                        ContextHelper.Remove("ApiContext");
                        return(task);
                    }
                    catch (Exception e)
                    {
                        LogRecorder.Exception(e);
                    }
                }
                var result = base.SendAsync(request, cancellationToken);

                result.ContinueWith((task, state) => OnEnd(request, result.Result, cancellationToken), null,
                                    TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.ExecuteSynchronously);

                return(result);
            }
        }
コード例 #22
0
        /// <summary>
        ///     取得Socket对象
        /// </summary>
        /// <param name="type"></param>
        /// <param name="socket"></param>
        /// <returns></returns>
        private static bool GetSocket(string type, out RequestSocket socket)
        {
            try
            {
                lock (Publishers)
                {
                    if (Publishers.TryGetValue(type, out socket))
                    {
                        return(true);
                    }
                    var config = StationProgram.GetConfig(type);
                    if (config == null)
                    {
                        StationProgram.WriteLine($"【{type}】connect error =>无法拉取配置");
                        return(false);
                    }

                    socket = new RequestSocket();
                    socket.Options.Identity =
                        StationProgram.Config.StationName.ToAsciiBytes(); //RandomOperate.Generate(8).ToAsciiBytes();
                    socket.Options.ReconnectInterval = new TimeSpan(0, 0, 0, 0, 200);
                    socket.Connect(config.OutAddress);
                    Publishers.Add(type, socket);
                }
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e);
                StationProgram.WriteLine($"【{type}】connect error =>连接时发生异常:{e}");
                socket = null;
                return(false);
            }

            return(true);
        }
コード例 #23
0
ファイル: HttpRouter.cs プロジェクト: cuiopen/ZeroNet
        /// <summary>
        ///     远程调用
        /// </summary>
        /// <returns></returns>
        private string CallHttp()
        {
            // 当前请求调用的模型对应的主机名称
            string httpHost;

            // 当前请求调用的Api名称
            var httpApi = Data.RouteHost == HostConfig.DefaultHost ? Data.Uri.PathAndQuery : $"{Data.ApiName}{Data.Uri.Query}";

            // 查找主机
            if (Data.RouteHost.Hosts.Length == 1)
            {
                httpHost = Data.RouteHost.Hosts[0];
            }
            else
            {
                lock (Data.RouteHost)
                {
                    //平均分配
                    httpHost = Data.RouteHost.Hosts[Data.RouteHost.Next];
                    if (++Data.RouteHost.Next >= Data.RouteHost.Hosts.Length)
                    {
                        Data.RouteHost.Next = 0;
                    }
                }
            }
            // 远程调用
            var caller = new HttpApiCaller(httpHost)
            {
                Bearer = $"Bearer {ApiContext.RequestContext.Bear}"
            };
            var req = caller.CreateRequest(httpApi, Data.HttpMethod, Request, Data);

            LogRecorder.BeginStepMonitor("内部HTTP调用");
            LogRecorder.MonitorTrace($"Url:{req.RequestUri.PathAndQuery}");
            LogRecorder.MonitorTrace($"Auth:{caller.Bearer}");

            try
            {
                // 远程调用状态
                Data.ResultMessage = caller.GetResult(req, out var webStatus);
                LogRecorder.MonitorTrace(webStatus.ToString());
                if (webStatus != WebExceptionStatus.Success)
                {
                    Data.Status = RouteStatus.RemoteError;
                }
            }
            catch (Exception ex)
            {
                LogRecorder.Exception(ex);
                LogRecorder.MonitorTrace($"发生异常:{ex.Message}");
                Data.ResultMessage = RouteRuntime.NetworkError;
                Data.Status        = RouteStatus.RemoteError;
            }
            finally
            {
                LogRecorder.MonitorTrace(Data.ResultMessage);
                LogRecorder.EndStepMonitor();
            }
            return(Data.ResultMessage);
        }
コード例 #24
0
        /// <summary>
        ///     取返回值
        /// </summary>
        /// <returns></returns>
        public async Task <string> Call()
        {
            string jsonResult;

            UserState = HttpOperatorStateType.Success;
            //ZeroState = ZeroOperatorStateType.Ok;
            try
            {
                var resp = await RemoteRequest.GetResponseAsync();

                jsonResult = await ReadResponse(resp);
            }
            catch (WebException e)
            {
                LogRecorder.Exception(e);
                jsonResult = e.Status == WebExceptionStatus.ProtocolError
                    ? await ProtocolError(e)
                    : ResponseError(e);
            }
            catch (Exception e)
            {
                UserState = HttpOperatorStateType.LocalException;
                //ZeroState = ZeroOperatorStateType.LocalException;
                LogRecorder.Exception(e);
                jsonResult = ToErrorString(ErrorCode.LocalException, "未知错误", e.Message);
            }
            return(jsonResult);
        }
コード例 #25
0
        /// <summary>
        /// 检查旧标识
        /// </summary>
        /// <returns>
        /// 0:表示通过验证,可以继续
        /// 1:令牌为空
        /// 2:令牌是伪造的
        /// </returns>
        int CheckServiceKey()
        {
            InternalCallContext context;

            try
            {
                context = JsonConvert.DeserializeObject <InternalCallContext>(token);
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e);
                return(2);
            }

            var checker = IocHelper.Create <IBearValidater>();
            var result  = checker.ValidateServiceKey(context.ServiceKey.ToString());

            if (!result.Result)
            {
                return(result.Status.ErrorCode);
            }
            if (context.UserId > 0)
            {
                var user = checker.GetUserProfile(context.UserId);
                if (!user.Result)
                {
                    return(user.Status.ErrorCode);
                }
                ApiContext.SetCustomer(user.ResultData);
            }
            ApiContext.SetRequestContext(context);
            return(0);
        }
コード例 #26
0
        /// <summary>
        ///     进入系统侦听
        /// </summary>
        public static void RunMonitor()
        {
            var timeout = new TimeSpan(0, 0, 1);

            try
            {
                StationProgram.WriteLine("System Monitor Runing...");
                var subscriber = new SubscriberSocket();
                subscriber.Options.Identity          = StationProgram.Config.StationName.ToAsciiBytes();
                subscriber.Options.ReconnectInterval = new TimeSpan(0, 0, 0, 0, 200);
                subscriber.Connect(StationProgram.ZeroMonitorAddress);
                subscriber.Subscribe("");

                while (StationProgram.State == StationState.Run)
                {
                    if (!subscriber.TryReceiveFrameString(timeout, out var result))
                    {
                        continue;
                    }
                    OnMessagePush(result);
                }
            }
            catch (Exception e)
            {
                StationProgram.WriteLine(e.Message);
                LogRecorder.Exception(e);
            }
            if (StationProgram.State == StationState.Run)
            {
                Task.Factory.StartNew(RunMonitor);
            }
        }
コード例 #27
0
        /// <summary>
        ///     检查设备标识
        /// </summary>
        /// <returns>
        ///     0:表示通过验证,可以继续
        ///     1:令牌为空
        ///     2:令牌是伪造的
        /// </returns>
        private int CheckDeviceId(HttpRequestMessage request, string token)
        {
            if (string.IsNullOrWhiteSpace(token) || token.Contains('.') || token.Length <= 33)
            {
                return(ErrorCode.DenyAccess);
            }
            for (var index = 1; index < token.Length; index++)
            {
                var ch = token[index];
                if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ch == '_')
                {
                    continue;
                }
                return(ErrorCode.DenyAccess);
            }
            var checker = IocHelper.Create <IBearValidater>();
            ApiResult <LoginUserInfo> result;

            try
            {
                result = checker.ValidateDeviceId(token);
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e);
                return(0); //ErrorCode.Auth_Device_Unknow;
            }
            if (!result.Result)
            {
                return(result.Status.ErrorCode);
            }
            CreateApiContext(result.ResultData, token);
            LogRecorder.MonitorTrace("Authorization:匿名用户");
            return(0);
        }
コード例 #28
0
        /// <summary>
        /// 开始计数
        /// </summary>
        /// <returns></returns>
        public void End(RouteData data)
        {
            data.End = DateTime.Now;
            try
            {
                var tm = (DateTime.Now - Start).TotalMilliseconds;
                if (tm > 200)
                {
                    LogRecorder.Warning($"{data.HostName}/{data.ApiName}:执行时间异常({tm:F2}ms):");
                }

                if (tm > AppConfig.Config.SystemConfig.WaringTime)
                {
                    RuntimeWaring.Waring(data.HostName, data.ApiName, $"执行时间异常({tm:F0}ms)");
                }

                long unit = DateTime.Today.Year * 1000000 + DateTime.Today.Month * 10000 + DateTime.Today.Day * 100 + DateTime.Now.Hour;
                if (unit != Unit)
                {
                    Unit = unit;
                    Save();
                    Station = new CountItem();
                }

                Station.SetValue(tm, data);
                if (string.IsNullOrWhiteSpace(data.HostName))
                {
                    return;
                }
                CountItem host;
                lock (Station)
                {
                    if (!Station.Items.TryGetValue(data.HostName, out host))
                    {
                        Station.Items.Add(data.HostName, host = new CountItem());
                    }
                }
                host.SetValue(tm, data);

                if (string.IsNullOrWhiteSpace(data.ApiName))
                {
                    return;
                }
                CountItem api;
                lock (host)
                {
                    if (!host.Items.TryGetValue(data.ApiName, out api))
                    {
                        host.Items.Add(data.ApiName, api = new CountItem());
                    }
                }
                api.SetValue(tm, data);
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e);
            }
        }
コード例 #29
0
ファイル: SubStation.cs プロジェクト: cuiopen/ZeroNet
        /// <summary>
        /// 命令轮询
        /// </summary>
        /// <returns></returns>
        private void PollTask()
        {
            StationProgram.WriteLine($"【{StationName}】poll start");
            var timeout = new TimeSpan(0, 0, 5);

            _inPoll = true;
            while (RunState == StationState.Run)
            {
                try
                {
                    if (!_socket.TryReceiveFrameString(timeout, out var title, out var more) || !more)
                    {
                        continue;
                    }
                    if (!_socket.TryReceiveFrameBytes(out var description, out more) || !more)
                    {
                        continue;
                    }
                    PublishItem item = new PublishItem
                    {
                        Title = title
                    };
                    int idx = 1;
                    while (more)
                    {
                        if (!_socket.TryReceiveFrameString(out var val, out more))
                        {
                            continue;
                        }
                        switch (description[idx++])
                        {
                        case ZeroHelper.zero_pub_sub:
                            item.SubTitle = val;
                            break;

                        case ZeroHelper.zero_pub_publisher:
                            item.Station = val;
                            break;

                        case ZeroHelper.zero_arg:
                            item.Content = val;
                            break;
                        }
                    }
                    _items.Push(item);
                }
                catch (Exception e)
                {
                    StationProgram.WriteLine($"【{StationName}】poll error{e.Message}...");
                    LogRecorder.Exception(e);
                    RunState = StationState.Failed;
                }
            }
            _inPoll = false;
            StationProgram.WriteLine($"【{StationName}】poll stop");
            _items.Save(CacheFileName);
            CloseSocket();
        }
コード例 #30
0
 /// <summary>
 ///     发出属性修改事件
 /// </summary>
 /// <param name="args">属性</param>
 private void RaisePropertyChangedInner(PropertyChangedEventArgs args)
 {
     try
     {
         propertyChanged?.Invoke(this, args);
     }
     catch (Exception ex)
     {
         LogRecorder.Exception(ex);
     }
 }