public void WhenOperationContextIsServiceContextReturnsRequest()
 {
     using ( var host = new HostingContext<ContextCheckService, IContextCheckService>() )
     {
         host.Open();
         var client = host.GetChannel();
         using ( var scope = new OperationContextScope((IContextChannel)client) )
         {
             Assert.IsTrue(client.CanGetRequestTelemetry());
         }
     }
 }
        public void CallsToOpMarkedWithOperationTelemetryGeneratesEvents()
        {
            TestTelemetryChannel.Clear();
            var host = new HostingContext<SelectiveTelemetryService, ISelectiveTelemetryService>();
            using ( host )
            {
                host.Open();

                ISelectiveTelemetryService client = host.GetChannel();
                client.OperationWithTelemetry();
            }
            Assert.IsTrue(TestTelemetryChannel.CollectedData().Count > 0);
        }
        public void CallsToOpWithoutOperationTelemetryGeneratesEvents()
        {
            TestTelemetryChannel.Clear();
            var host = new HostingContext<SelectiveTelemetryService, ISelectiveTelemetryService>();
            using ( host )
            {
                host.Open();

                ISelectiveTelemetryService client = host.GetChannel();
                client.OperationWithoutTelemetry();
            }
            Assert.AreEqual(0, TestTelemetryChannel.CollectedData().Count);
        }
        public void SuccessfulOneWayCallGeneratesRequestEvent()
        {
            TestTelemetryChannel.Clear();
            using ( var host = new HostingContext<OneWayService, IOneWayService>() )
            {
                host.Open();
                IOneWayService client = host.GetChannel();
                client.SuccessfullOneWayCall();
            }
            var req = TestTelemetryChannel.CollectedData()
                     .FirstOrDefault(x => x is RequestTelemetry);

            Assert.IsNotNull(req);
        }
        public void AllTelemetryEventsFromOneCallHaveSameOperationId()
        {
            TestTelemetryChannel.Clear();
            using ( var host = new HostingContext<SimpleService, ISimpleService>() )
            {
                host.Open();
                ISimpleService client = host.GetChannel();
                client.GetSimpleData();
            }
            var ids = TestTelemetryChannel.CollectedData()
                    .Select(x => x.Context.Operation.Id)
                    .Distinct();

            Assert.AreEqual(1, ids.Count());
        }
Example #6
0
        public TestServer(IConfiguration config, IServiceProvider serviceProvider, Action <IApplicationBuilder> appStartup)
        {
            var appEnv = serviceProvider.GetRequiredService <IApplicationEnvironment>();

            HostingContext hostContext = new HostingContext()
            {
                ApplicationName    = appEnv.ApplicationName,
                Configuration      = config,
                ServerFactory      = this,
                Services           = serviceProvider,
                ApplicationStartup = appStartup
            };

            var engine = serviceProvider.GetRequiredService <IHostingEngine>();

            _appInstance = engine.Start(hostContext);
        }
        private static DbContext TryCreateContextFromStartup(Type type)
        {
#if DNX451 || DNXCORE50
            try
            {
                var context = new HostingContext
                {
                    ServerFactory = new ServerFactory(),
                };
                var instance = new HostingEngine().Start(context);
                return(context.ApplicationServices.GetService(type) as DbContext);
            }
            catch
            {
            }
#endif

            return(null);
        }
        public static IServiceProvider CreateServiceProvider(Action <IServiceCollection> configure)
        {
            var context = new HostingContext
            {
                ServerFactory  = new ServerFactory(),
                StartupMethods = new StartupMethods(
                    _ => { },
                    services =>
                {
                    services.AddSignalR();
                    configure(services);
                    return(services.BuildServiceProvider());
                })
            };

            var engine = new HostingEngine().Start(context);

            return(context.ApplicationServices);
        }
        public void CallCanFlowRootOperationId()
        {
            TestTelemetryChannel.Clear();
            var host = new HostingContext<SelectiveTelemetryService, ISelectiveTelemetryService>();
            using ( host )
            {
                host.Open();

                ISelectiveTelemetryService client = host.GetChannel();
                using ( var scope = new OperationContextScope((IContextChannel)client) )
                {
                    var rootId = new RootIdMessageHeader();
                    rootId.RootId = "rootId";
                    OperationContext.Current.OutgoingMessageHeaders.Add(rootId);
                    client.OperationWithTelemetry();
                }
            }
            Assert.AreEqual("rootId", TestTelemetryChannel.CollectedData().First().Context.Operation.Id);
        }
        public void FailedOneWayCallGeneratesExceptionEvent()
        {
            TestTelemetryChannel.Clear();
            var host = new HostingContext<OneWayService, IOneWayService>()
                      .ExpectFailure();
            using ( host )
            {
                host.Open();
                IOneWayService client = host.GetChannel();
                try
                {
                    client.FailureOneWayCall();
                } catch
                {
                }
            }
            var req = TestTelemetryChannel.CollectedData()
                     .FirstOrDefault(x => x is ExceptionTelemetry);

            Assert.IsNotNull(req);
        }
