public void ShouldLogExceptions()
        {
            Throws instance = new Throws();

            IInvocation invocation = Substitute.For<IInvocation>();
            invocation.Request.Target.Returns(instance);
            MethodInfo method = typeof(Throws).GetMethod("DoSomething");
            invocation.Request.Method.Returns(method);
            invocation.When(i => i.Proceed()).Do(i => instance.DoSomething());

            ILogger logger = Substitute.For<ILogger>();
            IKernel kernel = new StandardKernel();
            kernel.Bind<ILogger>().ToConstant(logger);
            invocation.Request.Kernel.Returns(kernel);

            LogInterceptor interceptor = new LogInterceptor();
            try
            {
                interceptor.Intercept(invocation);
                Assert.Fail("The LogInterceptor swallowed the exception.");
            }
            catch (Exception exception)
            {
                logger.Received().Trace(Throws.LogName, "Entering {0}.{1}", typeof(Throws), "DoSomething");
                logger.Received().ErrorException(Throws.LogName, exception);
                logger.Received().Trace(Throws.LogName, "Exiting {0}.{1}", typeof(Throws), "DoSomething");
            }
        }
        public void ShouldLogExceptions()
        {
            Throws instance = new Throws();

            IInvocation invocation = Substitute.For <IInvocation>();

            invocation.Request.Target.Returns(instance);
            MethodInfo method = typeof(Throws).GetMethod("DoSomething");

            invocation.Request.Method.Returns(method);
            invocation.When(i => i.Proceed()).Do(i => instance.DoSomething());

            ILogger logger = Substitute.For <ILogger>();
            IKernel kernel = new StandardKernel();

            kernel.Bind <ILogger>().ToConstant(logger);
            invocation.Request.Kernel.Returns(kernel);

            LogInterceptor interceptor = new LogInterceptor();

            try
            {
                interceptor.Intercept(invocation);
                Assert.Fail("The LogInterceptor swallowed the exception.");
            }
            catch (Exception exception)
            {
                logger.Received().Trace(Throws.LogName, "Entering {0}.{1}", typeof(Throws), "DoSomething");
                logger.Received().ErrorException(Throws.LogName, exception);
                logger.Received().Trace(Throws.LogName, "Exiting {0}.{1}", typeof(Throws), "DoSomething");
            }
        }
        public void ShouldLogToNamedLogWhenAttributeProvided()
        {
            WithAttribute instance = new WithAttribute();

            IInvocation invocation = Substitute.For <IInvocation>();

            invocation.Request.Target.Returns(instance);
            MethodInfo method = typeof(WithAttribute).GetMethod("DoSomething");

            invocation.Request.Method.Returns(method);
            invocation.When(i => i.Proceed()).Do(i => instance.DoSomething());

            ILogger logger = Substitute.For <ILogger>();
            IKernel kernel = new StandardKernel();

            kernel.Bind <ILogger>().ToConstant(logger);
            invocation.Request.Kernel.Returns(kernel);

            LogInterceptor interceptor = new LogInterceptor();

            interceptor.Intercept(invocation);

            logger.Received().Trace(WithAttribute.LogName, "Entering {0}.{1}", typeof(WithAttribute), "DoSomething");
            logger.Received().Trace(WithAttribute.LogName, "Exiting {0}.{1}", typeof(WithAttribute), "DoSomething");
        }
Beispiel #4
0
        /// <summary>
        /// Create a proxied instance of a class
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static T Of <T>(params object[] @params) where T : class
        {
            LogInterceptor interceptor = new LogInterceptor();

            try {
                return(generator.CreateClassProxy(typeof(T), @params, interceptor) as T);
            } catch (Exception ex) {
                string parameters = (@params != null && @params.Length > 0) ? string.Join(',', @params) : "Empty";
                throw new Exception($"Cannot create instance of [{typeof(T).Name}] with parameters [{parameters}]. Exception : \n {ex}");
            }
        }
Beispiel #5
0
        protected override ICascadedInterceptor HandleServiceIntern(IBeanContextFactory beanContextFactory, IServiceContext beanContext, IBeanConfiguration beanConfiguration, Type type, ISet <Type> requestedTypes)
        {
            if (!WrapAllInteractions)
            {
                return(null);
            }
            if (annotationCache.GetAnnotation(type) == null)
            {
                return(null);
            }
            LogInterceptor logInterceptor = new LogInterceptor();

            if (beanContext.IsRunning)
            {
                logInterceptor = beanContext.RegisterWithLifecycle(logInterceptor).Finish();
            }
            else
            {
                beanContextFactory.RegisterWithLifecycle(logInterceptor);
            }
            return(logInterceptor);

            //if (service is IProxyTargetAccessor || service is IInterceptor)
            //{
            //    return service;
            //}
            //if (!requestedType.IsInterface)
            //{
            //    MethodInfo[] methods = service.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance);
            //    foreach (MethodInfo method in methods)
            //    {
            //        if (typeof(Object).Equals(method.DeclaringType))
            //        {
            //            continue;
            //        }
            //        if (!method.IsVirtual)
            //        {
            //            if (Log.DebugEnabled)
            //            {
            //                Log.Debug(service.GetType().FullName + "." + LogTypesUtil.PrintMethod(method.Name, method.GetParameters(), null, PrintShortStringNames)
            //                    + " is not virtual. Skipping LoggingProxy for this service instance");
            //            }
            //            return service;
            //        }
            //    }
            //}
            //ICascadedInterceptor logInterceptor = BeanContext.MonitorObject<LogInterceptor>();
            //logInterceptor.Target = service;
            //return ProxyFactory.CreateProxy(requestedType, logInterceptor);
        }
