public static async Task Main(string[] args)
        {
            Console.WriteLine($"{PlatformServices.Default.Application.ApplicationName} version {PlatformServices.Default.Application.ApplicationVersion}");
#if DEBUG
            Console.WriteLine("Is DEBUG");
#else
            Console.WriteLine("Is RELEASE");
#endif
            Console.WriteLine($"ENV_INFO: {EnvInfo}");

            try
            {
                var webHost = new WebHostBuilder()
                              .UseKestrel()
                              .UseUrls("http://*:5000")
                              .UseContentRoot(Directory.GetCurrentDirectory())
                              .UseStartup <Startup>()
                              .UseApplicationInsights()
                              .Build();

                await webHost.RunAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Fatal error:");
                Console.WriteLine(ex);

                // Lets devops to see startup error in console between restarts in the Kubernetes
                var delay = TimeSpan.FromMinutes(1);

                Console.WriteLine();
                Console.WriteLine($"Process will be terminated in {delay}. Press any key to terminate immediately.");

                await Task.WhenAny(
                    Task.Delay(delay),
                    Task.Run(() =>
                {
                    Console.ReadKey(true);
                }));
            }

            Console.WriteLine("Terminated");
        }
Пример #2
0
            public void Run(CancellationToken cancellationToken)
            {
                var config = new ConfigurationBuilder()
                             .AddEnvironmentVariables(prefix: "ASPNETCORE_")
                             .Build();

                var host = new WebHostBuilder()
                           .UseConfiguration(config)
                           .UseKestrel()
                           .UseUrls("http://localhost:9090")
                           .UseContentRoot(Directory.GetCurrentDirectory())
                           .UseStartup <Startup>()
                           .ConfigureLogging((ctx, logging) => ConfigureLogging(logging))
                           .Build();

                Logger.LogTrace("test");
                Logger.LogCritical("test");
                host.RunAsync(cancellationToken).GetAwaiter().GetResult();
            }
        public static async Task Main(string[] args)
        {
            Console.WriteLine($"{PlatformServices.Default.Application.ApplicationName} version {PlatformServices.Default.Application.ApplicationVersion}");
            Console.WriteLine($"Is {(Constants.IsDebug ? "DEBUG" : "RELEASE")}");

            if (!string.IsNullOrEmpty(EnvInfo))
            {
                Console.WriteLine($"ENV_INFO: {EnvInfo}");
            }

            try
            {
                var host = new WebHostBuilder()
                           .UseKestrel()
                           .UseUrls("http://*:5000")
                           .UseContentRoot(Directory.GetCurrentDirectory())
                           .UseStartup <Startup>()
                           .UseApplicationInsights()
                           .Build();

                await host.RunAsync();
            }
            catch (Exception ex)
            {
                var delay = TimeSpan.FromMinutes(1);

                Console.WriteLine("Fatal error:");
                Console.WriteLine();
                Console.WriteLine(ex);
                Console.WriteLine();
                Console.WriteLine($"Process will be terminated in {delay}. Press any key to terminate immediately.");
                Console.WriteLine();

                await Task.WhenAny
                (
                    Task.Delay(delay),
                    Task.Run(() => { Console.ReadKey(true); })
                );
            }

            Console.WriteLine("Terminated");
        }
Пример #4
0
            public async Task Run(CancellationToken cancellationToken)
            {
                var config = new ConfigurationBuilder()
                             .AddEnvironmentVariables(prefix: "ASPNETCORE_")
                             .Build();

                var host = new WebHostBuilder()
                           .UseConfiguration(config)
                           .UseKestrel()
                           .UseUrls("http://localhost:9090")
                           .UseContentRoot(Directory.GetCurrentDirectory())
                           .ConfigureServices(services => {
                    services.AddTransient(w => _asyncProcessor);
                })
                           .UseStartup <Startup>()
                           .ConfigureLogging((ctx, logging) => ConfigureLogging(logging))
                           .Build();

                await host.RunAsync(cancellationToken);
            }
Пример #5
0
        //public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        //	WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();

        static async Task Main(string[] args)
        {
            var host = new WebHostBuilder()
                       .UseKestrel()
                       //.UseLibuv()
                       .UseSockets()

                       /*.UseLinuxTransport(async opts =>
                        * {
                        *      await Console.Out.WriteLineAsync("Using Linux Transport");
                        * })*/
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       //.UseIISIntegration()
                       .UseStartup <Startup>()
                       .Build();

            await host.RunAsync();

            //await CreateWebHostBuilder(args).Build().RunAsync();
        }
Пример #6
0
        public async static Task Main(string[] args)
        {
            var host = new WebHostBuilder()
                       .ConfigureLogging((hostingEnvironment, logging) => {
                logging.AddDebug();
                logging.AddConsole();
            })
                       .UseKestrel(options =>
            {
                options.Listen(IPAddress.Loopback, 6379, connectionBuilder => {
                    connectionBuilder.UseConnectionLogging();
                    connectionBuilder.UseConnectionHandler <RespHandler>();
                });
            })
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseStartup <Startup>()
                       .Build();

            await host.RunAsync();
        }
