Exemple #1
0
        protected void PostInvoke(object[] inputs, object returnedValue, object[] outputs, Exception exception)
        {
            try
            {
#if DEBUG
                if (exception == null)
                {
                    Console.WriteLine("End invoke:" + OperationContext.Current.GetCurrentOperationDescription().SyncMethod.Name);
                }
                Console.WriteLine("ElapsedMilliseconds:" + sw.ElapsedMilliseconds);
#endif
                var results = new List <string>();
                results.Add(returnedValue.ToString());
                results.AddRange(outputs.Select(o => o.ToString()).ToList());

                var logSetting = WcfSettingManager.CurrentServerSetting(OperationContext.Current.GetCurrentServiceDescription().ServiceType).WcfLogSetting;
                if (logSetting.Enabled && logSetting.InvokeInfoSetting.Enabled)
                {
                    var log = WcfLogProvider.GetServerInvokeInfo(
                        "OperationInvoker.PostInvoke",
                        sw.ElapsedMilliseconds,
                        exception == null ? true : false,
                        OperationContext.Current.GetCurrentOperationDescription().SyncMethod.Name,
                        ServerApplicationContext.Current,
                        inputs.Select(i => i.ToString()).ToList(), results);
                    WcfServiceLocator.GetLogService().LogWithoutException(log);
                }
            }
            catch (Exception ex)
            {
                LocalLogService.Log(ex.ToString());
            }
        }
Exemple #2
0
 static WcfServiceLocator()
 {
     logServiceCheckTimer = new Timer(o =>
     {
         try
         {
             using (var remoteLog = WcfServiceClientFactory.CreateServiceClient <IWcfLogService>())
             {
                 remoteLog.Channel.Health();
             }
             if (logServiceCheckTimer != null)
             {
                 logServiceCheckTimer.Change(NORMAL_CHECK_SPAN, NORMAL_CHECK_SPAN);
             }
             enableRemoteLogService = true;
         }
         catch (Exception ex)
         {
             LocalLogService.Log(ex.ToString());
             LocalLogService.Log("Remote log service is unavailable, use local log service replaced...");
             enableRemoteLogService = false;
             if (logServiceCheckTimer != null)
             {
                 logServiceCheckTimer.Change(EXCEPTION_CHECK_SPAN, EXCEPTION_CHECK_SPAN);
             }
         }
     }, null, NORMAL_CHECK_SPAN, NORMAL_CHECK_SPAN);
 }
Exemple #3
0
 public override IMessage Invoke(IMessage msg)
 {
     using (var client = WcfServiceClientFactory.CreateServiceClient <IWcfLogService>())
     {
         var channel = client.Channel;
         IMethodCallMessage   methodCall   = (IMethodCallMessage)msg;
         IMethodReturnMessage methodReturn = null;
         object[]             copiedArgs   = Array.CreateInstance(typeof(object), methodCall.Args.Length) as object[];
         methodCall.Args.CopyTo(copiedArgs, 0);
         try
         {
             object returnValue = methodCall.MethodBase.Invoke(channel, copiedArgs);
             methodReturn = new ReturnMessage(returnValue,
                                              copiedArgs,
                                              copiedArgs.Length,
                                              methodCall.LogicalCallContext,
                                              methodCall);
         }
         catch (Exception ex)
         {
             if (ex.InnerException != null)
             {
                 LocalLogService.Log(ex.InnerException.ToString());
                 methodReturn = new ReturnMessage(ex.InnerException, methodCall);
             }
             else
             {
                 LocalLogService.Log(ex.ToString());
                 methodReturn = new ReturnMessage(ex, methodCall);
             }
         }
         return(methodReturn);
     }
 }
