private void Configure(AzureServiceBusOwinServiceConfiguration config, Action<IAppBuilder> startup)
        {
            if (startup == null)
            {
                throw new ArgumentNullException("startup");
            }

            var options = new StartOptions();
            if (string.IsNullOrWhiteSpace(options.AppStartup))
            {
                // Populate AppStartup for use in host.AppName
                options.AppStartup = startup.Method.ReflectedType.FullName;
            }

            var testServerFactory = new AzureServiceBusOwinServerFactory(config);
            var services = ServicesFactory.Create();
            var engine = services.GetService<IHostingEngine>();
            var context = new StartContext(options)
            {
                ServerFactory = new ServerFactoryAdapter(testServerFactory),
                Startup = startup
            };
            _started = engine.Start(context);
            _next = testServerFactory.Invoke;
        }
Exemple #2
0
        static void Main(string[] args)
        {
            var uris = Utilities.GetUriParams(8080);
            var owinStartupOptions = new StartOptions();


            foreach (var uri in uris)
            {
                owinStartupOptions.Urls.Add(uri.ToString());
            }

            using (WebApp.Start<SelfHost.OwinStartup>(owinStartupOptions))
            {
                // todo: create tray icon instead of console app...
                Console.WriteLine("\nEIC System Tracker Host. Running at:\n");

                Console.ForegroundColor = ConsoleColor.Green;
                foreach (var uri in uris)
                    Console.WriteLine("\t" + uri.ToString());

                // Start Chrome
                System.Diagnostics.Process.Start("chrome", uris[0].AbsoluteUri);

                Console.ResetColor();
                Console.Write("\n\nPress \'Enter\' to exit.");
                Console.ReadLine();
            }
        }
Exemple #3
0
		public static App Initialize(AppConfig config, Func<StartOptions, NancyOptions, IDisposable> hostFunc)
		{
			config.ThrowIfInvalid();
			var poller = new LeaderInfoPoller(config.StorageAccount);
			var startOptions = new StartOptions();
			startOptions.Urls.Add(config.InternalUri);
			startOptions.Urls.Add(config.PublicUri);

			var auth = LoadAuth.LoadFromStorageAccount(config.StorageAccount);
			AddSystemAccess(auth, config.StorageAccount.GetSysPassword());
			var api = ApiImplementation.Create(config.StorageAccount, poller, auth);
			var nancyOptions = new NancyOptions
			{
				Bootstrapper = new NancyBootstrapper(api, new UserValidator(auth))
			};
			var nodeInfo = new LeaderInfo(config.InternalUri);

			var selector = new LeaderLock(config.StorageAccount, nodeInfo, api);

			var cts = new CancellationTokenSource();
			// fire up leader and scheduler first
			var tasks = new List<Task> {
				selector.KeepTryingToAcquireLock(cts.Token),
				poller.KeepPollingForLeaderInfo(cts.Token),
			};
			// bind the API
			var host = hostFunc(startOptions, nancyOptions);

			return new App(host, cts, tasks);
		}
        public void Start()
        {
            var siteUrl = Settings.Default.SiteUrl;
            var portNumber = Settings.Default.PortNumber;
            var uri = $"http://*:{portNumber}{siteUrl}";

            SmartDBEntities.SetConnection(Settings.Default.DBServer, Settings.Default.DBName,
                Settings.Default.DBUser,
                Encryption.Decrypt(Settings.Default.DBPassword));

            Program.ProcessLog.Write("Database connection string to " + Settings.Default.DBServer +
                                     " has successfully been made.");
            if (SmartDBEntities.IsDBAvailable)
                Program.ProcessLog.Write("Database connection  " + Settings.Default.DBServer +
                                         " has successfully been made.");
            else
                Program.ProcessLog.Write("Database connection  " + Settings.Default.DBServer + " has failed.");
            var options = new StartOptions();
#if DEBUG
            options.Urls.Add($"http://{Environment.MachineName}:15000");
            options.Urls.Add("http://localhost:15000/");
#endif
            options.Urls.Add(uri);
            Host = WebApp.Start<Startup>(options);
        }
        public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            this.logger = providerRuntime.GetLogger("Dashboard");

            var router = new Router();
            new DashboardController(router, TaskScheduler.Current,  providerRuntime);

            var options = new StartOptions
            {
                ServerFactory = "Nowin",
                Port = config.Properties.ContainsKey("Port") ? int.Parse(config.Properties["Port"]) : 8080,
            };

            var username = config.Properties.ContainsKey("Username") ? config.Properties["Username"] : null;
            var password = config.Properties.ContainsKey("Password") ? config.Properties["Password"] : null;
            try
            {
                host = WebApp.Start(options, app => new WebServer(router, username, password).Configuration(app));
            }
            catch (Exception ex)
            {
                this.logger.Error(10001, ex.ToString());
            }

            this.logger.Verbose($"Dashboard listening on {options.Port}");

            this.profiler = new GrainProfiler(TaskScheduler.Current, providerRuntime);

            var dashboardGrain = providerRuntime.GrainFactory.GetGrain<IDashboardGrain>(0);
            return dashboardGrain.Init();
        }
	    private static void Owin()
	    {
		    var options = new StartOptions
			    {
				    ServerFactory = "Nowin",
				    Port = 8081
			    };

		    using (WebApp.Start<Startup>(options))
		    {
			    string localIp = "?";
				IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
				foreach (IPAddress ip in host.AddressList)
				{
					if (ip.AddressFamily == AddressFamily.InterNetwork)
					{
						localIp = ip.ToString();
					}
				}	
				Console.WriteLine(string.Format("Running a http server on port http://{0}:{1}",localIp, options.Port));
				while (true)
				{
					Thread.Sleep(1000);
				}
		    }
	    }
