public void ChangeScale(int newScaleSize) { if (newScaleSize <= 0) { throw new ArgumentOutOfRangeException("newScaleSize", "Must be Greater than Zero"); } ScaleSize = newScaleSize; if (!running) { return; } lock (lockWorkers) { // Scale down while (workers.Count > ScaleSize) { workers[0].Cancel(); workers.RemoveAt(0); } // Scale up while (workers.Count < ScaleSize) { var worker = new ServiceWorkerAdapter <TNotification>(this, ServiceConnectionFactory.Create()); workers.Add(worker); worker.Start(); } LogAgent.Debug("Scaled Changed to: " + workers.Count); } }
/// <summary> /// 执行带body体的POST请求。 /// </summary> /// <param name="url">请求地址,含URL参数</param> /// <param name="body">请求body体字节流</param> /// <param name="contentType">body内容类型</param> /// <param name="headerParams">请求头部参数</param> /// <returns>HTTP响应</returns> public string DoPostJson(BrowserPara browserPara) { LogAgent.Info("[Request]->Url:{0};Parameter:{1};Method:{2}", browserPara.Uri, browserPara.PostData, browserPara.Method.ToString()); string url = browserPara.Uri; HttpWebRequest req = GetWebRequest(browserPara, "POST"); req.ContentType = browserPara.ContentType; string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线 req.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary; System.IO.Stream reqStream = req.GetRequestStream(); byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); reqStream.Close(); HttpWebResponse rsp = (HttpWebResponse)req.GetResponse(); Encoding encoding = GetResponseEncoding(rsp); string responseFromServer = GetResponseAsString(req, rsp, encoding); LogAgent.Info(req.CookieContainer.GetCookieHeader(new Uri(browserPara.Uri))); LogAgent.Info("[Response]->Url:{0};{1}", browserPara.Uri, responseFromServer); return(responseFromServer); }
private void Execute() { if (cts.Token.IsCancellationRequested) { return; } var list = this.GetExecutors(); foreach (var item in list) { Task.Factory.StartNew(() => { item.Run(); }); } var dt = DateTime.Now; dt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, 0); var next = dt.AddMinutes(1); var due = Convert.ToInt32(Math.Ceiling((next - DateTime.Now).TotalMilliseconds)); Task.Factory.StartNew(async() => { try { await Task.Delay(due, cts.Token); Execute(); } catch (Exception ex) { LogAgent.Error(ex.ToString()); } }, cts.Token); }
public void Stop(bool immediately = false) { if (!running) { throw new OperationCanceledException("ServiceBroker has already been signaled to Stop"); } running = false; notifications.CompleteAdding(); lock (lockWorkers) { // Kill all workers right away if (immediately) { workers.ForEach(sw => sw.Cancel()); } var all = (from sw in workers select sw.WorkerTask).ToArray(); LogAgent.Info("Stopping: Waiting on Tasks"); Task.WaitAll(all); LogAgent.Info("Stopping: Done Waiting on Tasks"); workers.Clear(); } }
private string DownloadFile(string url, string fileId) { string path = System.IO.Path.Combine(dirPath, url.Substring(url.LastIndexOf('/') + 1)); string fileName = path.Substring(path.LastIndexOf('/') + 1); string endName = fileName.Substring(fileName.LastIndexOf('.')); path = path.Replace(fileName, fileId + endName); bool status = false; try { HttpSimpleMgr.DownloadHttp(url, path); status = true; } catch (NullReferenceException e) { LogAgent.LogError(e.ToString()); if (File.Exists(path)) { File.Delete(path); } } Interlocked.Exchange(ref isDownLoading, 0); if (status) { return(path); } else { return(string.Empty); } }
/// <summary> /// 处理新任务 /// </summary> private void ProcessNewTask() { try { var newTaskList = this.taskDocker.TaskList.Where(o => o.TaskState == TaskState.NewTask).ToList(); foreach (var task in newTaskList) { if (task.TaskState == TaskState.NewTask) { LogAgent.Info(String.Format("处理新任务:{0}", task.ToString())); ProcessTask(task); if (task.Dead) { task.Complete(); } //else //{ // this.connectionDocker.AddCase(task.GetRelatedProtocol()); //} } } } catch (Exception exception) { var m = exception.Message; LogAgent.Error("处理新任务:" + m.ToString()); } }
/// <summary> /// 接收数据回调[协议进程] /// </summary> /// <param name="receiveState"></param> protected void ReceiveCallback(NetworkState receiveState) { try { if (receiveState.RemoteHost == null) { return; } var received = receiveState.RawBuffer.Length; if (received == 0) { return; } receiveState.Buffer.WriteBytes(receiveState.RawBuffer, 0, received); List <IByteBuf> decoded; Decoder.Decode(ConnectionAdapter, receiveState.Buffer, out decoded); foreach (var message in decoded) { var networkData = NetworkData.Create(receiveState.RemoteHost, message); LogTemplate("处理数据-{0}-->>{1}", networkData.Buffer); if (ConnectionAdapter is ReactorConnectionAdapter) {//合法消息回调到线程进行分发处理 ((ReactorConnectionAdapter)ConnectionAdapter).networkDataDocker.AddNetworkData(networkData); ((EventWaitHandle)((ReactorConnectionAdapter)ConnectionAdapter).protocolEvents[(int)ProtocolEvents.PortReceivedData]).Set(); } } } catch (Exception ex) { LogAgent.Error(ex.ToString()); } }
/// <summary> /// 判断异步任务是否超时并处理。 /// </summary> private void ProcessAsyncTaskOvertime() { try { lock (this.taskDocker.TaskList) { var taskList = this.taskDocker.TaskList; for (int i = 0; i < taskList.Count; ++i) { if (taskList[i].AsyncTaskOvertime || taskList[i].Dead) { RemoveTask(taskList[i]); continue; } //检查任务对应的协议是否超时 if (taskList[i].GetRelatedProtocol().Dead) { taskList[i].Complete(TaskState.TaskOvertime); } else { this.taskDocker.SetTaskTimeout(taskList[i].GetRelatedProtocol()); } } } } catch (Exception ex) { string msg = string.Format("ProcessAsyncTaskOvertime:{0}", ex.ToString()); LogAgent.Error(msg); } }
public static string Value() { if (string.IsNullOrEmpty(fingerPrint)) { CounterToken counterToken = LogAgent.StartCounter(); string newValue = RegistryUtil.GetRegeditkeyValue(LicenseConstData.KeyRegistyPath, LicenseConstData.MacCodeKey); if (string.IsNullOrEmpty(newValue)) { string cpuId = CpuId(); string biosId = BiosId(); string baseId = BaseId(); fingerPrint = GetHash( "\nCPU >> " + cpuId + "\nBIOS >> " + biosId + "\nBASE >> " + baseId ); RegistryUtil.SetSecurityLey(fingerPrint, LicenseConstData.KeyRegistyPath, LicenseConstData.MacCodeKey); LogAgent.Info("CPU:" + cpuId + ";BIOS:" + biosId + ";BASE:" + baseId); } else { fingerPrint = newValue; } LogAgent.StopCounterAndLog(counterToken, "SystemUtil.Value:" + fingerPrint + " " + newValue); } return(fingerPrint); }
public void PlayProgress() { while (true) { Thread.Sleep(1000); switch (mgrStatus) { case 0: case 3: goto STOP_PLAY; case 2: continue; } if (string.IsNullOrEmpty(curPlayPath)) { continue; } string tmpPath = curPlayPath; curPlayPath = string.Empty; addMainAction(() => { UICtrl.Instance.OpenMPPanel(); UICtrl.Instance.mpPanel.playerHelper.Play(tmpPath); }); mgrStatus = 2; } STOP_PLAY: LogAgent.Log("销毁播放了"); }
public void OnException(ExceptionContext context) { JsonResponses jsonResponses = JsonResponses.Failed.Clone(); Exception ex = context.Exception; string errMsg = "Exception:" + ex.ToString(); if (context.Exception.GetType() == typeof(ErrorCodeException)) { ErrorCodeException errorCodeException = (ErrorCodeException)ex; //针对不同的自定义异常,做不同处理 jsonResponses.code = errorCodeException.GetErrorCode(); jsonResponses.msg = errorCodeException.GetErrorMsg(); } else if (context.Exception.GetType() == typeof(WebSocketException)) { //针对不同的自定义异常,做不同处理 WebSocketException errorCodeException = (WebSocketException)ex; jsonResponses.code = errorCodeException.ErrorCode; jsonResponses.msg = errorCodeException.Message; } else if (context.Exception.GetType() == typeof(ArgumentException)) { //针对不同的自定义异常,做不同处理 ArgumentException errorCodeException = (ArgumentException)ex; jsonResponses.msg = errorCodeException.Message; } else { jsonResponses.msg = "系统错误"; } context.Result = new JsonResult(jsonResponses); context.ExceptionHandled = true; LogAgent.Error(errMsg + " " + JsonConvert.SerializeObject(jsonResponses)); }
/// <summary> /// 用于输出参数化查询语句的SQL语句 /// </summary> /// <param name="sSQL"></param> /// <param name="t"></param> /// <returns></returns> public static string doGetSQL(string sSQL, DbParameter[] cmdParms) { string sSQLResult = sSQL; try { foreach (var propertyInfo in cmdParms) { DbParameter obj = (DbParameter)propertyInfo; if (obj == null || obj.Value == null) { sSQLResult = sSQLResult.Replace(obj.ParameterName, "null"); } else { sSQLResult = sSQLResult.Replace(obj.ParameterName, obj.Value.ToString()); } } } catch (Exception ex) { sSQLResult = "Export SQL Error:" + ex.ToString(); } LogAgent.Info(String.Format("[SQL]:{0}", sSQLResult)); return(sSQLResult); }
/// <summary> /// 发送数据 /// </summary> /// <param name="buffer"></param> /// <param name="index"></param> /// <param name="length"></param> /// <param name="destination"></param> public override void Send(byte[] buffer, int index, int length, INode destination) { var clientSocket = SocketMap[destination.nodeConfig.ToString()]; try { if (clientSocket.WasDisposed) { CloseConnection(clientSocket); return; } var buf = Allocator.Buffer(length); buf.WriteBytes(buffer, index, length); Encoder.Encode(ConnectionAdapter, buf, out List <IByteBuf> encodedMessages); foreach (var message in encodedMessages) { var state = CreateNetworkState(clientSocket.Local, destination, message, 0); ListenerSocket.BeginSendTo(message.ToArray(), 0, message.ReadableBytes, SocketFlags.None, destination.ToEndPoint <EndPoint>(), SendCallback, state); LogAgent.Info(String.Format("发送数据-{0}-->>{1}", this.Listener.reactorType, this.Encoder.ByteEncode(message.ToArray()))); clientSocket.Receiving = true; } } catch (Exception ex) { LogAgent.Error(ex.ToString()); CloseConnection(ex, clientSocket); } }
public void Close() { var originState = Interlocked.CompareExchange(ref _serverState, 3, 2); if (originState != 2) { return; } try { _server.Close(); } catch { } var clientTransportList = _clientTransportDictionary.Values.ToList(); foreach (var transport in clientTransportList) { transport.Close(); } _serverState = -1; LogAgent.Info("server closed"); }
private void CheckTransport() { var transportState = _transport.State; if (transportState == TcpTransportState.Closed) { throw new RpcException("SimpleRpcClient CheckTransport failed,connection has been closed"); } if (transportState == TcpTransportState.Uninit) { try { _transport.Init(); } catch (Exception ex) { try { _transport.Close(); } catch { } LogAgent.Warn("close network in SimpleRpcClient CheckTransport,transport init error", ex); throw; } } }
public void Close() { var originalClient = Interlocked.Exchange(ref _client, null); if (originalClient == null) { return; } if (originalClient.TransportState == TcpTransportState.Closed) { return; } var cacheResult = SimpleRpcClientPoolRoot.Enpool(originalClient); if (cacheResult == false) { try { originalClient.Dispose(); } catch { LogAgent.Warn("SimpleRpcClient Dispose error"); } } }
/// <summary> /// 删除 /// </summary> /// <param name="id"></param> /// <returns></returns> public int Delete(int id) { var type = typeof(TInterface); CounterToken counterToken = LogAgent.StartCounter(); var tablename = PropertiesHelper.Instance().GetTableName(type); if (string.IsNullOrEmpty(tablename)) { return(-1); } var sbColumnList = new List <string>(); var WhereList = new List <string>(); var ParaList = new List <DbParameter>(); var KeyProperties = PropertiesHelper.Instance().GetKeyProperties(type); foreach (var item in KeyProperties) { WhereList.Add(string.Format("{0}=@{0}", item.Name)); ParaList.Add(DbFactory.Instance().CreateDataParameter(string.Format("@{0}", item.Name), id)); } var sSQL = string.Format("Delete from {0} WHERE {1};", tablename, string.Join("AND", WhereList.ToArray())); LogAgent.StopCounterAndLog(counterToken, "[CreateSQL]-Delete:"); return(RepositoryHelper.ExecuteNonQuery(CommandType.Text, sSQL, ParaList.ToArray())); }
public void Close() { if (_client == null) { return; } var oldValue = Interlocked.Exchange(ref _client, null); if (oldValue == null) { return; } var cacheResult = SimpleRpcClientPoolRoot.ReturnItem(oldValue); if (cacheResult == false) { try { oldValue.Dispose(); } catch { LogAgent.Error("SimpleRpcCLient Dispose error"); } } }
protected override IEnumerable <TInputMsg> DecorateInputMessages(IEnumerable <TInputMsg> inputMsgs) { var e = inputMsgs.GetEnumerator(); while (true) { if (!e.MoveNext()) { yield break; } var msg = e.Current; Interlocked.Increment(ref m_NumMessagesProcessed); if (msg.IsBroken) { LogAgent.LogTrace(TaskType, Name, "Broken message propagates through network. Node: {0}, Message: {1}", Name, msg.Title); } else { LogAgent.LogTrace(TaskType, Name, "Processing: {0}", msg.Title); } yield return(msg); } }
protected override IEnumerable <TOutputMsg> ProcessInner(IEnumerable <TInputMsg> inputMsgs, out bool hasErrors) { TOutputMsg errorResult = default(TOutputMsg); try { return(base.ProcessInner(inputMsgs, out hasErrors)); } catch (DataflowNetworkUnrecoverableErrorException ex) { LogAgent.LogFatal(TaskType, InnerTask.Name, ex); //Now cancel the network Network.CancelNetwork(); errorResult = CreateErrorOutputMessage(ex); } catch (DataflowNetworkRecoverableErrorException ex) { LogAgent.LogUnknown(TaskType, InnerTask.Name, ex); errorResult = CreateErrorOutputMessage(ex); } catch (Exception ex) { errorResult = CreateErrorOutputMessage(ex); } hasErrors = true; return(new[] { errorResult }); }
/// <summary> /// 检查时间 /// </summary> /// <param name="TimeSpan"></param> /// <param name="response"></param> /// <returns></returns> public JsonResponse CheckLocalServerTime(long timeSpan, JsonResponse response) { if (!(response.data is Dictionary <string, object>)) { LogAgent.Info("CheckLocalServerTime:" + JsonConvert.SerializeObject(response)); return(response); } Dictionary <string, object> Payload = response.data as Dictionary <string, object>; if (Payload.ContainsKey("exp")) { long exp = Convert.ToInt64(Payload["exp"]); if (timeSpan < exp) { response.code = JsonResponse.SuccessCode; response.data = Payload; response.msg = "校准成功"; return(response); } else { response.code = (int)ErrorCodeEnums.TokenExpired; response.msg = ErrorCodeEnums.TokenExpired.GetEnumDescription(); LogAgent.Info(String.Format("注册码已过期:localExp:{0},ServerExp:{1}", exp, timeSpan)); if (File.Exists(this.LicensePath)) { File.Delete(this.LicensePath); LogAgent.Info("CheckAuthorize:删除文件" + this.LicensePath + " " + response.msg); } } } return(response); }
protected override IEnumerable <TOutputMsg> DecorateOutputMessages(IEnumerable <TOutputMsg> outputMsgs) { if (outputMsgs == null) { yield break; } var e = outputMsgs.GetEnumerator(); while (true) { if (!e.MoveNext()) { yield break; } TOutputMsg outputMsg = e.Current; if (outputMsg.IsBroken) { Interlocked.Increment(ref m_NumBrokenMsgs); LogAgent.LogBrokenMessage(DataflowNetworkConstituent.Transformation, Name, outputMsg.Title, outputMsg); } else { LogAgent.LogTrace(DataflowNetworkConstituent.Transformation, Name, "Transformed: old: {0} new: {1}", outputMsg.Title, outputMsg.Title); } yield return(outputMsg); } }
public void Close() { if (_serverState == 0) { return; } if (_serverState == -1) { return; } var oldValue = Interlocked.Exchange(ref _serverState, -1); if (oldValue == -1) { return; } try { _server.Stop(); } catch { } LogAgent.Info("server closed"); }
/// <summary> /// 执行方法前先执行这 /// </summary> /// <param name="context"></param> public override void OnActionExecuting(ActionExecutingContext context) { base.OnActionExecuting(context); try { string Moudle = String.Format("接收[{0}-{1}]请求 {2}", MoudleName, MethodName, context.ActionDescriptor.DisplayName); string RequestAddress = String.Format("RequestAddress: {0}:{1}", context.HttpContext.Connection.RemoteIpAddress.ToString(), context.HttpContext.Connection.RemotePort.ToString()); string URL = String.Format("uri: {0}", context.HttpContext.Request.Path.Value.ToString()); string method = String.Format("method: {0}", context.HttpContext.Request.Method.ToString()); string contentType = String.Format("contentType: {0}", context.HttpContext.Request.ContentType == null ? "null" : context.HttpContext.Request.ContentType.ToString()); string parameter = String.Format("parameter: {0}", JsonConvert.SerializeObject(context.ActionArguments)); StringBuilder message = new StringBuilder(); message.AppendLine(Moudle); message.AppendLine(RequestAddress); message.AppendLine(URL); message.AppendLine(method); message.AppendLine(contentType); message.AppendLine(parameter); LogAgent.Info(message.ToString()); CounterToken counterToken = LogAgent.StartCounter(); context.ActionDescriptor.Properties.TryAdd("Action-" + context.HttpContext.TraceIdentifier, counterToken); } catch (Exception ex) { LogAgent.Error(ex.ToString()); } }
/// <summary> /// 移除任务 /// </summary> /// <param name="connectionTask"></param> /// <returns></returns> public virtual bool RemoveTask(ConnectionTask connectionTask) { bool result = this.taskDocker.RemoveTask(connectionTask); this.connectionDocker.SetCaseAsDead(connectionTask); LogAgent.Info(String.Format("处理超时任务:{0}", connectionTask.ToString())); return(result); }
public void SetErrCode(string err) { LogAgent.Log(err); if (errAction != null) { errAction(err); } }
///// <summary> /// 处理数据 /// </summary> /// <param name="receiveState"></param> private void ReceiveCallback(IAsyncResult ar) { var receiveState = (NetworkState)ar.AsyncState; try { var received = ListenerSocket.EndReceiveFrom(ar, ref RemoteEndPoint); if (received == 0) { return; } var remoteAddress = (IPEndPoint)RemoteEndPoint; receiveState.RemoteHost = remoteAddress.ToNode(ReactorType.Udp); INode node = receiveState.RemoteHost; if (SocketMap.ContainsKey(receiveState.RemoteHost.nodeConfig.ToString())) { var connection = SocketMap[receiveState.RemoteHost.nodeConfig.ToString()]; node = connection.RemoteHost; } else { RefactorRequestChannel requestChannel = new RefactorProxyRequestChannel(this, node, "none"); SocketMap.Add(node.nodeConfig.ToString(), requestChannel); } receiveState.Buffer.WriteBytes(receiveState.RawBuffer, 0, received); Decoder.Decode(ConnectionAdapter, receiveState.Buffer, out List <IByteBuf> decoded); foreach (var message in decoded) { var networkData = NetworkData.Create(receiveState.RemoteHost, message); LogAgent.Info(String.Format("Socket收到数据-->>{0}", this.Encoder.ByteEncode(networkData.Buffer))); if (ConnectionAdapter is ReactorConnectionAdapter) { ((ReactorConnectionAdapter)ConnectionAdapter).networkDataDocker.AddNetworkData(networkData); ((EventWaitHandle)((ReactorConnectionAdapter)ConnectionAdapter).protocolEvents[(int)ProtocolEvents.PortReceivedData]).Set(); } } //清除数据继续接收 receiveState.RawBuffer = new byte[receiveState.RawBuffer.Length]; ListenerSocket.BeginReceiveFrom(receiveState.RawBuffer, 0, receiveState.RawBuffer.Length, SocketFlags.None, ref RemoteEndPoint, ReceiveCallback, receiveState); } catch //node disconnected { if (SocketMap.ContainsKey(receiveState.RemoteHost.nodeConfig.ToString())) { var connection = SocketMap[receiveState.RemoteHost.nodeConfig.ToString()]; CloseConnection(connection); } } }
/// <summary> /// 程序启动时,记录目录 /// </summary> /// <param name="env"></param> public static void LogWhenStart(IHostingEnvironment env) { StringBuilder sb = new StringBuilder(); sb.AppendLine("程序启动"); sb.AppendLine("ContentRootPath:" + env.ContentRootPath); sb.AppendLine("WebRootPath:" + env.WebRootPath); sb.AppendLine("IsDevelopment:" + env.IsDevelopment()); LogAgent.Write(LogLevel.Info, sb.ToString()); }
public static void RegisterProtocol(int protocol, Action <PackageResponse> reponse) { string name = "ProtocolMgr====" + protocol; Common.EventMgr.EventSystemMgr.RegisteredEvent(name, (na, objs) => { LogAgent.Log("收到协议!协议Id = " + protocol + "\r\n"); reponse((PackageResponse)objs[0]); }); }
protected override ErrorLogModel ThrowRequestID(HttpContext context, Exception ex) { int siteId = 0; int userId = 0; ErrorLogModel model = new ErrorLogModel(ex, siteId, userId, context); // 存入数据库 & 发送通知 LogAgent.Instance().SaveLog(model); return(model); }