Exemple #4
0
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            try
            {
                var clientContext = new ClientApplicationContext();
                clientContext.ServerMachineName = WcfLogProvider.MachineName;
                clientContext.RequestIdentity   = ServerApplicationContext.Current.RequestIdentity;
                clientContext.ServerExceptionID = ServerApplicationContext.Current.ServerExceptionID ?? "";

                var serviceType = OperationContext.Current.GetCurrentServiceDescription().ServiceType;
                if (!serviceVersionCache.ContainsKey(serviceType.FullName))
                {
                    lock (locker)
                    {
                        if (!serviceVersionCache.ContainsKey(serviceType.FullName))
                        {
                            serviceVersionCache.Add(serviceType.FullName, serviceType.Assembly.GetName().Version.ToString());
                        }
                    }
                }
                clientContext.ServerVersion = serviceVersionCache[serviceType.FullName];

                reply.SetApplicationContext(clientContext);

#if DEBUG
                var message = reply.ToString();
                Console.WriteLine("Server send message:" + message);
#endif

                var setting = WcfSettingManager.CurrentServerSetting(OperationContext.Current.GetCurrentServiceDescription().ServiceType);

                var securitySetting = setting.WcfSecuritySetting;
                if (securitySetting.PasswordCheck.Enable)
                {
                    if (securitySetting.PasswordCheck.Direction == OperationDirection.Both || securitySetting.PasswordCheck.Direction == OperationDirection.Reply)
                    {
                        clientContext.Password = securitySetting.PasswordCheck.Password;
                    }
                }

                var logSetting = setting.WcfLogSetting;
                if (logSetting.Enabled && logSetting.MessageInfoSetting.Enabled)
                {
                    var direct = logSetting.MessageInfoSetting.MessageDirection;
                    if (direct == MessageDirection.Both ||
                        direct == MessageDirection.Send)
                    {
                        var log = WcfLogProvider.GetServerMessageInfo(
                            "ServerMessageInspector.BeforeSendReply",
                            MessageDirection.Send,
                            reply.ToString());
                        WcfServiceLocator.GetLogService().LogWithoutException(log);
                    }
                }
            }
            catch (Exception ex)
            {
                LocalLogService.Log(ex.ToString());
            }
        }
Exemple #5
0
 internal static void LogWithoutException(this IWcfLogService logService, AbstractLogInfo log)
 {
     try
     {
         logService.Log(log);
     }
     catch (Exception ex)
     {
         LocalLogService.Log(ex.ToString());
     }
 }