Exemple #7
0
        private static void Main(string[] args)
        {
            Bootstrapper.Init();

            var port = ConfigurationManager.AppSettings["Port"];

            var options = new StartOptions($"http://*:{port}")
            {
                ServerFactory = "Microsoft.Owin.Host.HttpListener"
            };

            using (var scope = Bootstrapper.Container.BeginLifetimeScope())
            {
                var startup = scope.Resolve<Startup>();

                var service = scope.Resolve<Service>();

                Task.Run(() => service.Start());

                // Start OWIN host
                using (WebApp.Start(options, startup.Configuration))
                {
                    foreach (var url in options.Urls)
                    {
                        Console.WriteLine($"Service listening on {url}");
                    }

                    Console.ReadLine();
                }
            }
        }
Exemple #8
0
        public static void RunServer(StartOptions options)
        {
            if (options == null)
            {
                return;
            }

            string boot;
            if (!options.Settings.TryGetValue("boot", out boot)
                || string.IsNullOrWhiteSpace(boot))
            {
                options.Settings["boot"] = "Domain";
            }

            ResolveAssembliesFromDirectory(
                Path.Combine(Directory.GetCurrentDirectory(), "bin"));

            WriteLine("Starting with " + GetDisplayUrl(options));

            IServiceProvider services = ServicesFactory.Create();
            var starter = services.GetService<IHostingStarter>();
            IDisposable server = starter.Start(options);

            WriteLine("Started successfully");

            WriteLine("Press Enter to exit");
            Console.ReadLine();

            WriteLine("Terminating.");

            server.Dispose();
        }
        public IDisposable CreateApp(List<string> urls)
        {
            var services = CreateServiceFactory();
            var engine = services.GetService<IHostingEngine>();

            var options = new StartOptions()
            {
                ServerFactory = "Microsoft.Owin.Host.HttpListener"
            };

            urls.ForEach(options.Urls.Add);

            var context = new StartContext(options) { Startup = BuildApp };


            try
            {
                return engine.Start(context);
            }
            catch (TargetInvocationException ex)
            {
                if (ex.InnerException == null)
                {
                    throw;
                }

                if (ex.InnerException is HttpListenerException)
                {
                    throw new PortInUseException("Port {0} is already in use, please ensure NzbDrone is not already running.", ex, _configFileProvider.Port);
                }

                throw ex.InnerException;
            }
        }