Пример #7
0
        public static async Task Main(string[] args)
        {
            Console.WriteLine($"{PlatformServices.Default.Application.ApplicationName} version {PlatformServices.Default.Application.ApplicationVersion}");
            Console.WriteLine($"ENV_INFO: {EnvInfo}");

            try
            {
                var host = new WebHostBuilder()
                           .UseKestrel()
                           .UseContentRoot(Directory.GetCurrentDirectory())
                           .ConfigureLogging((hostingContext, logging) =>
                {
                    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                })
                           .UseStartup <Startup>()
                           .UseApplicationInsights()
                           .Build();

                await host.RunAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Fatal error:");
                Console.WriteLine(ex);

                // Lets devops to see startup error in console between restarts in the Kubernetes
                var delay = TimeSpan.FromMinutes(1);

                Console.WriteLine();
                Console.WriteLine($"Process will be terminated in {delay}. Press any key to terminate immediately.");

                await Task.WhenAny(
                    Task.Delay(delay),
                    Task.Run(() =>
                {
                    Console.ReadKey(true);
                }));
            }

            Console.WriteLine("Terminated");
        }
        private static async Task Main(string[] args)
        {
            try
            {
                var host = new WebHostBuilder()
                           .UseKestrel()
                           .UseUrls("http://*:5000")
                           .UseContentRoot(Directory.GetCurrentDirectory())
                           .UseStartup <Startup>()
                           .UseApplicationInsights()
                           .Build();

                await host.RunAsync(); // returns on Ctrl+C

                Console.WriteLine("The service is stopped.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
 private async Task RunServer()
 {
     using (var streamStore = _factory.Create())
         using (var host = new WebHostBuilder()
                           .SuppressStatusMessages(true)
                           .UseKestrel()
                           .UseStartup(new SqlStreamStoreServerStartup(
                                           streamStore,
                                           new SqlStreamStoreMiddlewareOptions
         {
             UseCanonicalUrls = _configuration.UseCanonicalUris,
             ServerAssembly = typeof(SqlStreamStoreServer).Assembly
         }))
                           .UseSerilog()
                           .Build())
         {
             await Task.WhenAll(
                 host.RunAsync(_cts.Token),
                 host.WaitForShutdownAsync(_cts.Token));
         }
 }
Пример #10
0
        public static async Task <int> RunAsync <TStartup>()
            where TStartup : class
        {
            var config = Configuration.GetConfiguration();

            LogHelper.Logger = new SerilogLogger();

            try
            {
                LogHelper.Info("Starting WebHost...");

                var host = new WebHostBuilder()
                           .UseKestrel()
                           .UseContentRoot(Directory.GetCurrentDirectory())
                           .ConfigureAppConfiguration((hostingContext, configurationBuilder) =>
                {
                    var env             = hostingContext.HostingEnvironment;
                    env.EnvironmentName = Configuration.Stage.Get().GetDescription();

                    configurationBuilder.AddConfiguration(config);
                })
                           .UseStartup <TStartup>()
                           .Build();

                await host.RunAsync();

                LogHelper.Info("Exiting WebHost...");

                return(0);
            }
            catch (Exception ex)
            {
                LogHelper.Error("WebHost terminated unexpectedly.", ex);

#if DEBUG
                Console.ReadLine();
#endif
                return(1);
            }
        }
Пример #11
0
        public static Task Main(string[] args)
        {
            string configPath = "config.yaml";

            TryCreateConfig(configPath);

            var config = new ConfigurationBuilder()
                         .SetBasePath(Directory.GetCurrentDirectory())
                         .AddYamlFile(configPath, false)
                         .AddEnvironmentVariables()
                         .Build();

            var host = new WebHostBuilder()
                       .UseConfiguration(config)
                       .UseUrls(config.GetListenUrl())
                       .UseKestrel()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseStartup <Startup>()
                       .Build();

            return(host.RunAsync());
        }
Пример #12
0
        static void Main(string[] args)
        {
            using (var context = new CateringsDbContext())
            {
                // Create database
                context.Database.EnsureCreated();



                /*inserimento*//*
                *  context.Students.Add(s);
                *  context.Students.Add(n);
                *  context.Students.Add(f);
                *  context.Corsi.Add(cor);
                *  context.SaveChanges();
                *
                *  /*cancellazione*/
                /*var a=context.Students.FirstOrDefault(x => x.Name == "Giovanni");
                 * context.Students.Remove(a);
                 * context.SaveChanges();
                 *
                 * /*update*/
                /*var b= context.Students.FirstOrDefault(x => x.Name == "Piero");
                 * b.DateOfBirth = new DateTime(2017, 2, 1);
                 * context.Students.Update(b);
                 * context.SaveChanges();*/
            }
            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseStartup <Startup>()
                       .Build();

            Task restService = host.RunAsync();

            //System.Diagnostics.Process.Start("chrome.exe", "http://localhost/netcoreapp2.0/corsoing/");
            // System.Diagnostics.Process.Start("cmd", "/C start http://localhost/netcoreapp2.0/corsoing/");
            restService.Wait();
            Console.ReadKey();
        }
Пример #13
0
        public static int Main(string[] args)
        {
            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseStartup <Startup>()
                       .UseUrls("http://*:80")
                       .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConsole();
                logging.SetMinimumLevel(LogLevel.Warning);
            })
                       .Build();

            var task = host.RunAsync();

            PublishDevice();

            task.GetAwaiter().GetResult();

            return(0);
        }
Пример #14
0
        public static async Task MainAsync()
        {
            //Connect to database
            conn = new DeltaConnection(config.database_config, "dynamic-tiles-streamable", 0, 0);
            await conn.Connect();

            //Set up builder servers
            builders = new BuilderNetworking(conn, new byte[32], config.builder_port);
            builders.StartServer();

            //Set up web server
            var host = new WebHostBuilder()
                       .UseKestrel(options =>
            {
                IPAddress addr = IPAddress.Any;
                options.Listen(addr, config.port);
            })
                       .UseStartup <Program>()
                       .Build();

            await host.RunAsync();
        }
Пример #15
0
        private static async Task Main(string[] args)
        {
            //un services
            var magicOnionHost = MagicOnionHost.CreateDefaultBuilder()
                                 .UseMagicOnion(
                new MagicOnionOptions(true),
                //new ServerPort("127.0.0.1", 12345, ServerCredentials.Insecure)
                new ServerPort("0.0.0.0", 12345, ServerCredentials.Insecure)
                )
                                 .UseConsoleLifetime()
                                 .Build();

            // NuGet: Microsoft.AspNetCore.Server.Kestrel
            var webHost = new WebHostBuilder()
                          .ConfigureServices(
                collection =>
            {
                collection.AddSingleton(
                    magicOnionHost.Services.GetService <MagicOnionHostedServiceDefinition>().ServiceDefinition
                    );
                // add the following codes
                collection.Configure <KestrelServerOptions>(options => { options.AllowSynchronousIO = true; });
                collection.Configure <MagicOnionHostingOptions>(options =>
                {
                    options.ChannelOptions.MaxReceiveMessageLength = 1024 * 1024 * 1024;
                    options.ChannelOptions.MaxSendMessageLength    = 1024 * 1024 * 1024;
                });
            }
                )
                          .UseKestrel()
                          .UseContentRoot(Directory.GetCurrentDirectory())
                          .UseStartup <Startup>()
                          .UseUrls("http://0.0.0.0:9999")
                          .Build();
            //webHost.Run();
            // Run and wait both.
            await Task.WhenAll(webHost.RunAsync(), magicOnionHost.RunAsync());
        }
Пример #16
0
        static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseStartup <Startup>()
                       .Build();

            Task restService = host.RunAsync();


            using (var context = new AutoConcessonarieDbContext())
            {
                // Create database
                context.Database.EnsureCreated();
                //Fatto per la prima volta

                /*Cliente c = new Cliente()
                 * {
                 *  Nome = "Nome",
                 *  DataNascita = new DateTime(2012, 1, 1),
                 *  CF="SVV677",
                 *  Cognome="Cognome",
                 *  Email="*****@*****.**",
                 *  Indirizzo="indirizzo",
                 *  Sesso="x",
                 *  Telefono=100000
                 * };
                 *
                 * context.Clienti.Add(c);
                 *
                 * context.SaveChanges();*/
            }


            //System.Diagnostics.Process.Start("chrome.exe", "http://localhost/netcoreapp2.0/corsoing/");
            //System.Diagnostics.Process.Start("cmd", "/C start http://localhost/netcoreapp2.0/corsoing/");
            restService.Wait();
        }
