Пример #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());
            }
        }
Пример #2
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());
            }
        }
Пример #3
0
        internal static WcfChannelWrapper <T> CreateServiceClient <T>() where T : class
        {
            string         typeName = typeof(T).FullName;
            ChannelFactory cf;

            if (!channelFactoryCache.TryGetValue(typeName, out cf))
            {
                lock (cacheLocker)
                {
                    if (!channelFactoryCache.TryGetValue(typeName, out cf))
                    {
                        if (typeof(T) == typeof(IWcfConfigService))
                        {
                            var configServiceAddress = ConfigurationManager.AppSettings[WCFCONFIGSERVICE_ADDRESS_KEY];
                            if (string.IsNullOrEmpty(configServiceAddress))
                            {
                                throw new Exception("Please set [" + WCFCONFIGSERVICE_ADDRESS_KEY + "] appSettings in your config!");
                            }
                            var binding = new NetTcpBinding();
                            binding.Security.Mode = SecurityMode.None;
                            var address = string.Format("net.tcp://{0}", configServiceAddress);
                            cf = new ChannelFactory <IWcfConfigService>(binding, address);
                        }
                        else if (typeof(T) == typeof(IWcfLogService))
                        {
                            var logServiceAddress = ConfigurationManager.AppSettings[WCFLOGSERVICE_ADDRESS_KEY];
                            if (string.IsNullOrEmpty(logServiceAddress))
                            {
                                throw new Exception("Please set [" + WCFLOGSERVICE_ADDRESS_KEY + "] appSettings in your config!");
                            }
                            var elements = new List <BindingElement>();
                            elements.Add(new BinaryMessageEncodingBindingElement());
                            elements.Add(new TcpTransportBindingElement());
                            var binding = new CustomBinding(elements);
                            var address = string.Format("net.tcp://{0}", logServiceAddress);
                            cf = new ChannelFactory <IWcfLogService>(binding, address);
                        }
                        else
                        {
                            var endpoint = GetWcfClientEndpointConfiguration(typeof(T));
                            cf = CreateChannelFactory <T>(endpoint);

                            WcfSettingManager.Init <T>();
                            ConfigUpdateManager.InitClient();

                            if (WcfSettingManager.CurrentClientSetting <T>().WcfLogSetting.StartInfoSetting.Enabled)
                            {
                                var log = WcfLogProvider.GetClientStartInfo(typeof(T).FullName, "WcfServiceClientFactory.CreateServiceClient", endpoint);
                                WcfServiceLocator.GetLogService().LogWithoutException(log);
                            }
                        }

                        channelFactoryCache[typeName] = cf;
                    }
                }
            }

            return(new WcfChannelWrapper <T>((cf as ChannelFactory <T>).CreateChannel()));
        }
Пример #4
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;
                }
            }
        }
Пример #5
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);
        }
Пример #6
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);
        }
Пример #7
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());
        }
Пример #8
0
        public override IMessage Invoke(IMessage msg)
        {
            using (var client = WcfServiceClientFactory.CreateServiceClient <T>())
            {
                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);

                bool isSuccessuful = false;
                var  stopwatch     = Stopwatch.StartNew();

                try
                {
#if DEBUG
                    Console.WriteLine("Begin to invoke:" + methodCall.MethodName);
#endif
                    object returnValue = methodCall.MethodBase.Invoke(channel, copiedArgs);

#if DEBUG
                    Console.WriteLine("End invoke:" + methodCall.MethodName);
#endif
                    methodReturn = new ReturnMessage(returnValue,
                                                     copiedArgs,
                                                     copiedArgs.Length,
                                                     methodCall.LogicalCallContext,
                                                     methodCall);
                    isSuccessuful = true;
                }
                catch (Exception ex)
                {
                    var exception  = ex;
                    var excepionID = ClientApplicationContext.Current.ServerExceptionID ?? "";
                    if (ex.InnerException != null)
                    {
                        exception          = ex.InnerException;
                        exception.HelpLink = "Please check this exception via ID : " + excepionID;
                    }

                    methodReturn = new ReturnMessage(exception, methodCall);
                    if (WcfLogSetting.Enabled && WcfLogSetting.ExceptionInfoSetting.Enabled)
                    {
                        var log = WcfLogProvider.GetClientExceptionInfo(
                            typeof(T).FullName,
                            ClientApplicationContext.Current.RequestIdentity,
                            "ServiceRealProxy.Invoke",
                            exception, excepionID);
                        WcfServiceLocator.GetLogService().LogWithoutException(log);
                    }
                }
                finally
                {
                    if (WcfLogSetting.Enabled && WcfLogSetting.InvokeInfoSetting.Enabled)
                    {
                        var log = WcfLogProvider.GetClientInvokeLog(
                            typeof(T).FullName,
                            "ServiceRealProxy.Invoke",
                            stopwatch.ElapsedMilliseconds,
                            isSuccessuful,
                            methodCall.MethodName,
                            ClientApplicationContext.Current);
                        WcfServiceLocator.GetLogService().LogWithoutException(log);
                    }
                }
                return(methodReturn);
            }
        }