Exemple #10
0
		private static void Main()
		{
			var options = new StartOptions();
			options.Urls.Add(ConfigurationManager.AppSettings["ServerUrl"]);

			using (WebApp.Start<Startup>(options))
			{
				Console.WriteLine("Server running on {0}", options.Urls[0]);

				do
				{
					var readLine = Console.ReadLine();

					if (readLine != null)
					{
						if (readLine.ToLower() == "start")
						{
							Sync.ConsolePauseEvent.Reset();
						}
						if (readLine.ToLower() == "pause")
						{
							Sync.ConsolePauseEvent.Set();
						}
					}
				} while (true);
			}
		}
		public void BeforeAnyTests() {
			var options = new StartOptions();
			options.Urls.Add( "http://+:" + PORT );

			m_disposeHandle = WebApp.Start( options, OwinStartup );

		}
Exemple #12
0
        public static void Main(string[] args)
        {
            var evt = new ManualResetEvent (false);

            var basePath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", ".."));
            Console.WriteLine(basePath);
            Console.Title = "IdentityServer3 SelfHost";

            Log.Logger = new LoggerConfiguration()
                .WriteTo
                .LiterateConsole(outputTemplate: "{Timestamp:HH:MM} [{Level}] ({Name:l}){NewLine} {Message}{NewLine}{Exception}")
                .CreateLogger();
            var port = ((args != null && args.Length > 1) ? args [0] : null) ?? Environment.GetEnvironmentVariable ("PORT") ?? "44002";
            var url = string.Format ("http://+:{0}/", port);
            var startOptions = new StartOptions();
            startOptions.Urls.Add(url);
            using (WebApp.Start(url, (appBuilder) =>
            {
                new Startup(basePath).Configuration(appBuilder);
            }))
            {
                Console.WriteLine("\n\nServer listening at {0}. Press ctrl+c to stop", url);
                Console.CancelKeyPress += (sender, e) => evt.Set ();
                evt.WaitOne ();
                Console.WriteLine ("Exited");
            }
        }
        public void Start()
        {
            var siteUrl = Settings.Default.SiteUrl;
            var portNumber = Settings.Default.PortNumber;

            var uri = string.Format("http://*:{0}{1}", portNumber, siteUrl);

            SmartDBEntities.SetConnection(Settings.Default.DBServer, Settings.Default.DBName,
                   Settings.Default.DBUser,
                   Encryption.Decrypt(Settings.Default.DBPassword));

            Program.ProcessLog.Write("Database connection string to " + Settings.Default.DBServer + " has successfully been made.");

            if (SmartDBEntities.IsDBAvailable)
                Program.ProcessLog.Write("Database connection  " + Settings.Default.DBServer + " has successfully been made.");
            else
                Program.ProcessLog.Write("Database connection  " + Settings.Default.DBServer + " has failed.");

            StartOptions options = new StartOptions();
            options.Urls.Add(uri);
            Program.ProcessLog.Write("connection has been added to uri.");
            options.Urls.Add("http://localhost:14000");
            Program.ProcessLog.Write("14000 has been added");

            try
            {
                host = WebApp.Start<Startup>(options);

            }
            catch (Exception ex)
            {
                Program.ProcessLog.Write(ex.ToString());
            }
            Program.ProcessLog.Write("Service has been initialised");
        }
		static void Main(string[] args)
		{
			var url = "http://+:8080";

			var options = new StartOptions
			{
				ServerFactory = "Nowin",
				Port = 8080
			};

			/*
			var loggerConfig = new LoggerConfiguration()
				.MinimumLevel.Debug()
				.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(NuSearchConfiguration.CreateUri(9200))
				{
					AutoRegisterTemplate = true,
					Period = TimeSpan.FromSeconds(2)
				});

			Serilog.Log.Logger = loggerConfig.CreateLogger();
			 */

			using (WebApp.Start<Bootstrap>(options))
			{
				Console.WriteLine("Running on {0}", url);
				Console.WriteLine("Press enter to exit");
				Console.ReadLine();
			}


		}