Exemple #6
0
        private static void CreateRedisSubThreadForServer()
        {
            redisSubThreadForServer = new Thread(() =>
            {
                try
                {
                    using (var subscription = redisClientManager.GetClient().CreateSubscription())
                    {
                        subscription.OnSubscribe = channel =>
                        {
                            LocalLogService.Log("CreateClientRedisSubThread OnSubscribe");
                        };
                        subscription.OnMessage = (channel, msg) =>
                        {
                            try
                            {
                                if (msg == HEART_MESSAGE)
                                {
                                    lastCheckMsgTime = DateTime.Now;
                                }
                                else
                                {
                                    if (ServerManager.TryRestartService(msg))
                                    {
                                        LocalLogService.Log("Got redis message, server restarted, type : " + msg);
                                    }
                                    else
                                    {
                                        LocalLogService.Log("Got redis message, server type is not match, type : " + msg);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                LocalLogService.Log(ex.ToString());
                            }
                        };

                        subscription.SubscribeToChannels(REDIS_MESSAGE_SERVICE_CHANNEL);
                    }
                }
                catch (Exception ex)
                {
                    LocalLogService.Log(ex.ToString());
                }
            });

            redisSubThreadForServer.Name         = "redisSubThreadForServer";
            redisSubThreadForServer.IsBackground = true;
            redisSubThreadForServer.Start();
        }
Exemple #7
0
        private static void CreateRedisSubThreadForClient()
        {
            redisSubThreadForClient = new Thread(() =>
            {
                try
                {
                    using (var subscription = redisClientManager.GetClient().CreateSubscription())
                    {
                        subscription.OnSubscribe = channel =>
                        {
                            LocalLogService.Log("CreateClientRedisSubThread OnSubscribe");
                        };
                        subscription.OnMessage = (channel, msg) =>
                        {
                            try
                            {
                                if (msg == HEART_MESSAGE)
                                {
                                    lastCheckMsgTime = DateTime.Now;
                                }
                                else
                                {
                                    if (WcfServiceClientFactory.TryRemoteChannelFactoryFromCache(msg))
                                    {
                                        LocalLogService.Log("Got redis message, client cache removed, type : " + msg);
                                    }
                                    else
                                    {
                                        LocalLogService.Log("Got redis message, failed to find type client cache, type : " + msg);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                LocalLogService.Log(ex.ToString());
                            }
                        };

                        subscription.SubscribeToChannels(REDIS_MESSAGE_CLIENT_CHANNEL);
                    }
                }
                catch (Exception ex)
                {
                    LocalLogService.Log(ex.ToString());
                }
            });

            redisSubThreadForClient.Name         = "redisSubThreadForClient";
            redisSubThreadForClient.IsBackground = true;
            redisSubThreadForClient.Start();
        }
Exemple #8
0
 public static void StartService(Type serviceType)
 {
     try
     {
         host = WcfServiceHostFactory.CreateServiceHost(serviceType);
         host.Open();
         ConfigUpdateManager.InitServer();
     }
     catch (Exception ex)
     {
         LocalLogService.Log(ex.ToString());
         throw;
     }
 }
Exemple #9
0
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
#if DEBUG
            var message = reply.ToString();
            Console.WriteLine("Client got message:" + message);
#endif
            ClientApplicationContext.Current = reply.GetApplicationContext <ClientApplicationContext>();

            try
            {
                var setting    = WcfSettingManager.CurrentClientSetting((correlationState as Type));
                var logSetting = setting.WcfLogSetting;
                if (logSetting.Enabled && logSetting.MessageInfoSetting.Enabled)
                {
                    var direct = logSetting.MessageInfoSetting.MessageDirection;
                    if (direct == MessageDirection.Both || direct == MessageDirection.Receive)
                    {
                        var log = WcfLogProvider.GetClientMessageInfo(
                            (correlationState as Type).FullName,
                            ClientApplicationContext.Current.RequestIdentity,
                            "ClientMessageInspector.AfterReceiveReply",
                            MessageDirection.Receive,
                            reply.ToString());

                        WcfServiceLocator.GetLogService().LogWithoutException(log);
                    }
                }

                var securitySetting = setting.WcfSecuritySetting;
                if (securitySetting.PasswordCheck.Enable)
                {
                    if (securitySetting.PasswordCheck.Direction == OperationDirection.Both || securitySetting.PasswordCheck.Direction == OperationDirection.Reply)
                    {
                        if (ClientApplicationContext.Current.Password != securitySetting.PasswordCheck.Password)
                        {
                            throw new WcfSecurityException("PasswordCheck failed in reply!");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LocalLogService.Log(ex.ToString());
                if (ex is WcfSecurityException)
                {
                    throw;
                }
            }
        }
Exemple #10
0
 public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
 {
     try
     {
         var errorid = Guid.NewGuid().ToString();
         error.Data.Add("id", errorid);
         ServerApplicationContext.Current.ServerExceptionID = errorid;
         FaultException fe           = new FaultException(new FaultReason(error.Message));
         MessageFault   messagefault = fe.CreateMessageFault();
         fault = Message.CreateMessage(version, messagefault, "http://www.5173.com");
     }
     catch (Exception ex)
     {
         LocalLogService.Log(ex.ToString());
     }
 }
Exemple #11
0
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
#if DEBUG
            var message = request.ToString();
            Console.WriteLine("Server got message:" + message);
#endif
            ServerApplicationContext.Current = request.GetApplicationContext <ServerApplicationContext>();

            try
            {
                var setting    = WcfSettingManager.CurrentServerSetting(OperationContext.Current.GetCurrentServiceDescription().ServiceType);
                var logSetting = setting.WcfLogSetting;
                if (logSetting.Enabled && logSetting.MessageInfoSetting.Enabled)
                {
                    var direct = logSetting.MessageInfoSetting.MessageDirection;
                    if (direct == MessageDirection.Both || direct == MessageDirection.Receive)
                    {
                        var log = WcfLogProvider.GetServerMessageInfo(
                            "ServerMessageInspector.AfterReceiveRequest",
                            MessageDirection.Receive,
                            request.ToString());
                        WcfServiceLocator.GetLogService().LogWithoutException(log);
                    }
                }

                var securitySetting = setting.WcfSecuritySetting;
                if (securitySetting.PasswordCheck.Enable)
                {
                    if (securitySetting.PasswordCheck.Direction == OperationDirection.Both || securitySetting.PasswordCheck.Direction == OperationDirection.Request)
                    {
                        if (ServerApplicationContext.Current.Password != securitySetting.PasswordCheck.Password)
                        {
                            throw new WcfSecurityException("PasswordCheck failed in request!");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LocalLogService.Log(ex.ToString());
                if (ex is WcfSecurityException)
                {
                    throw;
                }
            }
            return(null);
        }
Exemple #12
0
        private static WcfService GetWcfServiceConfiguration(Type serviceType)
        {
            var version = serviceType.GetInterfaces().First().Assembly.GetName().Version;

            try
            {
                using (var scf = WcfServiceClientFactory.CreateServiceClient <IWcfConfigService>())
                {
                    return(scf.Channel.GetWcfService(serviceType.FullName, version.Major + "." + version.Minor, WcfLogProvider.MachineIP));
                }
            }
            catch (Exception ex)
            {
                LocalLogService.Log(ex.ToString());
                throw new Exception("Can not get service metadata, error message is " + ex.Message);
            }
        }
Exemple #13
0
        private static WcfClientEndpoint GetWcfClientEndpointConfiguration(Type serviceContractType)
        {
            var version       = serviceContractType.Assembly.GetName().Version;
            var versionstring = version.Major + "." + version.Minor;

            try
            {
                using (var scf = WcfServiceClientFactory.CreateServiceClient <IWcfConfigService>())
                {
                    return(scf.Channel.GetWcfClientEndpoint(serviceContractType.FullName, versionstring, WcfLogProvider.MachineIP));
                }
            }
            catch (Exception ex)
            {
                LocalLogService.Log(ex.ToString());
                throw new Exception("Can not get client metadata, error message is " + ex.Message);
            }
        }
Exemple #14
0
        public static void InitHeart()
        {
            LocalLogService.Log("InitHeart");
            if (redisHeartThreadForClient == null)
            {
                redisHeartThreadForClient = new Thread(() =>
                {
                    while (true)
                    {
                        using (var redisClient = redisClientManager.GetClient())
                        {
                            redisClient.PublishMessage(REDIS_MESSAGE_CLIENT_CHANNEL, HEART_MESSAGE);
                        }
                        Thread.Sleep(CHECK_SECONDS * 1000);
                    }
                })
                {
                    IsBackground = true,
                    Name         = "redisHeartThreadForClient",
                };
                redisHeartThreadForClient.Start();
            }

            if (redisHeartThreadForServer == null)
            {
                redisHeartThreadForServer = new Thread(() =>
                {
                    while (true)
                    {
                        using (var redisClient = redisClientManager.GetClient())
                        {
                            redisClient.PublishMessage(REDIS_MESSAGE_SERVICE_CHANNEL, HEART_MESSAGE);
                        }
                        Thread.Sleep(CHECK_SECONDS * 1000);
                    }
                })
                {
                    IsBackground = true,
                    Name         = "redisHeartThreadForServer",
                };
                redisHeartThreadForServer.Start();
            }
        }
Exemple #15
0
        public bool HandleError(Exception error)
        {
            try
            {
#if DEBUG
                Console.WriteLine("Exception in service! Message:{0}, id : {1}", error.Message, error.Data["id"]);
#endif
                var logSetting = WcfSettingManager.CurrentServerSetting(OperationContext.Current.GetCurrentServiceDescription().ServiceType).WcfLogSetting;
                if (logSetting.Enabled && logSetting.ExceptionInfoSetting.Enabled)
                {
                    var exceptionID = error.Data["id"].ToString();

                    var log = WcfLogProvider.GetServerExceptionInfo("ErrorHandler.HandleErrer", error);
                    log.ID = exceptionID;
                    WcfServiceLocator.GetLogService().LogWithoutException(log);
                }
            }
            catch (Exception ex)
            {
                LocalLogService.Log(ex.ToString());
            }
            return(true);
        }
Exemple #16
0
 private static void CreateCheckTimer(Action action)
 {
     if (redisCheckTimer == null)
     {
         redisCheckTimer = new Timer(obj =>
         {
             if (((TimeSpan)(DateTime.Now - lastCheckMsgTime)).Seconds > CHECK_SECONDS * 2)
             {
                 LocalLogService.Log("Recreate redis sub thread");
                 try
                 {
                     redisSubThreadForClient.Abort();
                 }
                 catch
                 {
                 }
                 finally
                 {
                     action();
                 }
             }
         }, null, 0, 5000);
     }
 }
Exemple #17
0
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
#if DEBUG
            var message = request.ToString();
            Console.WriteLine("Client send message:" + message);
#endif
            try
            {
                var channelType = channel.GetType();

                var serverContext = new ServerApplicationContext();
                var clientContext = new ClientApplicationContext();
                clientContext.RequestIdentity    = serverContext.RequestIdentity;
                ClientApplicationContext.Current = clientContext;

                var setting         = WcfSettingManager.CurrentClientSetting(channelType);
                var securitySetting = setting.WcfSecuritySetting;
                if (securitySetting.PasswordCheck.Enable)
                {
                    if (securitySetting.PasswordCheck.Direction == OperationDirection.Both || securitySetting.PasswordCheck.Direction == OperationDirection.Request)
                    {
                        serverContext.Password = securitySetting.PasswordCheck.Password;
                    }
                }

                var logSetting = setting.WcfLogSetting;
                if (logSetting.Enabled && logSetting.MessageInfoSetting.Enabled)
                {
                    var direct = logSetting.MessageInfoSetting.MessageDirection;
                    if (direct == MessageDirection.Both || direct == MessageDirection.Send)
                    {
                        var log = WcfLogProvider.GetClientMessageInfo(
                            channelType.FullName,
                            ClientApplicationContext.Current.RequestIdentity,
                            "ClientMessageInspector.BeforeSendRequest",
                            MessageDirection.Send,
                            request.ToString());
                        WcfServiceLocator.GetLogService().LogWithoutException(log);
                    }
                }

                serverContext.RequestIdentity   = Guid.NewGuid().ToString();
                serverContext.ClientMachineName = WcfLogProvider.MachineName;

                if (!contractVersionCache.ContainsKey(channelType.FullName))
                {
                    lock (locker)
                    {
                        if (!contractVersionCache.ContainsKey(channelType.FullName))
                        {
                            contractVersionCache.Add(channelType.FullName, channelType.Assembly.GetName().Version.ToString());
                        }
                    }
                }
                serverContext.ClientVersion = contractVersionCache[channelType.FullName];
                request.SetApplicationContext(serverContext);

                return(channelType);
            }
            catch (Exception ex)
            {
                LocalLogService.Log(ex.ToString());
            }
            return(channel.GetType());
        }