Beispiel #6
0
		protected override bool RunTest()
		{
			using (var appender = new LogInterceptor(Log))
			using (var silo = new OutOfProcessSilo())
			{
				silo.OnHostOutputWritten += LogHost;
				silo.Start();
				var instance = silo.CreateGrain<ISample>(typeof (Sample));
				Log(string.Format("Have you been called yet? - {0}", instance.HaveYouBeenCalledYet()));
				instance.Call("This message is sent via a remote procedure call through the ISample interface");
				Log(string.Format("What about now? - {0}", instance.HaveYouBeenCalledYet()));

				Log("What's the value of PI?");
				instance.WritePi();
				return true;
			}
		}
Beispiel #7
0
        protected override bool RunTest()
        {
            using (var accessor = new LogInterceptor(Log))
                using (var endPoint = new SocketEndPoint(EndPointType.Client))
                {
                    endPoint.Connect(WatchdogHost.PeerName, TimeSpan.FromSeconds(5));

                    var remote   = endPoint.CreateProxy <IInternalWatchdog>(WatchdogHost.ObjectId);
                    var watchdog = new Watchdog(remote);

                    var app = new ApplicationDescriptor
                    {
                        Name = "SharpRemote 0.1 Developer Build"
                    };
                    using (var installer = watchdog.StartInstallation(app, Installation.CleanInstall))
                    {
                        installer.AddFiles(new[]
                        {
                            // Full deployment
                            "SharpRemote.dll",
                            "SharpRemote.pdb",
                            "SharpRemote.Watchdog.exe",
                            "SharpRemote.Watchdog.exe.config",
                            "SharpRemote.Watchdog.pdb",
                            "SharpRemote.Watchdog.Service.exe",
                            "SharpRemote.Watchdog.Service.exe.config",
                            "SharpRemote.Watchdog.Service.pdb",
                            "SharpRemote.Host.exe",
                            "SharpRemote.Host.exe.config",
                            "SharpRemote.Host.pdb",

                            // 3rd party
                            "log4net.dll"
                        },
                                           Environment.SpecialFolder.LocalApplicationData);

                        installer.Commit();
                    }

                    return(true);
                }
        }
        public void ShouldLogToNamedLogWhenAttributeProvided()
        {
            WithAttribute instance = new WithAttribute();

            IInvocation invocation = Substitute.For<IInvocation>();
            invocation.Request.Target.Returns(instance);
            MethodInfo method = typeof(WithAttribute).GetMethod("DoSomething");
            invocation.Request.Method.Returns(method);
            invocation.When(i => i.Proceed()).Do(i => instance.DoSomething());

            ILogger logger = Substitute.For<ILogger>();
            IKernel kernel = new StandardKernel();
            kernel.Bind<ILogger>().ToConstant(logger);
            invocation.Request.Kernel.Returns(kernel);

            LogInterceptor interceptor = new LogInterceptor();
            interceptor.Intercept(invocation);

            logger.Received().Trace(WithAttribute.LogName, "Entering {0}.{1}", typeof(WithAttribute), "DoSomething");
            logger.Received().Trace(WithAttribute.LogName, "Exiting {0}.{1}", typeof(WithAttribute), "DoSomething");
        }
        protected override bool RunTest()
        {
            using (var appender = new LogInterceptor(Log, Level.Info))
                using (var silo = new InProcessRemotingSilo())
                {
                    //Ssilo.Start();
                    var grain = silo.CreateGrain <IGetInt64Property, ReturnsNearlyInt64Max>();

                    long sum   = 0;
                    long num   = 0;
                    var  time  = TimeSpan.FromSeconds(20);
                    var  watch = new Stopwatch();

                    // Measurement phase
                    watch.Start();
                    while (watch.Elapsed < time)
                    {
                        for (int i = 0; i < 100; ++i)
                        {
                            unchecked
                            {
                                sum += grain.Value;
                            }
                        }
                        num += 100;
                    }
                    watch.Stop();

                    var numSeconds = watch.Elapsed.TotalSeconds;
                    var ops        = 1.0 * num / numSeconds;
                    Log(string.Format("Total calls: {0} (sum: {1})", num, sum));
                    Log(string.Format("OP/s: {0:F2}k/s", ops / 1000));

                    return(true);
                }
        }
        public IInterceptor CreateInterceptor(IServiceContext sourceBeanContext, Type syncLocalInterface, Type syncRemoteInterface, Type asyncRemoteInterface)
        {
            ParamChecker.AssertParamNotNull(sourceBeanContext, "sourceBeanContext");
            Type syncInterceptorType = null;

            if (syncRemoteInterface == null)
            {
                syncRemoteInterface = syncLocalInterface;
            }
            else
            {
                syncInterceptorType = ClientServiceFactory.GetSyncInterceptorType(syncRemoteInterface);
            }

            if (asyncRemoteInterface == null)
            {
                asyncRemoteInterface = syncRemoteInterface;
            }

            Type clientProviderType = ClientServiceFactory.GetTargetProviderType(asyncRemoteInterface);

            String serviceName = ClientServiceFactory.GetServiceName(syncRemoteInterface);

            String syncRemoteInterceptorName = "syncRemoteInterceptor";
            String syncCallInterceptorName   = "syncCallInterceptor";
            String targetProviderName        = "targetProvider";
            String targetingInterceptorName  = "targetingInterceptor";
            String asyncProxyName            = "asyncProxy";

            IServiceContext childContext = sourceBeanContext.CreateService(delegate(IBeanContextFactory bcf)
            {
                if (typeof(IRemoteTargetProvider).IsAssignableFrom(clientProviderType))
                {
                    bcf.RegisterBean(targetProviderName, clientProviderType).PropertyValue("ServiceName", serviceName);
                    ClientServiceFactory.PostProcessTargetProviderBean(targetProviderName, bcf);

                    //TargetProvider and target have to be set up manually here
                    bcf.RegisterBean <TargetingInterceptor>(targetingInterceptorName).PropertyRef("TargetProvider", targetProviderName);

                    LogInterceptor logInterceptor = (LogInterceptor)bcf.RegisterBean <LogInterceptor>("logInterceptor").PropertyRef("Target", targetingInterceptorName).GetInstance();

                    Object asyncProxy = ProxyFactory.CreateProxy(asyncRemoteInterface, logInterceptor);
                    bcf.RegisterExternalBean(asyncProxyName, asyncProxy);

                    bcf.RegisterBean <SyncCallInterceptor>(syncCallInterceptorName).PropertyRef("AsyncService", asyncProxyName).PropertyValue("AsyncServiceInterface", asyncRemoteInterface);

                    if (syncRemoteInterface != syncLocalInterface)
                    {
                        bcf.RegisterBean(syncRemoteInterceptorName, syncInterceptorType).PropertyValue("WCFInterfaceType", syncRemoteInterface);
                    }
                    else
                    {
                        bcf.RegisterAlias(syncRemoteInterceptorName, syncCallInterceptorName);
                    }
                }
                else
                {
                    throw new Exception("ProviderType '" + clientProviderType + "' is not supported here");
                }
            });

            return(childContext.GetService <IInterceptor>(syncRemoteInterceptorName));
        }