Exemple #15
0
        private void Configure(Action<IAppBuilder> startup, StartOptions options = null)
        {
            if (startup == null)
            {
                throw new ArgumentNullException("startup");
            }

            options = options ?? new StartOptions();
            if (string.IsNullOrWhiteSpace(options.AppStartup))
            {
                // Populate AppStartup for use in host.AppName
                options.AppStartup = startup.Method.ReflectedType.FullName;
            }

            var testServerFactory = new OwinEmbeddedServerFactory();
            IServiceProvider services = ServicesFactory.Create(
                serviceProvider => serviceProvider.AddInstance<ITraceOutputFactory>(new NullTraceOutputFactory())
                );
            var engine = services.GetService<IHostingEngine>();
            var context = new StartContext(options)
            {
                ServerFactory = new ServerFactoryAdapter(testServerFactory),
                Startup = startup
            };
            _started = engine.Start(context);
            _next = testServerFactory.Invoke;
        }
        public void Start()
        {
            var siteUrl = Settings.Default.SiteUrl;
            var portNumber = Settings.Default.PortNumber;

            var uri = string.Format("http://*:{0}{1}", portNumber, siteUrl);

            const string url = "http://localhost:10000";
            StartOptions options = new StartOptions();
            options.Urls.Add(string.Format("http://{0}:10000", Environment.MachineName));
            options.Urls.Add("http://localhost:10000/");
            options.Urls.Add(uri);

            host = WebApp.Start<Startup>(options);

            var hubConnection = new HubConnection(url);
            var hubProxy = hubConnection.CreateHubProxy("MyHub");

            hubConnection.Start().ContinueWith(task =>
            {

            }).Wait();

            var timer = new Timer(x =>
            {
                if (ConnectionMapping.Count <= 1) return;

                hubProxy.Invoke("Send").Wait();
            }, null, 0, 2000);
        }
Exemple #17
0
        public bool Start(HostControl hostControl)
        {
            if (string.IsNullOrEmpty(TestConfig.Instance.ServerUrl))
            {
                throw new Exception("Url为空 无法启动服务器");
            }

            Pioneer.WxSdk.SdkSetup.MessageTokenGetter = (dic) =>
            {

                PublicAccount pa = new PublicAccount();

                pa.EncryptionKey = TestConfig.Instance.EncryptionKey;
                pa.MessageToken = TestConfig.Instance.Token;
                pa.AppId = TestConfig.Instance.AppId;
                return pa;
            };

            SdkSetup.RegisterListener(new WxSdk.Message.DefaultMessageListener());

            StartOptions so = new StartOptions();
            so.Urls.Add(TestConfig.Instance.ServerUrl);

            innerHost = WebApp.Start(so, builder =>
            {
                builder.Use(new MessageModel().ProcessRequest);
            });

            logger.Info("监听地址:" + TestConfig.Instance.ServerUrl);

            logger.Info("启动成功");

            return true;
        }
Exemple #18
0
        public const double SizeCapForDownload = 51200; // 50 KB size limit

        public static IDisposable Start(Dev2Endpoint[] endpoints)
        {
            // Make long polling connections wait a maximum of 110 seconds for a
            // response. When that time expires, trigger a timeout command and
            // make the client reconnect.
            GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(180);

            // Wait a maximum of 30 seconds after a transport connection is lost
            // before raising the Disconnected event to terminate the SignalR connection.
            GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromSeconds(30);

            // For transports other than long polling, send a keepalive packet every
            // 10 seconds. 
            // This value must be no more than 1/3 of the DisconnectTimeout value.
            GlobalHost.Configuration.KeepAlive = TimeSpan.FromSeconds(10);

            GlobalHost.Configuration.DefaultMessageBufferSize = 1000;
            GlobalHost.Configuration.MaxIncomingWebSocketMessageSize = null;
            GlobalHost.Configuration.TransportConnectTimeout = TimeSpan.FromSeconds(10);
            
            var startOptions = new StartOptions();
            
            foreach(var endpoint in endpoints)
            {
                startOptions.Urls.Add(endpoint.Url);
            }
            return WebApp.Start<WebServerStartup>(startOptions);
        }