Пример #17
0
        private async Task <int> Run()
        {
            try
            {
                using (var streamStore = await SqlStreamStoreFactory.Create())
                    using (var host = new WebHostBuilder()
                                      .UseKestrel()
                                      .UseStartup(new DevServerStartup(streamStore, new SqlStreamStoreMiddlewareOptions
                    {
                        UseCanonicalUrls = UseCanonicalUrls,
                        ServerAssembly = typeof(Program).Assembly
                    }))
                                      .UseSerilog()
                                      .Build())
                    {
                        var serverTask = host.RunAsync(_cts.Token);

                        if (Interactive)
                        {
                            Log.Warning("Running interactively.");
                            DisplayMenu(streamStore);
                        }

                        await serverTask;

                        return(0);
                    }
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly.");
                return(1);
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Пример #18
0
        private static async Task Main(string[] args)
        {
            // Main gRPC Host
            var magicOnionHost = MagicOnionHost.CreateDefaultBuilder()
                                 .UseMagicOnion()
                                 .ConfigureServices((context, collection) =>
            {
                // afe
            })
                                 .Build();

            var swaggerWeb = new WebHostBuilder()
                             .ConfigureServices(collection =>
            {
                // Add MagicOnionServiceDefinition for reference from Startup.
                collection.AddSingleton(magicOnionHost.Services.GetService <MagicOnionHostedServiceDefinition>()
                                        .ServiceDefinition);
            })
                             .UseKestrel()
                             .Build();

            await Task.WhenAll(magicOnionHost.RunAsync(), swaggerWeb.RunAsync());
        }
Пример #19
0
        internal static void Main(string[] args)
        {
            using (IWebHost webHost = new WebHostBuilder()
                                      // Use the Kestrel server, listen on port 3000
                                      .UseKestrel(o => o.ListenAnyIP(3000))
                                      .UseSetting(WebHostDefaults.SuppressStatusMessagesKey, "True")
                                      // Set the internal web host logging
                                      .ConfigureLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Debug))
                                      // Add MVC service and logging service to make logging dependency injection available to the MVC controllers
                                      .ConfigureServices(s => s.AddLogging().AddMvc())
                                      // Add MVC to the request pipeline
                                      .Configure(b => b.UseMvc())
                                      .Build())
            {
                // Startup

                // Run the web host, the resulting task completes when the web host is stopped
                System.Threading.Tasks.Task webHostRunTask = webHost.RunAsync();

                // Running
                while (!sShutdown)
                {
                    // Do other stuff with the main thread
                    if (!sShutdown)
                    {
                        Thread.Sleep(1000);
                    }
                }
                // Shutdown

                // On shutdown, stop the web host gracefully
                webHost.StopAsync();

                // And wait for the task to complete that denotes it has shutdown
                webHostRunTask.Wait();
            }
        }
Пример #20
0
        static async Task Main(string[] args)
        {
            using (var host = new WebHostBuilder()
                              .UseContentRoot(Directory.GetCurrentDirectory())
                              .UseKestrel()
                              .ConfigureServices(services =>
            {
                services.AddMvc();

                services.AddAuthorization();

                services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryClients(Clients.Get())
                .AddInMemoryApiResources(Scopes.GetApiScopes())
                ;

                services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication(x =>
                {
                    x.Authority = "http://localhost:5000";
                    x.ApiName = "myapi";
                    x.RequireHttpsMetadata = false;
                });
            })
                              .Configure(app => app
                                         .UseStaticFiles()
                                         .UseIdentityServer()
                                         .UseAuthentication()
                                         .UseMvcWithDefaultRoute()
                                         )
                              .ConfigureLogging(builder => builder.AddConsole().SetMinimumLevel(LogLevel.Trace))
                              .Build())
            {
                await host.RunAsync();
            }
        }