Пример #9
0
        public static ServiceHost CreateServiceHost(Type serviceType)
        {
            string typeName    = serviceType.FullName;
            var    serviceHost = new ServiceHost(serviceType);

            if (!typeof(IWcfConfigService).IsAssignableFrom(serviceType) && !typeof(IWcfLogService).IsAssignableFrom(serviceType))
            {
                WcfSettingManager.Init(serviceType);

                if (serviceHost.Description.Behaviors.Find <ServiceErrorBehavior>() == null)
                {
                    serviceHost.Description.Behaviors.Add(new ServiceErrorBehavior());
                }
                if (serviceHost.Description.Behaviors.Find <ActionInterceptBehavior>() == null)
                {
                    serviceHost.Description.Behaviors.Add(new ActionInterceptBehavior());
                }

                if (WcfSettingManager.CurrentServerSetting(serviceType).WcfCoreSetting.EnableUnity)
                {
                    if (serviceHost.Description.Behaviors.Find <UnityServiceBehavior>() == null)
                    {
                        serviceHost.Description.Behaviors.Add(new UnityServiceBehavior());
                    }
                }

                serviceHost.Description.Endpoints.Clear();
                var wcfService = GetWcfServiceConfiguration(serviceType);
                if (wcfService == null)
                {
                    throw new Exception("Can not locate any Wcf service, please check metadata config!");
                }

                var bindingCache = new Dictionary <string, Binding>();

                foreach (var ep in wcfService.Endpoints)
                {
                    string address = ConfigHelper.CreateAddress(
                        ep.EndpointProtocol,
                        Environment.MachineName,
                        ep.EndpointPort,
                        ep.EndpointName);

                    Binding binding;
                    if (!bindingCache.TryGetValue(address, out binding))
                    {
                        binding = ConfigHelper.CreateBinding(ep.EndpointBindingType, ep.EndpointBindingXml);
                        bindingCache[address] = binding;
                    }

                    serviceHost.AddServiceEndpoint(ep.ServiceContractType, binding, address);

                    if (!string.IsNullOrEmpty(ep.EndpointBehaviorXml))
                    {
                        AddEndPointBehavior(serviceHost.Description.Endpoints.Last(), ep.EndpointBehaviorXml);
                    }
                }

                foreach (var ep in serviceHost.Description.Endpoints)
                {
                    ep.Behaviors.Add(new MessageInspectorEndpointBehavior());
                }

                if (!string.IsNullOrEmpty(wcfService.ServiceBehaviorXml))
                {
                    AddServiceBehavior(serviceHost, wcfService.ServiceBehaviorXml);
                }

                serviceHost.Opened += (sender, o) =>
                {
                    if (WcfSettingManager.CurrentServerSetting(serviceType).WcfLogSetting.StartInfoSetting.Enabled)
                    {
                        var log = WcfLogProvider.GetServerStartInfo(serviceType.FullName, "WcfServiceHostFactory.CreateServiceHost", wcfService);
                        WcfServiceLocator.GetLogService().LogWithoutException(log);
                    }
                };
            }

            return(serviceHost);
        }