Exemple #19
0
        static void Main(string[] args)
        {
            var address = ConfigurationManager.AppSettings["useSecurePort"] == "true"
                                   ? ConfigurationManager.AppSettings["secureAddress"]
                                   : ConfigurationManager.AppSettings["unsecureAddress"];

            var startOpt = new StartOptions(address)
            {
                ServerFactory = typeof(SocketServerFactory).AssemblyQualifiedName,
            };

            try
            {
                // Start OWIN host 
                using (WebApp.Start<Startup>(startOpt))
                {
                    Console.WriteLine("Press Enter to stop the server");
                    Console.WriteLine("The following URLs could be used for testing:");
                    Console.WriteLine(address + "simpleTest.txt");
                    Console.WriteLine(address + "10mbTest.txt");
                    
                    Console.ReadLine(); 
                } 
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Error => {0} : {1}", 
                    ex.Message, 
                    (ex.InnerException != null) ? ex.InnerException.Message : String.Empty));
               	Console.ReadLine(); 
           
            }
        }
Exemple #20
0
		private void _SetServerEnableState(bool value, int port)
		{
			if (value)
			{
				StopServer();
				var options = new StartOptions {ServerFactory = "Nowin", Port = port}; //use the Nowin _server to listen for connections
				try
				{
					_server = WebApp.Start<Startup>(options);
				}
				catch (Exception ex)
				{
					Logging.Error("Unable to start web _server.", ex);
					return;
				}
				if (LiveContext == null)
				{
					LiveContext = VixenSystem.Contexts.CreateLiveContext("Web Server");
					LiveContext.Start();
				}
				
			}
			else
			{
				StopServer();
				if (LiveContext != null)
				{
					//We are the only current consumer of LiveContext, so shut it off when we are done.
					VixenSystem.Contexts.ReleaseContext(LiveContext);
					LiveContext = null;
				}
			}
		}
        public void Start()
        {
            var siteUrl = Settings.Default.SiteUrl;
            var portNumber = Settings.Default.PortNumber;
            var uri = string.Format("http://*:{0}{1}", portNumber, siteUrl);

            SmartDBEntities.SetConnection(Settings.Default.DBServer, Settings.Default.DBName,
                   Settings.Default.DBUser,
                   Encryption.Decrypt(Settings.Default.DBPassword));

            SmartFlowEntities.SetConnection("172.17.61.10", "SmartFlowFactory", "sa", "mha405741");
            Program.ProcessLog.Write("Database connection string to " + Settings.Default.DBServer + " has successfully been made.");

            if (SmartDBEntities.IsDBAvailable)
                Program.ProcessLog.Write("Database connection  " + Settings.Default.DBServer + " has successfully been made.");
            else
                Program.ProcessLog.Write("Database connection  " + Settings.Default.DBServer + " has failed.");

            StartOptions options = new StartOptions();


#if DEBUG
            options.Urls.Add(string.Format("http://{0}:10000", Environment.MachineName));
            options.Urls.Add("http://+:10000/");
#endif
            options.Urls.Add(uri);
            host = WebApp.Start<Startup>(options);
        }
Exemple #22
0
        protected override void OnStart(string[] args)
        {
            base.OnStart(args);

            startup = new SelfHostStartup(settings);

            var options = new StartOptions();

            if (!string.IsNullOrWhiteSpace(settings.ServerFactory))
            {
                options.ServerFactory = settings.ServerFactory;
                Log.Info(m => m("Using ServerFactory {0}", options.ServerFactory));
            };

            var urls = settings.Urls.ToArray();
            if (urls.Any())
            {
                options.Urls.AddRange(urls);
            }
            else
            {
                options.Port = settings.Port;
                urls = new[] {"http://*:" + options.Port + "/"};
            }

            server = WebApp.Start(options, startup.Configuration);

            Log.Info(m => m("Listening for HTTP requests on address(es): {0}", string.Join(", ", urls)));
        }
Exemple #23
0
 static void Main()
 {
     #if !RELEASE
     int port = 54537;
     string options = $"http://localhost:{port}/";
     #else
     int port = 9000;
     StartOptions options = new StartOptions($"http://+:{port}")
     {
         ServerFactory = "Microsoft.Owin.Host.HttpListener"
     };
     #endif
     using (WebApp.Start<ApiStartup>(options))
     {
         Console.WriteLine("Server started");
         Console.WriteLine($"\tMachine name: {Environment.MachineName}");
         Console.WriteLine($"\tPort: {port}");
     #if DEBUG
         HttpClient client = new HttpClient();
         var res = client.GetAsync($"http://localhost:{port}/api/tag").Result;
         Console.WriteLine($"{res.Content.ReadAsStringAsync().Result}");
     #endif
         Console.WriteLine("Press ENTER to stop server...");
         Console.ReadLine();
     }
 }