Пример #21
0
        public static async Task Main(string[] args)
        {
            using var server = new WebHostBuilder()
                               .SuppressStatusMessages(true)
                               .UseKestrel(kestrelOptions => kestrelOptions.Listen(IPAddress.Any, 8080))
                               .Configure(appBuilder => appBuilder
                                          .UseRoutable(routable => routable
                                                       .AddRouting(new DefaultRouting(routable))
                                                       .OnError(new KestrelRouting(routable)
            {
                _ => _.DoAsync(async(context, request, response) => {
                    response.Status = 500;
                    response.ClearPendingWrites();
                    var logger = routable.GetApplicationServices().GetRequiredService <ILoggerFactory>().CreateLogger <Program>();
                    logger.LogError($"Request ({context.PlatformContext.TraceIdentifier}) error: {context.Error?.GetType()?.FullName} ({context.Error?.Message})", context.Error);
                })
            })
                                                       )
                                          )
                               .ConfigureLogging(logging => {
                logging.ClearProviders();
                // log to console. if this is undesired, remove this line.
                logging.AddConsole();
            })
                               .Build();

            // shutdown on user (^C / SIGINT) request.
            using var cancellationSource = new CancellationTokenSource();
            Console.CancelKeyPress      += (_, e) => {
                cancellationSource.Cancel();
                e.Cancel = true;
            };

            // run until cancelled.
            await server.RunAsync(cancellationSource.Token);
        }
Пример #22
0
        static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseStartup <Startup>()
                       .Build();

            Task restService = host.RunAsync();


            //using (var context = new GlobalDbContext())
            //{
            //    // create database
            //    context.Database.EnsureCreated();


            //}



            //System.Diagnostics.Process.Start("chrome.exe", "http://localhost/netcoreapp2.0/corsoing/");
            System.Diagnostics.Process.Start("cmd", "/C start http://localhost/netcoreapp2.0/corsoing/");
            restService.Wait();
        }
Пример #23
0
        public async Task RunAsync()
        {
            if (File.Exists("./config.json"))
            {
                await configuration.ImportAsync(
                    new JsonSerializationProvider(),
                    "./config.json");
            }

            await configuration.ExportAsync(
                new JsonSerializationProvider(),
                "./config.json");

            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseUrls("http://0.0.0.0:5000")
                       .Configure(
                app => app.Map("/submit", SubmissionHandler)
                .Map("/ping", PingHandler)
                )
                       .Build();

            await host.RunAsync();
        }
Пример #24
0
        private static async Task <int> Run(string url)
        {
            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseStartup <Startup>()
                       .UseUrls(url)
                       .Build();

            var hostTask = host.RunAsync();

            var processJobsCts  = new CancellationTokenSource();
            var processJobsTask = ProcessJobs(processJobsCts.Token);

            var completedTask = await Task.WhenAny(hostTask, processJobsTask);

            // Propagate exception (and exit process) if either task faulted
            await completedTask;

            // Host exited normally, so cancel job processor
            processJobsCts.Cancel();
            await processJobsTask;

            return(0);
        }