Example #11
0
        public Task <int> Main(string[] args)
        {
            //Add command line configuration source to read command line parameters.
            var config = new Configuration();

            config.AddCommandLine(args);

            var serviceCollection = new ServiceCollection();

            serviceCollection.Add(HostingServices.GetDefaultServices(config));
            serviceCollection.AddInstance <IHostingEnvironment>(new HostingEnvironment()
            {
                WebRoot = "wwwroot"
            });
            var services = serviceCollection.BuildServiceProvider(_hostServiceProvider);

            var context = new HostingContext()
            {
                Services        = services,
                Configuration   = config,
                ServerName      = "Microsoft.AspNet.Server.WebListener",
                ApplicationName = "MusicStore"
            };

            var engine = services.GetService <IHostingEngine>();

            if (engine == null)
            {
                throw new Exception("TODO: IHostingEngine service not available exception");
            }

            using (engine.Start(context))
            {
                Console.WriteLine("Started the server..");
                Console.WriteLine("Press any key to stop the server");
                Console.ReadLine();
            }
            return(Task.FromResult(0));
        }
        public void RequestReply_TelemetryIsWritten()
        {
            TestTelemetryChannel.Clear();
            using (var host = new HostingContext <SimpleService, ISimpleService>())
            {
                host.Open();

                var            binding       = new NetTcpBinding();
                var            configuration = new TelemetryConfiguration();
                var            factory       = new ChannelFactory <ISimpleService>(binding, host.GetServiceAddress());
                ISimpleService channel       = null;
                try
                {
                    var behavior = new ClientTelemetryEndpointBehavior(configuration);
#if NET40
                    factory.Endpoint.Behaviors.Add(behavior);
#else
                    factory.Endpoint.EndpointBehaviors.Add(behavior);
#endif

                    channel = factory.CreateChannel();
                    channel.GetSimpleData();
                    ((IClientChannel)channel).Close();
                    factory.Close();

                    Assert.IsTrue(TestTelemetryChannel.CollectedData().Count > 0, "No telemetry events written");
                }
                catch
                {
                    if (channel != null)
                    {
                        ((IClientChannel)channel).Abort();
                    }

                    factory.Abort();
                    throw;
                }
            }
        }
Example #13
0
        public TestServer(IConfiguration config, IServiceProvider serviceProvider, Action <IBuilder> appStartup)
        {
            var env = serviceProvider.GetService <IApplicationEnvironment>();

            if (env == null)
            {
                throw new ArgumentException("IApplicationEnvironment couldn't be resolved.", "serviceProvider");
            }

            HostingContext hostContext = new HostingContext()
            {
                ApplicationName    = env.ApplicationName,
                Configuration      = config,
                ServerFactory      = this,
                Services           = serviceProvider,
                ApplicationStartup = appStartup
            };

            var engine = serviceProvider.GetService <IHostingEngine>();

            _appInstance = engine.Start(hostContext);
        }