Exemple #24
0
        static void Main()
        {
            string baseAddress = "http://localhost:9000/";

            var so = new StartOptions(baseAddress);
            var tl = new TextWriterTraceListenerCustomOutput(Console.Out);

            // Start OWIN host
            using (var srv = WebApp.Start<Startup>(options:so))
            {
                //var traceListener = Trace.Listeners.OfType<TextWriterTraceListener>().FirstOrDefault();
                //traceListener.TraceOutputOptions = TraceOptions.None;

                Trace.Listeners.Remove("HostingTraceListener");
                Trace.Listeners.Add(tl);
                //Trace.Listeners.OfType<HostingTraceListener>

                // Create HttpCient and make a request to api/values
                //HttpClient client = new HttpClient();

                //var response = client.GetAsync(baseAddress + "/api/rc/restaurants").Result;

                //Console.WriteLine(response);
                //Console.WriteLine(response.Content.ReadAsStringAsync().Result);
                Console.WriteLine();
                Console.WriteLine("Press ENTER to stop the server and close app...");
                Console.ReadLine();
            }
        }
Exemple #25
0
        public void Start()
        {
            var siteUrl = Settings.Default.SiteUrl;
            var portNumber = Settings.Default.PortNumber;
            var uri = string.Format("http://*:{0}{1}", portNumber, siteUrl);

            //SmartDBEntities.SetConnection(Settings.Default.DBServer, Settings.Default.DBName,
            //       Settings.Default.DBUser,
            //       Encryption.Decrypt(Settings.Default.DBPassword));

            SupportCallManagerEntities.SetConnection(@"192.168.0.11\dev", "SupportCallManager",
                  Settings.Default.DBUser,
                  Encryption.Decrypt(Settings.Default.DBPassword));

            Program.ProcessLog.Write("Database connection string to " + Settings.Default.DBServer + " has successfully been made.");

            //if (SupportCallManagerEntities.IsDBAvailable)
            //    Program.ProcessLog.Write("Database connection  " + Settings.Default.DBServer + " has successfully been made.");
            //else
            //    Program.ProcessLog.Write("Database connection  " + Settings.Default.DBServer + " has failed.");

            StartOptions options = new StartOptions();


#if DEBUG
            options.Urls.Add(string.Format("http://{0}:10000", Environment.MachineName));
            options.Urls.Add("http://+:10000/");
            options.Urls.Add("http://192.168.0.146:10000/");
#endif
            options.Urls.Add(uri);
            host = WebApp.Start<Startup>(options);
        }
Exemple #26
0
        static void Main(string[] args)
        {
            var address = ConfigurationManager.AppSettings["useSecurePort"] == "true"
                                   ? "https://localhost:8443/"
                                   : "http://localhost:8080/";

            var startOpt = new StartOptions(address)
            {
                ServerFactory = typeof(SocketServerFactory).AssemblyQualifiedName,
            };

            try
            {
                // Start OWIN host
                using (WebApp.Start<Startup>(startOpt))
                {
                    Console.WriteLine("Press Enter to stop the server");

                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Error => {0} : {1}",
                    ex.Message,
                    (ex.InnerException != null) ? ex.InnerException.Message : String.Empty));
               	Console.ReadLine();

            }
        }
Exemple #27
0
        public static void Start(SnowSettings settings)
        {
            Console.WriteLine("Sandra.Snow : Starting up a testing server");

            var options = new StartOptions
            {
                ServerFactory = "Nowin",
                Port = 5498
            };

            Startup.Settings = settings;

            using (WebApp.Start<Startup>(options))
            {
                Console.WriteLine("Sandra.Snow : Listening on http://locahost:5498/");
                Console.WriteLine(" - attempting to open your browser...");
                
                Process.Start("http://localhost:5498/");

                Console.WriteLine(" - press any to quit the testing server...");
                Console.ReadKey();
                Console.WriteLine("");
                Console.WriteLine("Sandra.Snow : Exited testing server");
            }
        }