Пример #25
0
        public static async Task Main(string[] args)
        {
            var environment   = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
            var isDevelopment = "Development".Equals(environment, StringComparison.OrdinalIgnoreCase);

            var config = new ConfigurationBuilder()
                         .SetBasePath(Directory.GetCurrentDirectory())
                         .AddInMemoryCollection(new Dictionary <string, string> // add default settings, that will be overridden by commandline
            {
                { "Id", "Webapp" },
                { "Version", "1.0.0" },
                { "ClusterId", "rrod-cluster" },
                { "ServiceId", "rrod" }
            })
                         .AddCommandLine(args)
                         .AddJsonFile("Webapp.settings.json", optional: true, reloadOnChange: true)
                         .AddJsonFile($"Webapp.settings.{environment}.json", optional: true, reloadOnChange: true)
                         .AddJsonFile("/run/config/Webapp.settings.json", optional: true, reloadOnChange: true)
                         .AddDockerSecrets("/run/secrets", optional: true)
                         .AddUserSecrets <Program>(optional: true)
                         .AddEnvironmentVariables("RROD_")
                         .Build();

            var loggerFactory = new LoggerFactory()
                                .AddConsole(config.GetSection("Logging"))
                                .AddDebug();
            var logger = loggerFactory.CreateLogger <Program>();

            logger.LogWarning($"Starting Webapp in {environment} environment...");

            foreach (var provider in config.Providers)
            {
                logger.LogInformation($"Config Provider {provider.GetType().Name}: {provider.GetChildKeys(Enumerable.Empty<string>(), null).Count()} settings");
            }

            // ServicePointManager.CheckCertificateRevocationList = false;
            ServicePointManager.SecurityProtocol       = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            ServicePointManager.DefaultConnectionLimit = 20;

            int            attempt = 0;
            int            initializeAttemptsBeforeFailing = 7;
            IClusterClient clusterClient = null;

            while (true)
            {
                // Initialize orleans client
                clusterClient = new ClientBuilder()
                                .ConfigureServices((context, services) =>
                {
                    // services.AddOptions();
                    services.AddSingleton <ILoggerFactory>(loggerFactory);
                    // services.AddSingleton<IConfiguration>(config);
                    services.Configure <ClusterOptions>(config);
                })
                                .AddAzureQueueStreams <AzureQueueDataAdapterV2>("Default", builder => builder.Configure(options => options.ConnectionString = config.GetConnectionString("DataConnectionString")))
                                .ConfigureApplicationParts(parts =>
                {
                    parts.AddApplicationPart(typeof(ICounterGrain).Assembly).WithReferences();
                    parts.AddApplicationPart(typeof(AzureQueueDataAdapterV2).Assembly).WithReferences();
                })
                                .UseAzureStorageClustering(options => options.ConnectionString = config.GetConnectionString("DataConnectionString"))
                                .Build();

                try
                {
                    await clusterClient.Connect().ConfigureAwait(false);

                    logger.LogInformation("Client successfully connected to silo host");
                    break;
                }
                catch (OrleansException)
                {
                    attempt++;
                    logger.LogWarning($"Attempt {attempt} of {initializeAttemptsBeforeFailing} failed to initialize the Orleans client.");

                    if (clusterClient != null)
                    {
                        clusterClient.Dispose();
                        clusterClient = null;
                    }

                    if (attempt > initializeAttemptsBeforeFailing)
                    {
                        throw;
                    }

                    // Wait 4 seconds before retrying
                    await Task.Delay(TimeSpan.FromSeconds(4));
                }
            }

            var endpoints = config.GetSection("Http:Endpoints")
                            .GetChildren()
                            .ToDictionary(section => section.Key, section =>
            {
                var endpoint = new EndpointConfiguration();
                section.Bind(endpoint);
                return(endpoint);
            });

            // if so, start a listener to respond to Acme (Let's Encrypt) requests, using a response received via an Orleans Cache Grain
            var hasHttps   = endpoints.Any(endpoint => endpoint.Value.Scheme.Equals("https", StringComparison.InvariantCultureIgnoreCase));
            var needPort80 = endpoints.Any(endpoint => (endpoint.Value.Port ?? (endpoint.Value.Scheme.Equals("https", StringComparison.InvariantCultureIgnoreCase) ? 443 : 80)) == 80);
            var certs      = new Dictionary <string, X509Certificate2>();

            var acmeOptions = new AcmeOptions
            {
                AcmeSettings         = config.GetSection(nameof(AcmeSettings)).Get <AcmeSettings>(),
                GetChallengeResponse = async(challenge) =>
                {
                    var cacheGrain = clusterClient.GetGrain <ICacheGrain <string> >(challenge);
                    var response   = await cacheGrain.Get();

                    return(response.Value);
                },
                SetChallengeResponse = async(challenge, response) =>
                {
                    var cacheGrain = clusterClient.GetGrain <ICacheGrain <string> >(challenge);
                    await cacheGrain.Set(new Immutable <string>(response), TimeSpan.FromHours(2));
                },
                StoreCertificate = async(string domainName, byte[] certData) =>
                {
                    var certGrain = clusterClient.GetGrain <ICertGrain>(domainName);
                    await certGrain.UpdateCertificate(certData);
                },
                RetrieveCertificate = async(domainName) =>
                {
                    var certGrain = clusterClient.GetGrain <ICertGrain>(domainName);
                    var certData  = await certGrain.GetCertificate();

                    return(certData.Value);
                }
            };

            if (hasHttps)
            {
                logger.LogWarning($"At least one https endpoint is present. Initialize Acme endpoint.");

                var acmeHost = new WebHostBuilder()
                               .UseEnvironment(environment)
                               .UseConfiguration(config)
                               .ConfigureServices(services =>
                {
                    services.AddSingleton <IClusterClient>(clusterClient);
                    services.AddSingleton <ILoggerFactory>(loggerFactory);
                    services.Configure <AcmeSettings>(config.GetSection(nameof(AcmeSettings)));

                    // Register a certitificate manager, supplying methods to store and retreive certificates and acme challenge responses
                    services.AddAcmeCertificateManager(acmeOptions);
                })
                               // .UseUrls("http://*:80")
                               .PreferHostingUrls(false)
                               .UseKestrel(options => {
                    options.Listen(IPAddress.Any, 80);
                })
                               .Configure(app =>
                {
                    app.UseAcmeResponse();
                })
                               .Build();

                try
                {
                    await acmeHost.StartAsync().ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    logger.LogError("Error: can't start web listener for acme certificate renewal, probably the web address is in use by another process. Exception message is: " + e.Message);
                    logger.LogError("Ignoring noncritical error (stop W3SVC or Skype to fix this), continuing...");
                }

                var certificateManager = acmeHost.Services.GetRequiredService <ICertificateManager>();
                // var certificateManager = new AcmeCertificateManager(Options.Create(acmeOptions));
                foreach (var endpoint in endpoints)
                {
                    var  endpointConfig  = endpoint.Value;
                    bool isHttpsEndpoint = endpointConfig.Scheme.Equals("https", StringComparison.InvariantCultureIgnoreCase);
                    var  port            = endpointConfig.Port ?? (isHttpsEndpoint ? 443 : 80);

                    X509Certificate2 certificate = null;
                    if (isHttpsEndpoint)
                    {
                        try
                        {
                            var domains = new List <string> {
                                endpointConfig.Domain
                            }
                            .Concat(endpointConfig.Domains)
                            .Where(ep => !string.IsNullOrEmpty(ep))
                            .Distinct()
                            .ToArray();

                            logger.LogInformation($"Getting certificate for domain {domains.First()} on port {port}");

                            // Request a new certificate with Let's Encrypt and store it for next time
                            try
                            {
                                certificate = await certificateManager.GetCertificate(domains);
                            }
                            catch (Exception e)
                            {
                                logger.LogCritical(e, $"Exception getting certificate for domain {domains.First()}. PfxPassword configured incorrectly?");
                            }
                            if (certificate == null)
                            {
                                // It didn't work - create a temporary certificate so that we can still start with an untrusted certificate
                                logger.LogCritical($"Error getting certificate for domain {domains.First()} (endpoint '{endpoint.Key}'). Creating self-signed temporary certificate...");
                                certificate = CertHelper.BuildTlsSelfSignedServer(domains);
                            }
                            certs.Add(domains.First(), certificate);
                            logger.LogInformation($"Certificate for domain {domains.First()}: {certificate != null}");
                        }
                        catch (Exception e)
                        {
                            logger.LogCritical($"Kestrel startup: Exception getting certificate. {e.Message}");
                        }
                    }
                }
                if (needPort80)
                {
                    await acmeHost.StopAsync();
                }
            }

            var webHost = new WebHostBuilder()
                          .UseEnvironment(environment)
                          .UseConfiguration(config)
                          .ConfigureServices(services =>
            {
                // services.AddSingleton<IConfiguration>(config);
                services.AddSingleton <IClusterClient>(clusterClient);
                services.AddSingleton <ILoggerFactory>(loggerFactory);
                services.Configure <AcmeSettings>(config.GetSection(nameof(AcmeSettings)));
                services.AddAcmeCertificateManager(acmeOptions);
            })
                          .UseContentRoot(Directory.GetCurrentDirectory())
                          // .UseUrls(listenUrls.ToArray())
                          .PreferHostingUrls(false)
                          .Configure(app =>
            {
                app.UseAcmeResponse();
            })
                          .UseStartup <Startup>()
                          .UseKestrel(options =>
            {
                foreach (var endpoint in endpoints)
                {
                    var endpointConfig   = endpoint.Value;
                    bool isHttpsEndpoint = endpointConfig.Scheme.Equals("https", StringComparison.InvariantCultureIgnoreCase);
                    var port             = endpointConfig.Port ?? (isHttpsEndpoint ? 443 : 80);

                    var ipAddresses = new List <IPAddress>();
                    var hosts       = new List <string> {
                        endpointConfig.Host
                    }
                    .Concat(endpointConfig.Hosts)
                    .Where(ep => !string.IsNullOrEmpty(ep))
                    .Distinct();

                    foreach (var host in hosts)
                    {
                        if (host == "localhost")
                        {
                            ipAddresses.Add(IPAddress.IPv6Loopback);
                            ipAddresses.Add(IPAddress.Loopback);
                        }
                        else if (IPAddress.TryParse(host, out var address))
                        {
                            ipAddresses.Add(address);
                        }
                        else
                        {
                            logger.LogError($"Error parsing endpoint host: {host}");
                        }
                    }

                    foreach (var address in ipAddresses)
                    {
                        options.Listen(address, port, listenOptions =>
                        {
                            if (isHttpsEndpoint)
                            {
                                var domains = new List <string> {
                                    endpointConfig.Domain
                                }
                                .Concat(endpointConfig.Domains)
                                .Where(ep => !string.IsNullOrEmpty(ep))
                                .Distinct()
                                .ToArray();

                                if (certs.TryGetValue(domains.First(), out var certificate))
                                {
                                    logger.LogInformation($"Kestrel config: Listen on address {address.ToString()}:{port}, certificate {(certificate == null ? "NULL" : certificate.Subject.ToString())}");
                                    listenOptions.UseHttps(certificate);
                                    listenOptions.NoDelay = false;
                                    // listenOptions.UseConnectionLogging();
                                }
                                else
                                {
                                    logger.LogError($"No certificate for domain: {domains.First()}");
                                }
                            }
                        });
                    }
                }
            })
                          .Build();

            await webHost.RunAsync();
        }