Beispiel #11
0
        /// <summary>
        /// Initializes this instance.
        /// </summary>
        private void Initialize()
        {
            try {
                //Set initializing Lock.
                if (IsInitializing || IsInitialized) return;
                IsInitializing = true;

                //Initialize File Settings.
                if (ConfigurationManager.AppSettings.AllKeys.Contains("LogFileName"))
                    FileName = ConfigurationManager.AppSettings["LogFileName"];
                else { FileName = Path.Combine(Environment.CurrentDirectory, "log.txt"); }
                if (ConfigurationManager.AppSettings.AllKeys.Contains("LogPrefix"))
                    Prefix = ConfigurationManager.AppSettings["LogPrefix"];
                else { Prefix = "[Logger]"; }

                //Initialize Log File.
                if (File.Exists(FileName)) File.Delete(FileName);
                var HeaderNamespace = "Keyrox.Infra.Properties.LogHeader.txt";
                using (var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(HeaderNamespace)) {
                    if (resourceStream == null) { throw new Exception(HeaderNamespace + " Not Found!"); }
                    using (var reader = new StreamReader(resourceStream)) {
                        var contents = reader.ReadToEnd();
                        contents = string.Format(contents,
                            Assembly.GetEntryAssembly().GetName().GetBuildDate().ToString("dd/MM/yyyy"),
                            Assembly.GetEntryAssembly().GetName().Version.FillLeftSpaces(14),
                            "8.3.1");
                        using (var writer = new StreamWriter(FileName)) {
                            writer.WriteLine(contents);
                            writer.Flush();
                            writer.Close();
                        }
                    }
                }
                //Unlock initializing.
                Interceptor = new LogInterceptor();
                IsInitialized = true;
                IsInitializing = false;
                System.Threading.Thread.Sleep(300);
            }
            catch (Exception ex) {
                var exMsg = "Unable to initialize Application Log!";
                string.Concat(exMsg, Environment.NewLine, ex.Message);
                throw new Exception(exMsg, ex);
            }
        }