Example #14
0
        public Task <int> Main(string[] args)
        {
            //Add command line configuration source to read command line parameters.
            var config = new Configuration();

            config.AddCommandLine(args);

            var context = new HostingContext()
            {
                Configuration         = config,
                ServerFactoryLocation = "Microsoft.AspNet.Server.WebListener",
                ApplicationName       = "MusicStore"
            };

            using (new HostingEngine().Start(context))
            {
                Console.WriteLine("Started the server..");
                Console.WriteLine("Press any key to stop the server");
                Console.ReadLine();
            }
            return(Task.FromResult(0));
        }
        public void BehaviorAddsCustomBinding()
        {
            using (var host = new HostingContext <SimpleService, ISimpleService>())
            {
                var            binding       = new NetTcpBinding();
                var            configuration = new TelemetryConfiguration();
                var            factory       = new ChannelFactory <ISimpleService>(binding, host.GetServiceAddress());
                ISimpleService channel       = null;
                try
                {
                    var behavior = new ClientTelemetryEndpointBehavior(configuration);
#if NET40
                    factory.Endpoint.Behaviors.Add(behavior);
#else
                    factory.Endpoint.EndpointBehaviors.Add(behavior);
#endif

                    channel = factory.CreateChannel();
                    var innerChannel = GetInnerChannel(channel);
                    ((IClientChannel)channel).Close();
                    factory.Close();

                    Assert.IsInstanceOfType(innerChannel, typeof(ClientTelemetryChannelBase), "Telemetry channel is missing");
                }
                catch
                {
                    factory.Abort();
                    if (channel != null)
                    {
                        ((IClientChannel)channel).Abort();
                    }

                    throw;
                }
            }
        }
 public StudentsController(HostingContext context)
 {
     _context = context;
 }
        public void CallWithUnknownActionReportsCatchAllOperation()
        {
            TestTelemetryChannel.Clear();
            var host = new HostingContext<SimpleService, ISimpleService>();
            using ( host )
            {
                host.Open();

                ISimpleService client = host.GetChannel();
                using ( OperationContextScope scope = new OperationContextScope((IContextChannel)client) )
                {
                    OperationContext.Current.OutgoingMessageHeaders.Action = "http://someaction";
                    client.CatchAllOperation();
                }
            }
            var evt = TestTelemetryChannel.CollectedData().First();
            Assert.AreEqual("ISimpleService.CatchAllOperation", evt.Context.Operation.Name);
        }
 public void TelemetryEventsAreGeneratedOnServiceCall()
 {
     TestTelemetryChannel.Clear();
     using ( var host = new HostingContext<SimpleService, ISimpleService>() )
     {
         host.Open();
         ISimpleService client = host.GetChannel();
         client.GetSimpleData();
         Assert.IsTrue(TestTelemetryChannel.CollectedData().Count > 0);
     }
 }
        public void OperationNameIsSetBasedOnOperationCalled()
        {
            TestTelemetryChannel.Clear();
            using ( var host = new HostingContext<SimpleService, ISimpleService>() )
            {
                host.Open();
                ISimpleService client = host.GetChannel();
                client.GetSimpleData();
            }
            var operationName = TestTelemetryChannel.CollectedData()
                               .Select(x => x.Context.Operation.Name)
                               .First();

            Assert.IsTrue(operationName.EndsWith("GetSimpleData", StringComparison.Ordinal));
        }
 public void ErrorTelemetryEventsContainDetailedInfoOnTypedFault()
 {
     TestTelemetryChannel.Clear();
     var host = new HostingContext<SimpleService, ISimpleService>()
               .ShouldWaitForCompletion();
     using ( host )
     {
         host.Open();
         ISimpleService client = host.GetChannel();
         try
         {
             client.CallFailsWithTypedFault();
         } catch
         {
         }
     }
     var error = (from item in TestTelemetryChannel.CollectedData()
                  where item is ExceptionTelemetry
                  select item).Cast<ExceptionTelemetry>().First();
     Assert.IsNotNull(error.Exception);
     Assert.IsNotNull(error.Context.Operation.Id);
     Assert.IsNotNull(error.Context.Operation.Name);
 }
 public void ErrorTelemetryEventsAreGeneratedOnFault()
 {
     TestTelemetryChannel.Clear();
     var host = new HostingContext<SimpleService, ISimpleService>()
               .ShouldWaitForCompletion();
     using ( host )
     {
         host.Open();
         ISimpleService client = host.GetChannel();
         try
         {
             client.CallFailsWithFault();
         } catch
         {
         }
     }
     var errors = from item in TestTelemetryChannel.CollectedData()
                  where item is ExceptionTelemetry
                  select item;
     Assert.IsTrue(errors.Count() > 0);
 }
Example #22
0
        public void Main(string[] args)
        {
            var applicationRoot = Directory.GetCurrentDirectory();
            var serverPort      = 2000;
            var traceType       = TraceType.Information;

            var enumerator = args.GetEnumerator();

            while (enumerator.MoveNext())
            {
                var arg = (string)enumerator.Current;
                if (arg == "-s")
                {
                    enumerator.MoveNext();
                    applicationRoot = Path.GetFullPath((string)enumerator.Current);
                }
                else if (arg == "-p")
                {
                    enumerator.MoveNext();
                    serverPort = int.Parse((string)enumerator.Current);
                }
                else if (arg == "-v")
                {
                    traceType = TraceType.Verbose;
                }
            }

            var environment = new OmnisharpEnvironment(applicationRoot, serverPort, traceType);
            var hostingEnv  = new HostingEnvironment {
                EnvironmentName = "Development"
            };

            var config = new Configuration()
                         .AddCommandLine(new[] { "--server.urls", "http://localhost:" + serverPort });

            var serviceCollection = new ServiceCollection();

            serviceCollection.Add(HostingServices.GetDefaultServices(config));
            serviceCollection.AddInstance <IOmnisharpEnvironment>(environment);
            serviceCollection.AddInstance <IHostingEnvironment>(hostingEnv);

            var services = serviceCollection
                           .BuildServiceProvider(_serviceProvider);

            var appEnv = services.GetRequiredService <IApplicationEnvironment>();

            var context = new HostingContext()
            {
                Services        = services,
                Configuration   = config,
                ServerName      = "Kestrel",
                ApplicationName = appEnv.ApplicationName,
                EnvironmentName = hostingEnv.EnvironmentName,
            };

            var engine             = services.GetRequiredService <IHostingEngine>();
            var appShutdownService = _serviceProvider.GetRequiredService <IApplicationShutdown>();
            var shutdownHandle     = new ManualResetEventSlim(false);

            var serverShutdown = engine.Start(context);

            appShutdownService.ShutdownRequested.Register(() =>
            {
                serverShutdown.Dispose();
                shutdownHandle.Set();
            });

#if ASPNETCORE50
            var ignored = Task.Run(() =>
            {
                Console.WriteLine("Started");
                Console.ReadLine();
                appShutdownService.RequestShutdown();
            });
#else
            Console.CancelKeyPress += (sender, e) =>
            {
                appShutdownService.RequestShutdown();
            };
#endif

            shutdownHandle.Wait();
        }