Пример #26
0
        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            try
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                var connectionResult = await _sharedSettings.WaitForLogin(false, cancellationToken);

                if (connectionResult != EConnectionResult.Connected)
                {
                    return;
                }

                var useHttps        = !string.IsNullOrEmpty(_remoteSettings.Network.CertificateFilename);
                var certificatePath = _remoteSettings.CertificateFilePath();

                _logger.LogInformation($"Using the ssl certificate at {certificatePath}");

                if (_remoteSettings.Network.AutoGenerateCertificate)
                {
                    // if no certificate name or password are specified, generate them automatically.
                    if (string.IsNullOrEmpty(_remoteSettings.Network.CertificateFilename))
                    {
                        throw new RemoteSecurityException(
                                  "The applicationSettings -> Network -> AutoGenerateCertificate is true, however there no setting for CertificateFilename");
                    }

                    if (string.IsNullOrEmpty(_remoteSettings.Network.CertificatePassword))
                    {
                        throw new RemoteSecurityException(
                                  "The applicationSettings -> Network -> AutoGenerateCertificate is true, however there no setting for CertificateFilename");
                    }

                    useHttps = true;

                    var renew = false;

                    if (File.Exists(certificatePath))
                    {
                        // Create a collection object and populate it using the PFX file
                        using (var cert = new X509Certificate2(certificatePath, _remoteSettings.Network.CertificatePassword))
                        {
                            // var effectiveDate = DateTime.Parse(cert.GetEffectiveDateString());
                            var expiresDate = DateTime.Parse(cert.GetExpirationDateString());

                            // if cert expires in next 14 days, then renew.
                            if (DateTime.Now > expiresDate.AddDays(-14))
                            {
                                renew = true;
                            }
                        }
                    }
                    else
                    {
                        renew = true;
                    }

                    // generate a new ssl certificate
                    if (renew)
                    {
                        await RenewSslCertificate(certificatePath, cancellationToken);
                    }
                }

                if (_remoteSettings.Network.EnforceHttps)
                {
                    if (string.IsNullOrEmpty(_remoteSettings.Network.CertificateFilename))
                    {
                        throw new RemoteSecurityException(
                                  "The server requires https, however a CertificateFile name is not specified.");
                    }

                    if (!File.Exists(certificatePath))
                    {
                        throw new RemoteSecurityException(
                                  $"The certificate with the filename {certificatePath} does not exist.");
                    }

                    using (var cert = new X509Certificate2(
                               certificatePath,
                               _remoteSettings.Network.CertificatePassword))
                    {
                        var effectiveDate = DateTime.Parse(cert.GetEffectiveDateString());
                        var expiresDate   = DateTime.Parse(cert.GetExpirationDateString());

                        if (DateTime.Now < effectiveDate)
                        {
                            throw new RemoteSecurityException(
                                      $"The certificate with the filename {certificatePath} is not valid until {effectiveDate}.");
                        }


                        if (DateTime.Now > expiresDate)
                        {
                            throw new RemoteSecurityException(
                                      $"The certificate with the filename {certificatePath} expired on {expiresDate}.");
                        }
                    }
                }

                if (!useHttps && _remoteSettings.Network.EnforceHttps)
                {
                    throw new RemoteSecurityException(
                              "The remote agent is set to EnforceHttps, however no SSL certificate was found or able to be generated.");
                }

                if (!useHttps || File.Exists(certificatePath))
                {
                    if (_remoteSettings.Network.DownloadPort == null)
                    {
                        throw new RemoteSecurityException("The web server download port was not set.");
                    }

                    var port = _remoteSettings.Network.DownloadPort.Value;

                    if (_remoteSettings.Network.EnableUPnP)
                    {
                        await EnableUPnp(port);
                    }

                    while (!cancellationToken.IsCancellationRequested)
                    {
                        try
                        {
                            _logger.LogInformation("Starting the data upload/download web server.");
                            var host = new WebHostBuilder()
                                       .UseStartup <Startup>()
                                       .ConfigureServices(s =>
                            {
                                s.AddSingleton(_sharedSettings);
                                s.AddSingleton(_liveApis);
                                s.AddSingleton(_memoryCache);
                                s.AddSingleton(_logger);
                            })
                                       .UseKestrel(options =>
                            {
                                options.Listen(IPAddress.Any,
                                               _remoteSettings.Network.DownloadPort ?? 33944,
                                               listenOptions =>
                                {
                                    // if there is a certificate then default to https
                                    if (useHttps)
                                    {
                                        listenOptions.UseHttps(
                                            certificatePath,
                                            _remoteSettings.Network.CertificatePassword);
                                    }
                                });
                            })
                                       .UseUrls((useHttps ? "https://*:" : "http://*:") + port)
                                       .Build();

                            await host.RunAsync(cancellationToken);
                        }
                        catch (OperationCanceledException)
                        {
                        }
                    }
                }

                _logger.LogInformation("HttpService has stopped.");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex,
                                 $"The following error was encountered with the http listening service.  Http connections will not be available.  {ex.Message}");
            }
        }