Exemple #28
0
        public static void Listen(string baseAddress)
        {
            //// Need lots of outgoing connections and hang on to them
            //ServicePointManager.DefaultConnectionLimit = 20;
            //ServicePointManager.MaxServicePointIdleTime = 10000;
            ////send packets as soon as you get them
            //ServicePointManager.UseNagleAlgorithm = false;
            ////send both header and body together
            //ServicePointManager.Expect100Continue = false;

            try
            {
                //var config = new HttpSelfHostConfiguration(baseAddress)
                //{
                //    HostNameComparisonMode = HostNameComparisonMode.StrongWildcard,
                //    IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always,
                //    TransferMode = System.ServiceModel.TransferMode.Streamed
                //};

                // Start OWIN host
                StartOptions options = new StartOptions(baseAddress);
                IDisposable app = WebApp.Start<Startup>(options);
                Trace.TraceInformation("Listening on:" + baseAddress);
                apps.Add(app);
            }
            catch (Exception ex)
            {
                Trace.TraceInformation(ex.Message + ':' + ex.InnerException.Message);
            }
        }
Exemple #29
0
        public static void Open(params string[] hostUrls)
        {
            try
            {
                if (_CloseOWin == null)
                {
                    // Start OWIN host
                    StartOptions so = new StartOptions();
                    foreach (string s in hostUrls)
                    {
                        so.Urls.Add(s);
                    }
                    _CloseOWin = WebApp.Start<SNStartup>(so);
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException is System.Net.HttpListenerException)
                {
                    throw new Exception("监听IP有错误");
                }

                if (_CloseOWin != null)
                {
                    _CloseOWin.Dispose();//必须
                    _CloseOWin = null;//必须
                }

                throw;
            }
        }
        static void Main(string[] args)
        {
            StartOptions options = new StartOptions();
            options.Urls.Add(webAddress);
            options.Urls.Add(string.Format("http://{0}:{1}/", Environment.MachineName, port));
            Console.WriteLine("Press enter to stop service");
            Log.Logging.Info("DeviceManager|Starting service|{0}", webAddress);

            using (WebApp.Start<Startup>(webAddress))
            {
                Log.Logging.Info("DeviceManager|Service started|{0}", webAddress);

                var scannerRepository = new DeviceRepository();
                var deviceConnectionManager = new DeviceConnectionManager(scannerRepository);

                deviceConnectionManager.InitializeConfig();
                deviceConnectionManager.ConnectAll();
                var input = Console.ReadLine();

                Log.Logging.Info("DeviceManager|Stopping service|{0}", webAddress);
                Log.Logging.Info("DeviceManager|Disposing|Please wait");
                deviceConnectionManager.DisposeAll();
            }

            Log.Logging.Info("DeviceManager|Service stopped|{0}", webAddress);

        }
 /// <summary>
 /// Start a web app with the given options, using defaults for items not specified.
 /// </summary>
 /// <returns>An IDisposible instance that can be called to shut down the web app.</returns>
 public static IDisposable Start(StartOptions options)
 {
     return(Start(BuildServices(options), options));
 }
        private static IDisposable StartImplementation(IServiceProvider services, StartOptions options)
        {
            var starter = services.GetService <IHostingStarter>();

            return(starter.Start(options));
        }
 /// <summary>
 /// Start a web app using the given service provider, settings, and entry point, using defaults for items not specified.
 /// </summary>
 /// <returns>An IDisposible instance that can be called to shut down the web app.</returns>
 public static IDisposable Start(IServiceProvider services, StartOptions options, Action <IAppBuilder> startup)
 {
     return(StartImplementation(services, options, startup));
 }
 /// <summary>
 /// Start a web app with the given service provider and options, using defaults for items not specified.
 /// </summary>
 /// <returns>An IDisposible instance that can be called to shut down the web app.</returns>
 public static IDisposable Start(IServiceProvider services, StartOptions options)
 {
     return(StartImplementation(services, options));
 }
 /// <summary>
 /// Start a web app using the given settings and entry point, using defaults for items not specified.
 /// </summary>
 /// <returns>An IDisposible instance that can be called to shut down the web app.</returns>
 public static IDisposable Start(StartOptions options, Action <IAppBuilder> startup)
 {
     return(Start(BuildServices(options), options, startup));
 }