Example #23
0
        public void Main(string[] args)
        {
            var applicationRoot = Directory.GetCurrentDirectory();
            var serverPort      = 2000;
            var logLevel        = LogLevel.Information;
            var hostPID         = -1;
            var transportType   = TransportType.Http;
            var otherArgs       = new List <string>();

            var enumerator = args.GetEnumerator();

            while (enumerator.MoveNext())
            {
                var arg = (string)enumerator.Current;
                if (arg == "-s")
                {
                    enumerator.MoveNext();
                    applicationRoot = Path.GetFullPath((string)enumerator.Current);
                }
                else if (arg == "-p")
                {
                    enumerator.MoveNext();
                    serverPort = int.Parse((string)enumerator.Current);
                }
                else if (arg == "-v")
                {
                    logLevel = LogLevel.Verbose;
                }
                else if (arg == "--hostPID")
                {
                    enumerator.MoveNext();
                    hostPID = int.Parse((string)enumerator.Current);
                }
                else if (arg == "--stdio")
                {
                    transportType = TransportType.Stdio;
                }
                else
                {
                    otherArgs.Add((string)enumerator.Current);
                }
            }

            Environment = new OmnisharpEnvironment(applicationRoot, serverPort, hostPID, logLevel, transportType, otherArgs.ToArray());

            var config = new Configuration()
                         .AddCommandLine(new[] { "--server.urls", "http://localhost:" + serverPort });

            var serviceCollection = HostingServices.Create(_serviceProvider, config);

            serviceCollection.AddSingleton <ISharedTextWriter, SharedConsoleWriter>();

            var services   = serviceCollection.BuildServiceProvider();
            var hostingEnv = services.GetRequiredService <IHostingEnvironment>();
            var appEnv     = services.GetRequiredService <IApplicationEnvironment>();

            var context = new HostingContext()
            {
                Services        = services,
                Configuration   = config,
                ServerName      = "Kestrel",
                ApplicationName = appEnv.ApplicationName,
                EnvironmentName = hostingEnv.EnvironmentName,
            };

            if (transportType == TransportType.Stdio)
            {
                context.ServerName    = null;
                context.ServerFactory = new Stdio.StdioServerFactory(Console.In, services.GetRequiredService <ISharedTextWriter>());
            }

            var engine             = services.GetRequiredService <IHostingEngine>();
            var appShutdownService = services.GetRequiredService <IApplicationShutdown>();
            var shutdownHandle     = new ManualResetEvent(false);

            var serverShutdown = engine.Start(context);

            appShutdownService.ShutdownRequested.Register(() =>
            {
                serverShutdown.Dispose();
                shutdownHandle.Set();
            });

#if ASPNETCORE50
            var ignored = Task.Run(() =>
            {
                Console.WriteLine("Started");
                Console.ReadLine();
                appShutdownService.RequestShutdown();
            });
#else
            Console.CancelKeyPress += (sender, e) =>
            {
                appShutdownService.RequestShutdown();
            };
#endif

            if (hostPID != -1)
            {
                try
                {
                    var hostProcess = Process.GetProcessById(hostPID);
                    hostProcess.EnableRaisingEvents = true;
                    hostProcess.OnExit(() => appShutdownService.RequestShutdown());
                }
                catch
                {
                    // If the process dies before we get here then request shutdown
                    // immediately
                    appShutdownService.RequestShutdown();
                }
            }

            shutdownHandle.WaitOne();
        }