Пример #27
0
        static async Task Main(string[] args)
        {
            // ServiceLocatorHelper.CreateService<UnaryService, ICalcSerivce>(null);

            const string GrpcHost = "localhost";

            Console.WriteLine("Server:::");

            //Environment.SetEnvironmentVariable("GRPC_VERBOSITY", "DEBUG");
            //Environment.SetEnvironmentVariable("GRPC_TRACE", "all");

            Environment.SetEnvironmentVariable("SETTINGS_MAX_HEADER_LIST_SIZE", "1000000");

            GrpcEnvironment.SetLogger(new ConsoleLogger());

            var options = new MagicOnionOptions(true)
            {
                //MagicOnionLogger = new MagicOnionLogToGrpcLogger(),
                MagicOnionLogger = new MagicOnionLogToGrpcLoggerWithNamedDataDump(),
                GlobalFilters    = new MagicOnionFilterAttribute[]
                {
                },
                EnableCurrentContext   = true,
                DisableEmbeddedService = true,
            };


            var magicOnionHost = MagicOnionHost.CreateDefaultBuilder(useSimpleConsoleLogger: true)
                                 .UseMagicOnion(options, new ServerPort("localhost", 12345, ServerCredentials.Insecure))
                                 .UseConsoleLifetime()
                                 .Build();

            // test webhost

            // NuGet: Microsoft.AspNetCore.Server.Kestrel
            var webHost = new WebHostBuilder()
                          .ConfigureServices(collection =>
            {
                // Add MagicOnionServiceDefinition for reference from Startup.
                collection.AddSingleton <MagicOnionServiceDefinition>(magicOnionHost.Services.GetService <MagicOnionServiceDefinition>());
            })
                          .UseKestrel()
                          .UseStartup <Startup>()
                          .UseUrls("http://localhost:5432")
                          .Build();

            await Task.WhenAll(webHost.RunAsync(), magicOnionHost.RunAsync());


            //webHost.Run();

            //Console.ReadLine();


            //{
            //    var channel = new Channel("localhost:12345", ChannelCredentials.Insecure);
            //    var client = StreamingHubClient.Connect<IChatHub, IMessageReceiver2>(channel, new Receiver());

            //    Console.WriteLine("Call to Server");
            //    await client.JoinAsync("me", "foo");
            //    await Task.WhenAll(
            //        client.SendMessageAsync("a"),
            //        client.SendMessageAsync("b"),
            //        client.SendMessageAsync("c"),
            //        client.SendMessageAsync("d"),
            //        client.SendMessageAsync("e"));

            //    Console.WriteLine("OK to Send");
            //    await client.DisposeAsync();
            //    await channel.ShutdownAsync();
            //}
        }
Пример #28
0
#pragma warning disable IDE1006 // Naming Styles
        public static async Task Main(string[] args)
#pragma warning restore IDE1006 // Naming Styles
        {
            var configFilePath = Path.Combine(FullSpvWallet.Global.DataDir, "Config.json");

            Global.Config = new Config();
            await Global.Config.LoadOrCreateDefaultFileAsync(configFilePath, CancellationToken.None);

            var endPoint       = "http://*****:*****@"tor\Tor\tor.exe";
                }
                var torProcessStartInfo = new ProcessStartInfo(torPath)
                {
                    Arguments              = Tor.TorArguments,
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                    RedirectStandardOutput = true
                };

                try
                {
                    // if doesn't fail tor is already running with the control port
                    await Tor.ControlPortClient.IsCircuitEstablishedAsync();                     // ToDo fix typo in DotNetTor: establish -> establish

                    Debug.WriteLine($"Tor is already running, using the existing instance.");
                }
                catch (Exception)
                {
                    Debug.WriteLine($"Starting Tor with arguments: {Tor.TorArguments}");
                    try
                    {
                        Tor.TorProcess = Process.Start(torProcessStartInfo);
                    }
                    catch
                    {
                        // ignore, just run the torjob
                    }
                }
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                Tor.MakeSureCircuitEstablishedAsync();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

                Global.WalletWrapper = new WalletWrapper();

                var host = new WebHostBuilder()
                           .UseKestrel()
                           .UseContentRoot(Directory.GetCurrentDirectory())
                           .UseStartup <Startup>()
                           .UseUrls(endPoint)
                           .Build();

                await host.RunAsync();
            }
            else
            {
                Console.WriteLine("API is already running. Shutting down...");
            }
        }
