/// <summary> /// send upd data to server /// </summary> /// <param name="bytes"></param> public void SendUdpData(byte[] bytes) { if (!BytesToSend.TryAdd(bytes)) { AutoLogger.LogText("cannot add udp block"); } }
private void Connect() { string comPort = _userSettings.Settings.ComPortSettings.ComPort; bool fastLogging = _userSettings.Settings.AutoLogSettings.FastLogging; int linesPerSecond = _userSettings.Settings.AutoLogSettings.LinesPerSecond; if (_utecConn == null || _utecConn.IsOpen == false) { try { _utecConn.OpenConnection(comPort, fastLogging, linesPerSecond, false); _logger = new AutoLogger(_userSettings.Settings.AutoLogSettings, _userSettings.Settings.GeneralSettings.LogOutputDirectory); this.ConnectBtnText = DISCONNECT; } catch (Exception ex) { _utecConn.CloseConnnection(); this.ConnectBtnText = CONNECT; this.OnShowError(ex, "Error establishing connection."); } } else { _utecConn.CloseConnnection(); this.ConnectBtnText = CONNECT; } }
/// <summary> /// Run action on thread /// </summary> /// <param name="action">your action</param> /// <param name="onException"></param> public static void Run(Action action, Action <Exception> onException = null) { #if (NET35 || NET40) ThreadPool.QueueUserWorkItem(RunAction, null); void RunAction(object state) #else System.Threading.Tasks.Task.Run(new Action(RunAction)); void RunAction() #endif { try { action(); } catch (Exception ex) { try { onException?.Invoke(ex); AutoLogger.LogError(ex, "AsyncActions Run"); OnActionException?.Invoke(ex); } catch (Exception ex2) { AutoLogger.LogError(ex2, "AsyncActions Run 2"); } } } }
/// <summary> /// close and dispose connector /// </summary> public void Dispose() { try { AutoLogger.LogText("Disposing Client"); IsConnected = false; IsDisposed = true; foreach (var item in ConnectorExtension.WaitedMethodsForResponse) { item.Value.Key.Set(); } if (_client != null) #if (NETSTANDARD1_6 || NETCOREAPP1_1) { _client.Dispose(); } #else { _client.Close(); } #endif OnDisconnected?.Invoke(); #if (NET35) getServiceDetailEvent?.Close(); #else getServiceDetailEvent?.Dispose(); #endif } catch (Exception ex) { AutoLogger.LogError(ex, "ConnectorBase Dispose"); } }
public static Thread StartNew(Action action, Action <Exception> onException = null) { Thread thread = new Thread(() => { try { action(); } catch (Exception ex) { try { onException?.Invoke(ex); AutoLogger.LogError(ex, "AsyncActions Run"); OnActionException?.Invoke(ex); } catch (Exception ex2) { AutoLogger.LogError(ex2, "AsyncActions Run 2"); } } }); thread.IsBackground = true; thread.Start(); return(thread); }
/// <summary> /// read data from stream /// </summary> /// <param name="stream">your stream to read a block</param> /// <param name="compress">compress mode</param> /// <returns>return a block byte array</returns> public static byte[] ReadBlockToEnd(NetworkStream stream, CompressMode compress, uint maximum, bool isWebSocket) { if (isWebSocket) { ulong size = 0; var bytes = GetLengthOfWebSocket(stream, ref size); var newBytes = ReadBlockSize(stream, size); List <byte> b = new List <byte>(); b.AddRange(bytes); b.AddRange(newBytes); var decode = DecodeMessage(b.ToArray()); if (decode == null || decode.Length == 0) { AutoLogger.LogText($"decode zero size: {size} bytes: {ByteArrayToText(bytes.ToArray())} newBytes:{ByteArrayToText(newBytes)} decode: {ByteArrayToText(decode)}"); } return(decode); } else { //first 4 bytes are size of block var dataLenByte = ReadBlockSize(stream, 4); //convert bytes to int int dataLength = BitConverter.ToInt32(dataLenByte, 0); if (dataLength > maximum) { throw new Exception("dataLength is upper than maximum :" + dataLength + " " + isWebSocket); } //else // AutoLogger.LogText("size: " + dataLength); //read a block var dataBytes = ReadBlockSize(stream, (ulong)dataLength); return(dataBytes); } }
public void Dispose() { if (Stream is NetworkStream) { try { #if (NETSTANDARD1_6) var property = typeof(NetworkStream).GetTypeInfo().GetProperty("Socket", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static); #else var property = typeof(NetworkStream).GetProperty("Socket", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static); #endif var socket = (Socket)property.GetValue(((NetworkStream)Stream), null); #if (NET35) socket.Close(); #else socket.Dispose(); #endif } catch (Exception ex) { AutoLogger.LogError(ex, "StreamInfo Dispose"); } } Stream.Dispose(); }
public static void HandleDeserializationError(object sender, ErrorEventArgs errorArgs) { if (errorArgs != null && errorArgs.ErrorContext != null && errorArgs.ErrorContext.Error != null && errorArgs.ErrorContext.Error.GetType() == typeof(JsonSerializationException)) { AutoLogger.LogError(errorArgs.ErrorContext.Error, $"HandleDeserializationError :{(errorArgs.ErrorContext.OriginalObject == null ? "null" : errorArgs.ErrorContext.OriginalObject.GetType().FullName)} member: {errorArgs.ErrorContext.Member} path: {errorArgs.ErrorContext.Path}"); } else { if (errorArgs != null) { if (errorArgs.ErrorContext != null) { if (errorArgs.ErrorContext.Error != null) { AutoLogger.LogError(errorArgs.ErrorContext.Error, $"HandleDeserializationError2 :{(errorArgs.ErrorContext.OriginalObject == null ? "null" : errorArgs.ErrorContext.OriginalObject.GetType().FullName)} member: {errorArgs.ErrorContext.Member} path: {errorArgs.ErrorContext.Path}"); } else { AutoLogger.LogText("json error ErrorContext.Error null"); AutoLogger.LogText("json error path: " + errorArgs.ErrorContext.Path); } } else { AutoLogger.LogText("json error ErrorContext null"); } } else { AutoLogger.LogText("json error null"); } } errorArgs.ErrorContext.Handled = true; }
private void StartReadingData() #endif { Task.Factory.StartNew(() => { try { #if (PORTABLE) socket.ConnectAsync(_ipAddress, _port).Wait(); #else socket.Connect(iPEndPoint); #endif #if (PORTABLE) ManualResetEvent ev = new ManualResetEvent(true); socket.MessageReceived += (s, e) => { OnReceivedData?.Invoke(e.ByteData); }; ev.WaitOne(); #else while (!IsDisposed) { byte[] bytes = new byte[BufferSize]; int readCount = socket.Receive(bytes); OnReceivedData?.Invoke(bytes.ToList().GetRange(0, readCount).ToArray()); } #endif } catch (Exception ex) { AutoLogger.LogError(ex, "UdpConnectorBase StartReadingData"); } }); }
//public object SendData(this ClientDuplex client, string className, string callerName, params object[] args) //{ // MethodCallInfo callInfo = new MethodCallInfo(); // callInfo.FullClassName = className; // callInfo.MethodName = callerName; // foreach (var item in args) // { // callInfo.Parameters.Add(new Shared.Models.ParameterInfo() { Type = item.GetType().FullName, Value = JsonConvert.SerializeObject(item) }); // } // SendData(callInfo); // return null; //} /// <summary> /// send data to call server method /// </summary> /// <param name="Data"></param> internal void SendData(MethodCallInfo Data) { AsyncActions.Run(() => { try { var json = JsonConvert.SerializeObject(Data); List <byte> bytes = new List <byte> { (byte)DataType.CallMethod, (byte)CompressMode.None }; var jsonBytes = Encoding.UTF8.GetBytes(json); if (SecuritySettings != null) { jsonBytes = EncryptBytes(jsonBytes); } byte[] dataLen = BitConverter.GetBytes(jsonBytes.Length); bytes.AddRange(dataLen); bytes.AddRange(jsonBytes); if (bytes.Count > ProviderSetting.MaximumSendDataBlock) { throw new Exception("SendData data length is upper than MaximumSendDataBlock"); } GoStreamWriter.WriteToStream(_client.GetStream(), bytes.ToArray(), IsWebSocket); } catch (Exception ex) { AutoLogger.LogError(ex, "ConnectorBase SendData"); } }); }
protected void Application_Start() { AutoLogger.Info("[Application_Start]:[begin]"); AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AutoLogger.Info("[Application_Start]:[end]"); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Application_Start(object sender, EventArgs e) { AutoLogger.Info("[Application_Start]:[begin]"); // 在应用程序启动时运行的代码 AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // 数据库配置 DbConfiguration.SetConfiguration(new MySqlEFConfiguration()); AutoLogger.Info("[Application_Start]:[end]"); }
static object FindClientCallback <T>(ServerBase serverBase, ClientInfo client, Type serviceType, string attribName) { var find = serverBase.FindClientCallbackByType(client, serviceType); if (find == null) { GetClientCallbackOfClientContext <T>(serverBase, client); find = serverBase.FindClientCallbackByType(client, serviceType); if (find == null) { AutoLogger.LogText($"GetAllClientCallbackListOfClientContext service not found : {serviceType.FullName} : name: {attribName} session: {client.SessionId}", true); } } return(find); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { try { if (reader.Value == null) { return(default(DateTime)); } return(((DateTime)reader.Value).ToLocalTime()); } catch (Exception ex) { AutoLogger.LogError(ex, "ToLocalDateTimeConvertor ReadJson"); AutoLogger.LogText(reader.Value == null ? "null" : reader.Value.ToString()); } return(default(DateTime)); }
internal override void ReconnectToUdp(MethodCallInfo callInfo) { AutoLogger.LogText("ReconnectToUdp"); MethodCallbackInfo callback = new MethodCallbackInfo(); callback.Guid = callInfo.Guid; try { SendUdpData(new byte[] { 0 }); } catch (Exception ex) { AutoLogger.LogError(ex, "UdpConnectorBase ReconnectToUdp"); callback.IsException = true; callback.Data = JsonConvert.SerializeObject(ex.ToString()); } SendCallbackData(callback); }
/// <summary> /// run your code on ui thread /// </summary> /// <param name="action"></param> public static void RunOnUI(Action action) { if (UIThread == null) { throw new Exception("UI thread not initialized please call AsyncActions.InitializeUIThread in your ui thread to initialize"); } UIThread.Post((state) => { try { action(); } catch (Exception ex) { AutoLogger.LogError(ex, "AsyncActions RunOnUI"); } }, null); }
///// <summary> ///// ///// </summary> ///// <param name="modelBuilder"></param> //protected override void OnModelCreating(DbModelBuilder modelBuilder) //{ // // 去除code first的检测 // // modelBuilder.HasDefaultSchema("project_manager"); // // __migrationhistory // // modelBuilder.Conventions.Remove<IncludeMetadataConvention>(); // Database.SetInitializer<BaseDbContext>(null); // base.OnModelCreating(modelBuilder); // // modelBuilder.Entity<AppInfo>().MapToStoredProcedures(); // // modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); // // modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>(); //} /// <summary> /// 检查数据 /// </summary> private void CheckEntity() { AutoLogger.Trace(string.Format("-- CheckEntity BEGIN --")); IEnumerable <DbEntityEntry> values = this.ChangeTracker.Entries(); foreach (DbEntityEntry value in values) { // TODO 日志 // AutoLogger.Info(string.Format("[{0}]:[CheckEntity BEGIN]", entityType.Name)); if (value.Entity is BaseModel) { BaseModel entity = value.Entity as BaseModel; if (HttpContext.Current.User.Identity.IsAuthenticated) { LoginUserPrincipal user = HttpContext.Current.User as LoginUserPrincipal; // 自动修改插入数据的插入用户和插入日期 if (value.State == EntityState.Added) { entity.InsertDate = DateTime.Now; entity.InsertUser = user.ID; entity.UpdateDate = DateTime.Now; entity.UpdateUser = user.ID; } // 自动修改更新数据的更新用户和更新日期 if (value.State == EntityState.Modified) { entity.UpdateDate = DateTime.Now; entity.UpdateUser = user.ID; } if (value.State == EntityState.Deleted || value.State == EntityState.Modified) { DateTime lastUpdateDate = (DateTime)value.GetDatabaseValues()["UpdateDate"]; if (entity.UpdateDate != lastUpdateDate) { throw new Exception("更新数据的排它日期错误"); } } } } // TODO 日志 // AutoLogger.Info(string.Format("[{0}]:[CheckEntity END]", entityType.Name)); } AutoLogger.Trace(string.Format("-- CheckEntity END --")); }
//start to reading data from server void StartReadingData() { Task.Factory.StartNew(() => { try { socket.Connect(iPEndPoint); while (!IsDisposed) { byte[] bytes = new byte[BufferSize]; var readCount = socket.Receive(bytes); OnReceivedData?.Invoke(bytes.ToList().GetRange(0, readCount).ToArray()); } } catch (Exception ex) { AutoLogger.LogError(ex, "UdpConnectorBase StartReadingData"); } }); }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { try { if (value == null) { writer.WriteValue(default(DateTime).ToLocalTime()); } else { var dt = ((DateTime)value).ToLocalTime(); writer.WriteValue(dt); } } catch (Exception ex) { AutoLogger.LogError(ex, "ToLocalDateTimeConvertor WriteJson"); AutoLogger.LogText(value == null ? "null" : value.ToString()); } }
/// <summary> /// Run action on thread /// </summary> /// <param name="action">your action</param> public static void Run(Action action, Action <Exception> onException = null) { Thread thread = new Thread(() => { try { action(); } catch (Exception ex) { onException?.Invoke(ex); AutoLogger.LogError(ex, "AsyncActions Run"); OnActionException?.Invoke(ex); } }) { IsBackground = false }; thread.Start(); }
/// <summary> /// call a method of client from server /// </summary> /// <param name="callInfo">method call data</param> internal void CallMethod(MethodCallInfo callInfo) { MethodCallbackInfo callback = new MethodCallbackInfo() { Guid = callInfo.Guid }; try { var service = Callbacks[callInfo.ServiceName].Value; var method = service.GetType().GetMethod(callInfo.MethodName, RuntimeTypeHelper.GetMethodTypes(service.GetType(), callInfo).ToArray()); if (method == null) { throw new Exception($"Method {callInfo.MethodName} from service {callInfo.ServiceName} not found! serviceType: {service.GetType().FullName}"); } List <object> parameters = new List <object>(); int index = 0; foreach (var item in method.GetParameters()) { parameters.Add(JsonConvert.DeserializeObject(callInfo.Parameters[index].Value, item.ParameterType)); index++; } if (method.ReturnType == typeof(void)) { method.Invoke(service, parameters.ToArray()); } else { var data = method.Invoke(service, parameters.ToArray()); callback.Data = data == null ? null : JsonConvert.SerializeObject(data); } } catch (Exception ex) { AutoLogger.LogError(ex, "ConnectorBase CallMethod"); callback.IsException = true; callback.Data = JsonConvert.SerializeObject(ex.ToString()); } SendCallbackData(callback); }
static ConnectorExtension() { #if (!Mobile) CSCodeInjection.InvokedClientMethodAction = (client, method, parameters) => { if (!(client is OperationCalls)) { AutoLogger.LogText($"cannot cast! {method.Name} params {parameters?.Length}"); } SendDataInvoke((OperationCalls)client, method.Name, parameters); }; CSCodeInjection.InvokedClientMethodFunction = (client, method, parameters) => { var data = SendData((OperationCalls)client, method.Name, "", parameters); if (data == null) { return(null); } return(data is StreamInfo ? data : JsonConvert.DeserializeObject(data.ToString(), method.ReturnType)); }; #endif }
private void Log(string methodName, RouteData routeData, IDictionary <string, object> actionParameters = null) { var controllerName = routeData.Values["controller"]; var actionName = routeData.Values["action"]; System.Text.StringBuilder parameters = new System.Text.StringBuilder(); if (actionParameters != null) { foreach (KeyValuePair <string, object> kvp in actionParameters) { if (parameters.Length > 0) { parameters.Append("&"); } parameters.Append(kvp.Key + "=" + kvp.Value); } parameters.Insert(0, "?"); } var message = String.Format("[Action Filter Log] | IP:[{4}] | controller:[{1}] action:[{2}] | [{0}] parameters:[{3}]", methodName, controllerName, actionName, parameters, GetIP()); // Debug.WriteLine(message, "Action Filter Log"); AutoLogger.Info(message); }
internal void DisposeClient(ClientInfo client, TcpClient tcpClient, string reason) { try { //Console.WriteLine($"Client disposed " + (client == null ? "null!" : client.ClientId) + " reason: " + reason); if (client == null) { if (tcpClient != null) { #if (NETSTANDARD1_6 || NETCOREAPP1_1) tcpClient.Dispose(); #else tcpClient.Close(); #endif } return; } Clients.Remove(client.ClientId); try { if (client.TcpClient != null) { #if (NETSTANDARD1_6 || NETCOREAPP1_1) client.TcpClient.Dispose(); #else client.TcpClient.Close(); #endif } } catch (Exception ex) { AutoLogger.LogError(ex, $"{client.IPAddress} {client.ClientId} CloseCllient"); } foreach (KeyValuePair <string, ConcurrentDictionary <string, object> > service in MultipleInstanceServices) { foreach (KeyValuePair <string, object> clientInfo in service.Value.Where(x => x.Key == client.ClientId)) { service.Value.Remove(clientInfo.Key); } } //ClientRemove(client); OperationContextBase.SavedSettings.Remove(client); client.OnDisconnected?.Invoke(); } catch (Exception ex) { Console.WriteLine("DisposeClient " + ex); AutoLogger.LogError(ex, "DisposeClientError"); } finally { try { OnClientDisconnectedAction?.Invoke(client); } catch (Exception ex) { } } }
/// <summary> /// write json for serialize object /// </summary> /// <param name="writer"></param> /// <param name="value"></param> /// <param name="serializer"></param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { try { if (SerializeHelper.GetTypeCodeOfObject(value.GetType()) != SerializeObjectType.Object) { writer.WriteValue(value); return; } var type = value.GetType(); #if (NETSTANDARD1_6 || NETCOREAPP1_1) if (type.GetTypeInfo().BaseType != null && type.Namespace == "System.Data.Entity.DynamicProxies") { type = type.GetTypeInfo().BaseType; } #else if (type.BaseType != null && type.Namespace == "System.Data.Entity.DynamicProxies") { type = type.BaseType; } #endif #if (NETSTANDARD1_6 || NETCOREAPP1_1) var implementICollection = (SkipDataExchangeAttribute)type.GetTypeInfo().GetCustomAttributes(typeof(SkipDataExchangeAttribute), true).FirstOrDefault(); #else var implementICollection = (SkipDataExchangeAttribute)type.GetCustomAttributes(typeof(SkipDataExchangeAttribute), true).FirstOrDefault(); #endif bool?canIgnore = implementICollection == null ? (bool?)null : implementICollection.CanIgnore(value, null, type, implementICollection); if (canIgnore.HasValue) { if (canIgnore.Value) { return; } } else if (implementICollection != null && (implementICollection.Mode == LimitExchangeType.Both || implementICollection.Mode == Mode)) { return; } bool isArray = typeof(IEnumerable).IsAssignableFrom(type) && !(value is string); bool isDictionary = typeof(IDictionary).IsAssignableFrom(type); if (isArray && !isDictionary) { writer.WriteStartArray(); } else { writer.WriteStartObject(); } if (isDictionary) { foreach (DictionaryEntry item in (IDictionary)value) { JToken jTokenKey = JToken.FromObject(item.Key); JToken jTokenValue = JToken.FromObject(item.Value); writer.WritePropertyName(item.Key.ToString()); if (jTokenValue.Type == JTokenType.Object || jTokenValue.Type == JTokenType.Array) { serializer.Serialize(writer, item.Value); } else { writer.WriteValue(item.Value); } } } else if (isArray) { foreach (var item in (IEnumerable)value) { if (item == null) { continue; } var itemType = item.GetType(); bool isPropertyArray = typeof(IEnumerable).IsAssignableFrom(itemType) && itemType != typeof(string); bool isPropertyDictionary = typeof(IDictionary).IsAssignableFrom(itemType); if (isPropertyArray || isPropertyDictionary) { serializer.Serialize(writer, item); } else { #if (NETSTANDARD1_6 || NETCOREAPP1_1) bool canWriteFast = itemType == typeof(string) || !(itemType.GetTypeInfo().IsClass || itemType.GetTypeInfo().IsInterface); #else bool canWriteFast = itemType == typeof(string) || !(itemType.IsClass || itemType.IsInterface); #endif if (canWriteFast) { writer.WriteValue(item); } else { serializer.Serialize(writer, item); } } } } else { WriteData(type, value, writer, serializer); } if (isArray && !isDictionary) { writer.WriteEndArray(); } else { writer.WriteEndObject(); } } catch (Exception ex) { AutoLogger.LogError(ex, "WriteJson"); } }
/// <summary> /// write data and convert to json for serialize /// </summary> /// <param name="baseType"></param> /// <param name="instance"></param> /// <param name="writer"></param> /// <param name="serializer"></param> void WriteData(Type baseType, object instance, JsonWriter writer, JsonSerializer serializer) { try { foreach (var property in baseType.GetProperties()) { if (property.CanRead) { var implementICollection = (SkipDataExchangeAttribute)property.GetCustomAttributes(typeof(SkipDataExchangeAttribute), true).FirstOrDefault(); var canIgnore = implementICollection == null ? (bool?)null : implementICollection.CanIgnore(instance, property, baseType, implementICollection); bool isIgnored = false; if (canIgnore.HasValue) { if (canIgnore.Value) { isIgnored = true; } } else if (implementICollection != null && (implementICollection.Mode == LimitExchangeType.Both || implementICollection.Mode == Mode)) { isIgnored = true; } if (!isIgnored) { if (ExchangerTypes != null) { var find = ExchangerTypes.FirstOrDefault(x => x.Type == baseType && (x.LimitationMode == LimitExchangeType.Both || x.LimitationMode == LimitExchangeType.OutgoingCall)); if (find != null) { if (find.CustomDataExchangerType == CustomDataExchangerType.Take) { if (find.Properties != null && !find.Properties.Contains(property.Name) && find.IsEnabled(Client, Server, property.Name, baseType)) { isIgnored = true; } } else { if (find.Properties != null && find.Properties.Contains(property.Name) && find.IsEnabled(Client, Server, property.Name, baseType)) { isIgnored = true; } } } } } if (!isIgnored) { bool isPropertyArray = typeof(IEnumerable).IsAssignableFrom(property.PropertyType) && property.PropertyType != typeof(string); bool isPropertyDictionary = typeof(IDictionary).IsAssignableFrom(property.PropertyType); if (isPropertyArray || isPropertyDictionary) { object propValue = null; try { propValue = property.GetValue(instance, null); } catch (Exception ex) { AutoLogger.LogError(ex, "WriteData 1"); } if (propValue != null) { try { writer.WritePropertyName(property.Name); serializer.Serialize(writer, propValue); } catch (Exception ex) { AutoLogger.LogError(ex, "WriteData 2"); } } } else { try { var value = property.GetValue(instance, null); writer.WritePropertyName(property.Name); serializer.Serialize(writer, value); } catch (Exception ex) { AutoLogger.LogError(ex, "WriteData 3"); } } } } } } catch (Exception ex) { AutoLogger.LogError(ex, "WriteData 4"); } }
private void StartEngine() { #if (PORTABLE) throw new NotSupportedException(); #else if (!isStop) { return; } isStop = false; _thread = Task.Factory.StartNew(() => { try { BaseLogInformation nextLog = null; while (!isStop) { if (Logs.TryPeek(out nextLog) && nextLog.CanWriteToFile) { if (isStop) { break; } if (Logs.TryDequeue(out nextLog)) { if (isStop) { break; } if (nextLog.IsIgnoreLogTextFile) { continue; } if (nextLog is CallMethodLogInformation) { WriteToFile((CallMethodLogInformation)nextLog); } else if (nextLog is HttpCallMethodLogInformation) { WriteToFile((HttpCallMethodLogInformation)nextLog); } else if (nextLog is CallClientMethodLogInformation) { WriteToFile((CallClientMethodLogInformation)nextLog); } else if (nextLog is StreamCallMethodLogInformation) { WriteToFile((StreamCallMethodLogInformation)nextLog); } } else { AutoLogger.LogText("WTF MethodCallsLogger StartEngine"); } } else { Thread.Sleep(1000); } } } catch (Exception ex) { AutoLogger.LogError(ex, "MethodCallsLogger StartEngine"); } isStop = true; }); #endif }
/// <summary> /// get current context callback /// </summary> /// <typeparam name="T">type of callback</typeparam> /// <param name="context">client context</param> /// <returns>list of callback context</returns> public static ClientContext <T> GetClientCallbackOfClientContext <T>(this OperationContext context) { #if (NETSTANDARD1_6 || NETCOREAPP1_1) if (typeof(T).GetTypeInfo().IsInterface) #else if (typeof(T).IsInterface) #endif { if (!context.ServerBase.Callbacks.ContainsKey(context.Client)) { context.ServerBase.RegisterCallbacksForClient(context.Client); if (!context.ServerBase.Callbacks.ContainsKey(context.Client)) { try { throw new Exception($"context client not exist! {context.Client.SessionId} {context.ServerBase.Callbacks.Count} {context.ServerBase.Services.Count} {DateTime.Now}"); } catch (Exception ex) { AutoLogger.LogError(ex, "GetClientCallbackOfClientContext"); } return(null); } else { var attribName1 = (typeof(T).GetCustomAttributes <ServiceContractAttribute>(true).FirstOrDefault()).Name; var serviceType1 = context.ServerBase.GetRegisteredCallbacksTypeByName(attribName1); var find1 = context.ServerBase.FindClientCallbackByType(context.Client, serviceType1); if (find1 == null) { try { throw new Exception($"context client not exist 2 ! {context.Client.SessionId} {context.ServerBase.Callbacks.Count} {context.ServerBase.Services.Count} {DateTime.Now}"); } catch (Exception ex) { AutoLogger.LogError(ex, "GetClientCallbackOfClientContext 2"); } return(null); } return(new ClientContext <T>(find1, context.Client)); } } #if (NETSTANDARD1_6 || NETCOREAPP1_1) var attribName = ((ServiceContractAttribute)typeof(T).GetTypeInfo().GetCustomAttributes(typeof(ServiceContractAttribute), true).FirstOrDefault()).Name; #else var attribName = ((ServiceContractAttribute)typeof(T).GetCustomAttributes(typeof(ServiceContractAttribute), true).FirstOrDefault()).Name; #endif var serviceType = context.ServerBase.GetRegisteredCallbacksTypeByName(attribName); var find = context.ServerBase.FindClientCallbackByType(context.Client, serviceType); if (find != null) { return(new ClientContext <T>(find, context.Client)); } var obj = CSCodeInjection.InstanceServerInterface <T>(serviceType, new List <Type>() { typeof(ServiceContractAttribute) }); //dynamic dobj = obj; if (CSCodeInjection.InvokedServerMethodAction == null) { ServerExtension.Init(); } var field = serviceType #if (NETSTANDARD1_6 || NETCOREAPP1_1) .GetTypeInfo() #endif .GetProperty("InvokedServerMethodAction"); field.SetValue(obj, CSCodeInjection.InvokedServerMethodAction, null); var field2 = serviceType #if (NETSTANDARD1_6 || NETCOREAPP1_1) .GetTypeInfo() #endif .GetProperty("InvokedServerMethodFunction"); field2.SetValue(obj, CSCodeInjection.InvokedServerMethodFunction, null); //dobj.InvokedServerMethodAction = CSCodeInjection.InvokedServerMethodAction; //dobj.InvokedServerMethodFunction = CSCodeInjection.InvokedServerMethodFunction; var op = obj as OperationCalls; op.ServerBase = context.ServerBase; op.CurrentClient = context.Client; //context.ServerBase.RegisteredCallbacksTypes.ContainsKey(attribute.Name); context.ServerBase.Callbacks[context.Client].Add(obj); if (!(obj is OperationCalls)) { Shared.Log.AutoLogger.LogText("is not OprationCalls: " + obj.ToString(), true); } return(new ClientContext <T>(obj, context.Client)); } else { Shared.Log.AutoLogger.LogText("is not interface: " + typeof(T).ToString(), true); return(new ClientContext <T>((T)context.ServerBase.FindClientCallbackByType(context.Client, typeof(T)), context.Client)); } }
/// <summary> /// 记录数据库日志 /// </summary> private void RecordDbChangeLog() { AutoLogger.Trace(string.Format("-- RecordDbChangeLog BEGIN --")); // 比较改变的项目,保存修改日志 // 所有改变的实体 IEnumerable <DbEntityEntry> values = this.ChangeTracker.Entries(); foreach (DbEntityEntry value in values) { // 没有改变的实体不做记录 if (value.State == EntityState.Detached || value.State == EntityState.Unchanged) { continue; } // 获取表名和字段名 Type entityType = value.Entity.GetType(); TableAttribute tableAttribute = (TableAttribute)Attribute.GetCustomAttribute(entityType, typeof(TableAttribute)); AutoLogger.Info(string.Format("[{0}]:[修改记录 BEGIN]", entityType.Name)); DbPropertyValues dbPropertyValues = value.CurrentValues; if (value.State == EntityState.Added) { // 新加的数据,数据库中没有元数据 } else { // 修改或删除数据,数据库中有元数据 dbPropertyValues = value.GetDatabaseValues(); } foreach (string propertyName in dbPropertyValues.PropertyNames) { // 获取表名和字段名 PropertyInfo propertyInfo = entityType.GetProperty(propertyName); ColumnAttribute columnAttribute = (ColumnAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(ColumnAttribute)); // 获取当前数据的主键 // 获取变更状态 ChangedEntity changedEntity = new ChangedEntity(); changedEntity.State = value.State; changedEntity.TableName = tableAttribute.Name; changedEntity.ColumnName = columnAttribute.Name; changedEntity.CurrentValue = value.CurrentValues[propertyName]; if (value.State != EntityState.Added) { // 添加数据时,元数据为空 // 非添加数据时,才有元数据 changedEntity.DatabaseValue = dbPropertyValues[propertyName]; changedEntity.OriginalValue = value.OriginalValues[propertyName]; } AutoLogger.Trace(changedEntity.ToString()); } AutoLogger.Info(string.Format("[{0}]:[修改记录 END]", entityType.Name)); } AutoLogger.Trace(string.Format("-- RecordDbChangeLog END --")); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Application_Error(Object sender, EventArgs e) { Exception lastError = Server.GetLastError(); AutoLogger.Error(lastError); }