Пример #29
0
        static async Task Main(string[] args)
        {
            //添加 json 文件路径
            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json");

            //创建配置根对象
            var Configuration = builder.Build();

            //Environment.SetEnvironmentVariable("GRPC_VERBOSITY", "DEBUG");
            //Environment.SetEnvironmentVariable("GRPC_TRACE", "all");

            Environment.SetEnvironmentVariable("SETTINGS_MAX_HEADER_LIST_SIZE", "1000000");

            GrpcEnvironment.SetLogger(new ConsoleLogger());

            var options = new MagicOnionOptions(true)
            {
                MagicOnionLogger = new MagicOnionLogToGrpcLoggerWithNamedDataDump(),
                GlobalFilters    = new MagicOnionFilterAttribute[]
                {
                },
                EnableCurrentContext          = true,
                DefaultGroupRepositoryFactory = new ConcurrentDictionaryGroupRepositoryFactory(),
                DisableEmbeddedService        = true,
            };
            var conn = ConnectionMultiplexer.Connect(Configuration["RedisConn"]);

            options.ServiceLocator.Register(conn);
            options.ServiceLocator.Register(MessagePackSerializer.DefaultResolver);
            options.ServiceLocator.Register <IMagicOnionLogger>(new NullMagicOnionLogger());

            //IServiceCollection services = new ServiceCollection();
            //services.AddTransient<ISomeService>(sp => new FooService(5));
            //services.AddAutoMapper(typeof(Source));
            //var                provider = services.BuildServiceProvider();
            //using (var scope = provider.CreateScope())
            //{
            //    var mapper = scope.ServiceProvider.GetService<IMapper>();

            //    foreach (var typeMap in mapper.ConfigurationProvider.GetAllTypeMaps())
            //    {
            //        Console.WriteLine($"{typeMap.SourceType.Name} -> {typeMap.DestinationType.Name}");
            //    }

            //    foreach (var service in services)
            //    {
            //        Console.WriteLine(service.ServiceType + " - " + service.ImplementationType);
            //    }

            //    var dest = mapper.Map<Dest2>(new Source2());
            //    Console.WriteLine(dest.ResolvedValue);
            //}

            var magicOnionHost = MagicOnionHost.CreateDefaultBuilder(useSimpleConsoleLogger: true)
                                 .ConfigureServices((ctx, services) =>
            {
                services.Configure <MongoAppSetting>(x =>
                {
                    x.MongoConn       = Configuration["MongoConn"].ToString();
                    x.MongoDbDatabase = Configuration["MongoDbDatabase"].ToString();
                });
                services.AddAutoMapper((collect, cfg) => { cfg.AddProfile <MappingProfile>(); },
                                       AppDomain.CurrentDomain.GetAssemblies());
                services.Add(new ServiceDescriptor(typeof(IMapper),
                                                   sp => new Mapper(sp.GetRequiredService <AutoMapper.IConfigurationProvider>(), sp.GetService),
                                                   ServiceLifetime.Transient));
                services.AddSingleton <MongoDbContext>();
                services.AddScoped <IUserRepository, UserRepository>();
            })
                                 .UseMagicOnion(options,
                                                new ServerPort(Configuration["GrpcService:IP"], Convert.ToInt32(Configuration["GrpcService:Port"]),
                                                               ServerCredentials.Insecure))
                                 .UseConsoleLifetime()
                                 .Build();

            var webHost = new WebHostBuilder()
                          .ConfigureServices(collection =>
            {
                // Add MagicOnionServiceDefinition for reference from Startup.
                collection.AddSingleton <MagicOnionServiceDefinition>(magicOnionHost.Services
                                                                      .GetService <MagicOnionServiceDefinition>());
            })
                          .UseKestrel()
                          .UseStartup <Startup>()
                          .UseUrls("http://localhost:5432")
                          .Build();

            await Task.WhenAll(webHost.RunAsync(), magicOnionHost.RunAsync());
        }
Пример #30
0
        public async Task StartAsync()
        {
            _projectName = Assembly.GetAssembly(typeof(TStartup)).FullName;
            _projectName = _projectName.Substring(0, _projectName.IndexOf(',')).TrimEnd();

            var apiEntry = _apis.Where(x => x.Value.ProjectName == _projectName).FirstOrDefault();

            if (apiEntry.Equals(default(KeyValuePair <string, ApiConfig>)))
            {
                throw new ApplicationException($"Cannot find configuration entry (e.g., in appsettings.Development.json) for an Api whose project name is '{_projectName}'");
            }


            var api = apiEntry.Value;

            if (api.ExternallyLaunched || (api.BaseAddress != null && api.BaseAddress != "" &&
                                           !api.BaseAddress.Contains("localhost")))
            {
                return;
            }

            var configKey = $"Apis:{apiEntry.Key}";


            var dir = api.ProjectDirectory.Replace("{Environment.UserName}", Environment.UserName);

            if (!api.BaseAddress.Contains("localhost"))
            {
                //assign a new port to the project or get the current port assignment
                var projectPortAssignment = _projectPorts.GetProjectPortAssignment(_projectName);
                _port = projectPortAssignment.Port;

                //short-circuit if the project has been assigned a port, already
                if (projectPortAssignment.AlreadyAssigned)
                {
                    _config[$"{configKey}:BaseAddress"] = $"http://*****:*****@ {_port}");
            await Task.Run(() => {
                host.WaitForShutdownAsync();
                host.RunAsync();
            });

            _config[$"{configKey}:BaseAddress"] = $"http://localhost:{_port}";

            await Task.Run(() => {
                Ping(configKey, "localhost", _port);
            });
        }