public void Start()
 {
     _host = new WebHostBuilder()
         //.UseKestrel()
         .UseStartup<StartupExternallyControlled>()
         .Start(_urls.ToArray());
 }
        public AspNetCoreService(IWebHost webHost)
        {
            if (webHost == null)
                throw new ArgumentNullException(nameof(webHost));

            _webHost = webHost;
        }
        public AspNetCoreCommunicationContext(IWebHost webHost)
        {
            if (webHost == null)
            {
                throw new ArgumentNullException(nameof(webHost));
            }

            WebHost = webHost;
        }
Beispiel #4
0
 public void Initialize()
 {
     server = new WebHostBuilder()
         .UseKestrel()
         .UseContentRoot(Directory.GetCurrentDirectory())
         .UseUrls("http://0.0.0.0:5000/")
         .UseStartup<Startup>()
         .UseLoggerFactory(SprayChronicleServer.LoggerFactory())
         .Build();
 }
        public AspNetCoreCommunicationContext(IWebHost webHost, bool addUrlPrefix)
        {
            if (webHost == null)
            {
                throw new ArgumentNullException(nameof(webHost));
            }

            WebHost = webHost;
            AddUrlPrefix = addUrlPrefix;
        }
        public ServiceFabricWebHost(IWebHost webHost, FabricRuntime fabricRuntime)
        {
            Console.WriteLine("ServiceFabricWebHost: Constructor");

            if (webHost == null)
                throw new ArgumentNullException(nameof(webHost));

            if (fabricRuntime == null)
                throw new ArgumentNullException(nameof(fabricRuntime));

            _webHost = webHost;
            _fabricRuntime = fabricRuntime;
        }
        private void Start()
        {
            _host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\..\..\"))
                .UseStartup<Startup>()
                .UseEnvironment("AcceptanceTesting")
                .ConfigureServices(services => {
                    services.AddScoped(serviceProvider => new LicensingContextBuilder().InMemory().Build());
                })
                .Build();

            _host.Start();
        }
        public AspNetCoreCommunicationListener(IStatelessServiceInstance instance, IWebHost webHost, bool addUrlPrefix)
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            if (webHost == null)
            {
                throw new ArgumentNullException(nameof(webHost));
            }

            _instanceOrReplica = instance;
            _webHost = webHost;
            _addUrlPrefix = addUrlPrefix;
        }
Beispiel #9
0
            Task<string> ICommunicationListener.OpenAsync(CancellationToken cancellationToken)
            {
                var endpoint = FabricRuntime.GetActivationContext().GetEndpoint(_endpointName);

                string serverUrl = $"{endpoint.Protocol}://{FabricRuntime.GetNodeContext().IPAddressOrFQDN}:{endpoint.Port}";

                _webHost = new WebHostBuilder().UseKestrel()
                                               .UseContentRoot(Directory.GetCurrentDirectory())
                                               .UseStartup<Startup>()
                                               .UseUrls(serverUrl)
                                               .Build();

                _webHost.Start();

                return Task.FromResult(serverUrl);
            }
        public AspNetCoreCommunicationListener(IStatefulServiceReplica replica, IWebHost webHost, bool addUrlPrefix)
        {
            if (replica == null)
            {
                throw new ArgumentNullException(nameof(replica));
            }

            if (webHost == null)
            {
                throw new ArgumentNullException(nameof(webHost));
            }

            _instanceOrReplica = replica;
            _webHost = webHost;
            _addUrlPrefix = addUrlPrefix;
        }
        public void Open()
        {
            string serverUrl = "http://localhost:5001/iot";

            CancellationTokenSource webApiCancellationSource = new CancellationTokenSource();
            FabricClient fabricClient = new FabricClient();

            this.webHost = new WebHostBuilder().UseKestrel()
                .ConfigureServices(
                    services => services
                        .AddSingleton<FabricClient>(fabricClient)
                        .AddSingleton<CancellationTokenSource>(webApiCancellationSource))
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>()
                .UseUrls(serverUrl)
                .Build();

            this.webHost.Run();
        }
Beispiel #12
0
 public static int Port(this IWebHost host)
 {
     return(host.ServerFeatures.Port());
 }
Beispiel #13
0
 public void Dispose()
 {
     StopHost(_server);
     _server = null;
 }
Beispiel #14
0
 public HostBuilder(IWebHost webHost)
 {
     _webHost = webHost;
 }
Beispiel #15
0
        public void Start()
        {
            if (!Directory.Exists(_Directory))
            {
                Directory.CreateDirectory(_Directory);
            }
            string chain          = NBXplorerDefaultSettings.GetFolderName(NetworkType.Regtest);
            string chainDirectory = Path.Combine(_Directory, chain);

            if (!Directory.Exists(chainDirectory))
            {
                Directory.CreateDirectory(chainDirectory);
            }


            StringBuilder config = new StringBuilder();

            config.AppendLine($"{chain.ToLowerInvariant()}=1");
            if (InContainer)
            {
                config.AppendLine($"bind=0.0.0.0");
            }
            config.AppendLine($"port={Port}");
            config.AppendLine($"chains=btc,ltc");

            config.AppendLine($"btc.explorer.url={NBXplorerUri.AbsoluteUri}");
            config.AppendLine($"btc.explorer.cookiefile=0");
            config.AppendLine("allow-admin-registration=1");
            config.AppendLine($"ltc.explorer.url={LTCNBXplorerUri.AbsoluteUri}");
            config.AppendLine($"ltc.explorer.cookiefile=0");
            config.AppendLine($"btc.lightning={IntegratedLightning.AbsoluteUri}");

            if (Postgres != null)
            {
                config.AppendLine($"postgres=" + Postgres);
            }
            var confPath = Path.Combine(chainDirectory, "settings.config");

            File.WriteAllText(confPath, config.ToString());

            ServerUri              = new Uri("http://" + HostName + ":" + Port + "/");
            HttpClient             = new HttpClient();
            HttpClient.BaseAddress = ServerUri;
            Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
            var conf = new DefaultConfiguration()
            {
                Logger = Logs.LogProvider.CreateLogger("Console")
            }.CreateConfiguration(new[] { "--datadir", _Directory, "--conf", confPath, "--disable-registration", "false" });

            _Host = new WebHostBuilder()
                    .UseConfiguration(conf)
                    .UseContentRoot(FindBTCPayServerDirectory())
                    .ConfigureServices(s =>
            {
                s.AddLogging(l =>
                {
                    l.AddFilter("System.Net.Http.HttpClient", LogLevel.Critical);
                    l.SetMinimumLevel(LogLevel.Information)
                    .AddFilter("Microsoft", LogLevel.Error)
                    .AddFilter("Hangfire", LogLevel.Error)
                    .AddProvider(Logs.LogProvider);
                });
            })
                    .UseKestrel()
                    .UseStartup <Startup>()
                    .Build();
            _Host.StartWithTasksAsync().GetAwaiter().GetResult();

            var urls = _Host.ServerFeatures.Get <IServerAddressesFeature>().Addresses;

            foreach (var url in urls)
            {
                Logs.Tester.LogInformation("Listening on " + url);
            }
            Logs.Tester.LogInformation("Server URI " + ServerUri);

            InvoiceRepository = (InvoiceRepository)_Host.Services.GetService(typeof(InvoiceRepository));
            StoreRepository   = (StoreRepository)_Host.Services.GetService(typeof(StoreRepository));
            Networks          = (BTCPayNetworkProvider)_Host.Services.GetService(typeof(BTCPayNetworkProvider));

            if (MockRates)
            {
                var rateProvider = (RateProviderFactory)_Host.Services.GetService(typeof(RateProviderFactory));
                rateProvider.Providers.Clear();

                var coinAverageMock = new MockRateProvider();
                coinAverageMock.ExchangeRates.Add(new Rating.ExchangeRate()
                {
                    Exchange     = "coinaverage",
                    CurrencyPair = CurrencyPair.Parse("BTC_USD"),
                    BidAsk       = new BidAsk(5000m)
                });
                coinAverageMock.ExchangeRates.Add(new Rating.ExchangeRate()
                {
                    Exchange     = "coinaverage",
                    CurrencyPair = CurrencyPair.Parse("BTC_CAD"),
                    BidAsk       = new BidAsk(4500m)
                });
                coinAverageMock.ExchangeRates.Add(new Rating.ExchangeRate()
                {
                    Exchange     = "coinaverage",
                    CurrencyPair = CurrencyPair.Parse("LTC_BTC"),
                    BidAsk       = new BidAsk(0.001m)
                });
                coinAverageMock.ExchangeRates.Add(new Rating.ExchangeRate()
                {
                    Exchange     = "coinaverage",
                    CurrencyPair = CurrencyPair.Parse("LTC_USD"),
                    BidAsk       = new BidAsk(500m)
                });
                rateProvider.Providers.Add("coinaverage", coinAverageMock);

                var bitflyerMock = new MockRateProvider();
                bitflyerMock.ExchangeRates.Add(new Rating.ExchangeRate()
                {
                    Exchange     = "bitflyer",
                    CurrencyPair = CurrencyPair.Parse("BTC_JPY"),
                    BidAsk       = new BidAsk(700000m)
                });
                rateProvider.Providers.Add("bitflyer", bitflyerMock);

                var quadrigacx = new MockRateProvider();
                quadrigacx.ExchangeRates.Add(new Rating.ExchangeRate()
                {
                    Exchange     = "quadrigacx",
                    CurrencyPair = CurrencyPair.Parse("BTC_CAD"),
                    BidAsk       = new BidAsk(6000m)
                });
                rateProvider.Providers.Add("quadrigacx", quadrigacx);

                var bittrex = new MockRateProvider();
                bittrex.ExchangeRates.Add(new Rating.ExchangeRate()
                {
                    Exchange     = "bittrex",
                    CurrencyPair = CurrencyPair.Parse("DOGE_BTC"),
                    BidAsk       = new BidAsk(0.004m)
                });
                rateProvider.Providers.Add("bittrex", bittrex);
            }



            WaitSiteIsOperational().GetAwaiter().GetResult();
        }
Beispiel #16
0
 private Task StartWebHostAsync(AppSettings settings)
 {
     _webHost = WebHostFactory.CreateWebHost(settings, Port);
     return(_webHost.StartAsync());
 }
Beispiel #17
0
        public static IWebHost Seed(this IWebHost webHost)
        {
            using (var scope = webHost.Services.CreateScope())
            {
                using (var context = scope.ServiceProvider.GetRequiredService <Prid1920_g01Context>())
                {
                    try
                    {
                        Console.Write("Seeding data ...");

                        if (context.Users.Count() == 0)
                        {
                            context.Users.AddRange(
                                new User {
                                Id = 1, Pseudo = "ben", Password = TokenHelper.GetPasswordHash("ben"), LastName = "Penelle", FirstName = "Benoît", Email = "*****@*****.**", Reputation = 50
                            },
                                new User {
                                Id = 2, Pseudo = "bruno", Password = TokenHelper.GetPasswordHash("bruno"), LastName = "Lacroix", FirstName = "Bruno", Email = "*****@*****.**", Reputation = 50
                            },
                                new User {
                                Id = 3, Pseudo = "admin", Password = TokenHelper.GetPasswordHash("admin"), LastName = "Administrator", FirstName = "Administrator", Email = "*****@*****.**", Role = Role.Admin, Reputation = 100
                            },
                                new User {
                                Id = 4, Pseudo = "boris", Password = TokenHelper.GetPasswordHash("boris"), LastName = "Verhaegen", FirstName = "Boris", Email = "*****@*****.**", Role = Role.Admin
                            },
                                new User {
                                Id = 5, Pseudo = "alain", Password = TokenHelper.GetPasswordHash("alain"), LastName = "Silovy", FirstName = "Alain", Email = "*****@*****.**"
                            }
                                );
                            context.SaveChanges();
                        }

                        if (context.Posts.Count() == 0)
                        {
                            context.Posts.AddRange(
                                new Post()
                            {
                                Id    = 1,
                                Title = "What does 'initialization' exactly mean?",
                                Body  = @"My csapp book says that if global and static variables are initialized, than they are contained in .data section in ELF relocatable object file.

So my question is that if some `foo.c` code contains 

```

int a;

int main()

{

    a = 3;

}`

```

and `example.c` contains,

```

int b = 3;

int main()

{

...

}

```

is it only `b` that considered to be initialized? In other words, does initialization mean declaration and definition in same line?",

                                UserId    = 1,
                                Timestamp = new DateTime(2019, 11, 15, 8, 30, 0)
                            },

                                new Post()
                            {
                                Id   = 2,
                                Body = @"It means exactly what it says. Initialized static storage duration objects will have their init values set before the main function is called. Not initialized will be zeroed. The second part of the statement is actually implementation dependant,  and implementation has the full freedom of the way it will be archived. 

When you declare the variable without the keyword `extern`  you always define it as well",

                                ParentId  = 1,
                                UserId    = 2,
                                Timestamp = new DateTime(2019, 11, 15, 8, 31, 0)
                            },

                                new Post()
                            {
                                Id   = 3,
                                Body = @"Both are considered initialized

------------------------------------

They get [zero initialized][1] or constant initalized (in short: if the right hand side is a compile time constant expression).

> If permitted, Constant initialization takes place first (see Constant

> initialization for the list of those situations). In practice,

> constant initialization is usually performed at compile time, and

> pre-calculated object representations are stored as part of the

> program image. If the compiler doesn't do that, it still has to

> guarantee that this initialization happens before any dynamic

> initialization.

> 

> For all other non-local static and thread-local variables, Zero

> initialization takes place. In practice, variables that are going to

> be zero-initialized are placed in the .bss segment of the program

> image, which occupies no space on disk, and is zeroed out by the OS

> when loading the program.

To sum up, if the implementation cannot constant initialize it, then it must first zero initialize and then initialize it before any dynamic initialization happends.

  [1]: https://en.cppreference.com/w/cpp/language/zero_initialization

",

                                ParentId  = 1,
                                UserId    = 3,
                                Timestamp = new DateTime(2019, 11, 15, 8, 32, 0)
                            },

                                new Post()
                            {
                                Id    = 4,
                                Title = "How do I escape characters in an Angular date pipe?",

                                Body = @"I have an Angular date variable `today` that I'm using the [date pipe][1] on, like so:

    {{today | date:'LLLL d'}}

> February 13

However, I would like to make it appear like this:

> 13 days so far in February

When I try a naive approach to this, I get this result:

    {{today | date:'d days so far in LLLL'}}

> 13 13PM201818 18o fPMr in February

This is because, for instance `d` refers to the day.

How can I escape these characters in an Angular date pipe? I tried `\d` and such, but the result did not change with the added backslashes.

  [1]: https://angular.io/api/common/DatePipe",

                                UserId    = 1,
                                Timestamp = new DateTime(2019, 11, 15, 8, 33, 0)
                            },

                                new Post()
                            {
                                Id   = 5,
                                Body = @"How about this:

    {{today | date:'d \'days so far in\' LLLL'}}

Anything inside single quotes is ignored. Just don't forget to escape them.",

                                ParentId  = 4,
                                UserId    = 1,
                                Timestamp = new DateTime(2019, 11, 15, 8, 34, 0)
                            },

                                new Post()
                            {
                                Id   = 6,
                                Body = @"Then only other alternative to stringing multiple pipes together as suggested by RichMcCluskey would be to create a custom pipe that calls through to momentjs format with the passed in date. Then you could use the same syntax including escape sequence that momentjs supports.

Something like this could work, it is not an exhaustive solution in that it does not deal with localization at all and there is no error handling code or tests.

    import { Inject, Pipe, PipeTransform } from '@angular/core';

    @Pipe({ name: 'momentDate', pure: true })

    export class MomentDatePipe implements PipeTransform {

        transform(value: any, pattern: string): string {

            if (!value)

                return '';

            return moment(value).format(pattern);

        }

    }

And then the calling code:

    {{today | momentDate:'d [days so far in] LLLL'}}

For all the format specifiers see the [documentation for format][1]. 

Keep in mind you do have to import `momentjs` either as an import statement, have it imported in your cli config file, or reference the library from the root HTML page (like index.html).

  [1]: http://momentjs.com/docs/#/displaying/format/",

                                ParentId  = 4,
                                UserId    = 3,
                                Timestamp = new DateTime(2019, 11, 15, 8, 35, 0)
                            },

                                new Post()
                            {
                                Id   = 7,
                                Body = @"As far as I know this is not possible with the Angular date pipe at the time of this answer. One alternative is to use multiple date pipes like so:

    {{today | date:'d'}} days so far in {{today | date:'LLLL'}}

EDIT:

After posting this I tried @Gh0sT 's solution and it worked, so I guess there is a way to use one date pipe.",

                                ParentId  = 4,
                                UserId    = 2,
                                Timestamp = new DateTime(2019, 11, 15, 8, 36, 0)
                            },

                                new Post()
                            {
                                Id        = 8,
                                Title     = "Q1",
                                Body      = "Q1",
                                UserId    = 5,
                                Timestamp = new DateTime(2019, 11, 22, 8, 0, 0)
                            },

                                new Post()
                            {
                                Id        = 9,
                                Body      = "R1",
                                ParentId  = 8,
                                UserId    = 1,
                                Timestamp = new DateTime(2019, 11, 22, 8, 5, 0)
                            },

                                new Post()
                            {
                                Id        = 10,
                                Body      = "R2",
                                ParentId  = 8,
                                UserId    = 2,
                                Timestamp = new DateTime(2019, 11, 22, 8, 3, 0)
                            },

                                new Post()
                            {
                                Id        = 11,
                                Body      = "R3",
                                ParentId  = 8,
                                UserId    = 3,
                                Timestamp = new DateTime(2019, 11, 22, 8, 4, 0)
                            },

                                new Post()
                            {
                                Id        = 12,
                                Title     = "Q2",
                                Body      = "Q2",
                                UserId    = 4,
                                Timestamp = new DateTime(2019, 11, 22, 9, 0, 0)
                            },

                                new Post()
                            {
                                Id        = 13,
                                Body      = "R4",
                                ParentId  = 12,
                                UserId    = 5,
                                Timestamp = new DateTime(2019, 11, 22, 9, 1, 0)
                            },

                                new Post()
                            {
                                Id        = 14,
                                Title     = "Q3",
                                Body      = "Q3",
                                UserId    = 1,
                                Timestamp = new DateTime(2019, 11, 22, 10, 0, 0)
                            },

                                new Post()
                            {
                                Id        = 15,
                                Body      = "R5",
                                ParentId  = 14,
                                UserId    = 5,
                                Timestamp = new DateTime(2019, 11, 22, 10, 2, 0)
                            },

                                new Post()
                            {
                                Id        = 16,
                                Body      = "R6",
                                ParentId  = 14,
                                UserId    = 3,
                                Timestamp = new DateTime(2019, 11, 22, 10, 2, 0)
                            },

                                new Post()
                            {
                                Id        = 17,
                                Title     = "Q4",
                                Body      = "Q4",
                                UserId    = 2,
                                Timestamp = new DateTime(2019, 11, 22, 11, 0, 0)
                            },

                                new Post()
                            {
                                Id        = 18,
                                Body      = "R7",
                                ParentId  = 17,
                                UserId    = 3,
                                Timestamp = new DateTime(2019, 11, 22, 10, 2, 0)
                            },

                                new Post()
                            {
                                Id        = 19,
                                Title     = "Q5",
                                Body      = "Q8",
                                UserId    = 4,
                                Timestamp = new DateTime(2019, 11, 22, 11, 0, 0)
                            },

                                new Post()
                            {
                                Id        = 20,
                                Body      = "R8",
                                ParentId  = 19,
                                UserId    = 3,
                                Timestamp = new DateTime(2019, 11, 22, 10, 2, 0)
                            },
                                new Post()
                            {
                                Id        = 21,
                                Title     = "Q6",
                                Body      = "Q6",
                                UserId    = 3,
                                Timestamp = new DateTime(2019, 11, 22, 10, 2, 0)
                            }

                                );

                            context.SaveChanges();
                            var post4 = context.Posts.Find(4);
                            post4.AcceptedAnswerId = 5;
                            context.SaveChanges();
                        }

                        if (context.Comments.Count() == 0)
                        {
                            context.Comments.AddRange(

                                new Comment()
                            {
                                Id        = 1,
                                Body      = @"Global ""uninitialized"" variables typically end up in a ""bss"" segment, which will be initialized to zero.",
                                UserId    = 1,
                                PostId    = 1,
                                Timestamp = new DateTime(2019, 11, 15, 8, 40, 0)
                            },

                                new Comment()
                            {
                                Id        = 2,
                                Body      = @"[stackoverflow.com/questions/1169858/…]() This might help",
                                UserId    = 2,
                                PostId    = 1,
                                Timestamp = new DateTime(2019, 11, 15, 8, 41, 0)
                            },

                                new Comment()
                            {
                                Id        = 3,
                                Body      = @"Verified that this works! Pretty cool",
                                UserId    = 2,
                                PostId    = 6,
                                Timestamp = new DateTime(2019, 11, 15, 8, 42, 0)
                            },

                                new Comment()
                            {
                                Id        = 4,
                                Body      = @"For me it works with double quotes. `{{today | date:""d \'days so far in\' LLLL""}}`",
                                UserId    = 3,
                                PostId    = 7,
                                Timestamp = new DateTime(2019, 11, 15, 8, 43, 0)
                            },

                                new Comment()
                            {
                                Id        = 5,
                                Body      = @"This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker.",
                                UserId    = 2,
                                PostId    = 6,
                                Timestamp = new DateTime(2019, 11, 15, 8, 44, 0)
                            },

                                new Comment()
                            {
                                Id        = 6,
                                Body      = @"Duplicate of [xxx](yyy). Please stop!",
                                UserId    = 1,
                                PostId    = 6,
                                Timestamp = new DateTime(2019, 11, 15, 8, 45, 0)
                            }
                                );
                            context.SaveChanges();
                        }

                        if (context.Votes.Count() == 0)
                        {
                            context.Votes.AddRange(
                                new Vote()
                            {
                                UpDown = 1, UserId = 5, PostId = 1
                            },
                                new Vote()
                            {
                                UpDown = -1, UserId = 3, PostId = 2
                            },
                                new Vote()
                            {
                                UpDown = -1, UserId = 2, PostId = 1
                            },
                                new Vote()
                            {
                                UpDown = -1, UserId = 3, PostId = 1
                            },
                                new Vote()
                            {
                                UpDown = 1, UserId = 2, PostId = 3
                            },
                                new Vote()
                            {
                                UpDown = 1, UserId = 5, PostId = 5
                            },
                                new Vote()
                            {
                                UpDown = -1, UserId = 3, PostId = 5
                            },
                                new Vote()
                            {
                                UpDown = 1, UserId = 4, PostId = 7
                            },
                                new Vote()
                            {
                                UpDown = -1, UserId = 4, PostId = 8
                            },
                                new Vote()
                            {
                                UpDown = -1, UserId = 1, PostId = 8
                            },
                                new Vote()
                            {
                                UpDown = 1, UserId = 4, PostId = 9
                            },
                                new Vote()
                            {
                                UpDown = -1, UserId = 2, PostId = 9
                            },
                                new Vote()
                            {
                                UpDown = 1, UserId = 1, PostId = 11
                            },
                                new Vote()
                            {
                                UpDown = 1, UserId = 2, PostId = 11
                            },
                                new Vote()
                            {
                                UpDown = 1, UserId = 1, PostId = 12
                            },
                                new Vote()
                            {
                                UpDown = 1, UserId = 2, PostId = 12
                            },
                                new Vote()
                            {
                                UpDown = 1, UserId = 3, PostId = 12
                            },
                                new Vote()
                            {
                                UpDown = -1, UserId = 1, PostId = 13
                            },
                                new Vote()
                            {
                                UpDown = -1, UserId = 2, PostId = 14
                            },
                                new Vote()
                            {
                                UpDown = -1, UserId = 2, PostId = 15
                            },
                                new Vote()
                            {
                                UpDown = -1, UserId = 4, PostId = 16
                            },
                                new Vote()
                            {
                                UpDown = 1, UserId = 1, PostId = 18
                            }
                                );
                            context.SaveChanges();
                        }

                        if (context.Tags.Count() == 0)
                        {
                            context.Tags.AddRange(
                                new Tag()
                            {
                                Id = 1, Name = "angular"
                            },
                                new Tag()
                            {
                                Id = 2, Name = "typescript"
                            },
                                new Tag()
                            {
                                Id = 3, Name = "csharp"
                            },
                                new Tag()
                            {
                                Id = 4, Name = "EntityFramework Core"
                            },
                                new Tag()
                            {
                                Id = 5, Name = "dotnet core"
                            },
                                new Tag()
                            {
                                Id = 6, Name = "mysql"
                            }
                                );
                            context.SaveChanges();
                        }

                        if (context.PostTags.Count() == 0)
                        {
                            context.PostTags.AddRange(
                                new PostTag()
                            {
                                PostId = 1, TagId = 1
                            },
                                new PostTag()
                            {
                                PostId = 1, TagId = 3
                            },
                                new PostTag()
                            {
                                PostId = 4, TagId = 2
                            }
                                );

                            context.SaveChanges();
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
            return(webHost);
        }
Beispiel #18
0
        public StressServer(Configuration configuration)
        {
            ServerUri = configuration.ServerUri;
            (string scheme, string hostname, int port) = ParseServerUri(configuration.ServerUri);
            IWebHostBuilder host = WebHost.CreateDefaultBuilder();

            if (configuration.UseHttpSys && OperatingSystem.IsWindows())
            {
                // Use http.sys.  This requires additional manual configuration ahead of time;
                // see https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/httpsys?view=aspnetcore-2.2#configure-windows-server.
                // In particular, you need to:
                // 1. Create a self-signed cert and install it into your local personal store, e.g. New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\LocalMachine\My"
                // 2. Pre-register the URL prefix, e.g. netsh http add urlacl url=https://localhost:5001/ user=Users
                // 3. Register the cert, e.g. netsh http add sslcert ipport=[::1]:5001 certhash=THUMBPRINTFROMABOVE appid="{some-guid}"
                host = host.UseHttpSys(hso =>
                {
                    hso.UrlPrefixes.Add(ServerUri);
                    hso.Authentication.Schemes        = Microsoft.AspNetCore.Server.HttpSys.AuthenticationSchemes.None;
                    hso.Authentication.AllowAnonymous = true;
                    hso.MaxConnections     = null;
                    hso.MaxRequestBodySize = null;
                });
            }
            else
            {
                // Use Kestrel, and configure it for HTTPS with a self-signed test certificate.
                host = host.UseKestrel(ko =>
                {
                    // conservative estimation based on https://github.com/dotnet/aspnetcore/blob/caa910ceeba5f2b2c02c47a23ead0ca31caea6f0/src/Servers/Kestrel/Core/src/Internal/Http2/Http2Stream.cs#L204
                    ko.Limits.MaxRequestLineSize         = Math.Max(ko.Limits.MaxRequestLineSize, configuration.MaxRequestUriSize + 100);
                    ko.Limits.MaxRequestHeaderCount      = Math.Max(ko.Limits.MaxRequestHeaderCount, configuration.MaxRequestHeaderCount);
                    ko.Limits.MaxRequestHeadersTotalSize = Math.Max(ko.Limits.MaxRequestHeadersTotalSize, configuration.MaxRequestHeaderTotalSize);

                    ko.Limits.Http2.MaxStreamsPerConnection     = configuration.ServerMaxConcurrentStreams ?? ko.Limits.Http2.MaxStreamsPerConnection;
                    ko.Limits.Http2.MaxFrameSize                = configuration.ServerMaxFrameSize ?? ko.Limits.Http2.MaxFrameSize;
                    ko.Limits.Http2.InitialConnectionWindowSize = configuration.ServerInitialConnectionWindowSize ?? ko.Limits.Http2.InitialConnectionWindowSize;
                    ko.Limits.Http2.MaxRequestHeaderFieldSize   = configuration.ServerMaxRequestHeaderFieldSize ?? ko.Limits.Http2.MaxRequestHeaderFieldSize;

                    switch (hostname)
                    {
                    case "+":
                    case "*":
                        ko.ListenAnyIP(port, ConfigureListenOptions);
                        break;

                    default:
                        IPAddress iPAddress = Dns.GetHostAddresses(hostname).First();
                        ko.Listen(iPAddress, port, ConfigureListenOptions);
                        break;
                    }

                    void ConfigureListenOptions(ListenOptions listenOptions)
                    {
                        if (scheme == "https")
                        {
                            // Create self-signed cert for server.
                            using (RSA rsa = RSA.Create())
                            {
                                var certReq = new CertificateRequest("CN=contoso.com", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
                                certReq.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false));
                                certReq.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection {
                                    new Oid("1.3.6.1.5.5.7.3.1")
                                }, false));
                                certReq.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false));
                                X509Certificate2 cert = certReq.CreateSelfSigned(DateTimeOffset.UtcNow.AddMonths(-1), DateTimeOffset.UtcNow.AddMonths(1));
                                if (OperatingSystem.IsWindows())
                                {
                                    cert = new X509Certificate2(cert.Export(X509ContentType.Pfx));
                                }
                                listenOptions.UseHttps(cert);
                            }
                            if (configuration.HttpVersion == HttpVersion.Version30)
                            {
                                listenOptions.Protocols = HttpProtocols.Http3;
                            }
                        }
                        else
                        {
                            listenOptions.Protocols =
                                configuration.HttpVersion == HttpVersion.Version20 ?
                                HttpProtocols.Http2 :
                                HttpProtocols.Http1;
                        }
                    }
                });

                if (configuration.HttpVersion == HttpVersion.Version30)
                {
                    host = host.UseQuic(options =>
                    {
                        options.Alpn        = "h3-29";
                        options.IdleTimeout = TimeSpan.FromMinutes(1);
                    });
                }
            };

            LoggerConfiguration loggerConfiguration = new LoggerConfiguration();

            if (configuration.Trace)
            {
                // Clear existing logs first.
                foreach (var filename in Directory.GetFiles(".", "server*.log"))
                {
                    try
                    {
                        File.Delete(filename);
                    } catch {}
                }

                loggerConfiguration = loggerConfiguration
                                      // Output diagnostics to the file
                                      .WriteTo.File("server.log", fileSizeLimitBytes: 50 << 20, rollOnFileSizeLimit: true)
                                      .MinimumLevel.Debug();
            }
            if (configuration.LogAspNet)
            {
                loggerConfiguration = loggerConfiguration
                                      // Output only warnings and errors
                                      .WriteTo.Console(Serilog.Events.LogEventLevel.Warning);
            }
            Log.Logger = loggerConfiguration.CreateLogger();

            host = host
                   .UseSerilog()
                   // Set up how each request should be handled by the server.
                   .Configure(app =>
            {
                app.UseRouting();
                app.UseEndpoints(MapRoutes);
            });

            _webHost = host.Build();
            _webHost.Start();
        }
Beispiel #19
0
        private void GivenThereIsAnIdentityServerOn(string url, string scopeName, AccessTokenType tokenType)
        {
            _identityServerBuilder = new WebHostBuilder()
                                     .UseUrls(url)
                                     .UseKestrel()
                                     .UseContentRoot(Directory.GetCurrentDirectory())
                                     .UseIISIntegration()
                                     .UseUrls(url)
                                     .ConfigureServices(services =>
            {
                services.AddLogging();
                services.AddIdentityServer()
                .AddTemporarySigningCredential()
                .AddInMemoryApiResources(new List <ApiResource>
                {
                    new ApiResource
                    {
                        Name        = scopeName,
                        Description = "My API",
                        Enabled     = true,
                        DisplayName = "test",
                        Scopes      = new List <Scope>()
                        {
                            new Scope("api"),
                            new Scope("openid"),
                            new Scope("offline_access")
                        },
                        ApiSecrets = new List <Secret>()
                        {
                            new Secret
                            {
                                Value = "secret".Sha256()
                            }
                        },
                        UserClaims = new List <string>()
                        {
                            "CustomerId", "LocationId"
                        }
                    },
                })
                .AddInMemoryClients(new List <Client>
                {
                    new Client
                    {
                        ClientId          = "client",
                        AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                        ClientSecrets     = new List <Secret> {
                            new Secret("secret".Sha256())
                        },
                        AllowedScopes = new List <string> {
                            scopeName, "openid", "offline_access"
                        },
                        AccessTokenType     = tokenType,
                        Enabled             = true,
                        RequireClientSecret = false
                    }
                })
                .AddTestUsers(new List <TestUser>
                {
                    new TestUser
                    {
                        Username  = "******",
                        Password  = "******",
                        SubjectId = "registered|1231231",
                        Claims    = new List <Claim>
                        {
                            new Claim("CustomerId", "123"),
                            new Claim("LocationId", "321")
                        }
                    }
                });
            })
                                     .Configure(app =>
            {
                app.UseIdentityServer();
            })
                                     .Build();

            _identityServerBuilder.Start();

            _steps.VerifyIdentiryServerStarted(url);
        }
Beispiel #20
0
        public static void RunReverseProxyAsService(this IWebHost host)
        {
            var webHostService = new ServiceHost(host);

            ServiceHost.Run(webHostService);
        }
Beispiel #21
0
        static void Main(string[] args)
        {
            ServicePointManager.DefaultConnectionLimit = 100;
            IWebHost host      = null;
            var      processor = new ConsoleLoggerProcessor();
            CustomConsoleLogProvider loggerProvider = new CustomConsoleLogProvider(processor);
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(loggerProvider);
            var logger = loggerFactory.CreateLogger("Configuration");

            try
            {
                // This is the only way toat LoadArgs can print to console. Because LoadArgs is called by the HostBuilder before Logs.Configure is called
                var conf = new DefaultConfiguration()
                {
                    Logger = logger
                }.CreateConfiguration(args);
                if (conf == null)
                {
                    return;
                }
                Logs.Configure(loggerFactory);
                new BTCPayServerOptions().LoadArgs(conf);
                Logs.Configure(null);
                /////

                host = new WebHostBuilder()
                       .UseKestrel()
                       .UseIISIntegration()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseConfiguration(conf)
                       .ConfigureLogging(l =>
                {
                    l.AddFilter("Microsoft", LogLevel.Error);
                    l.AddFilter("Microsoft.AspNetCore.Antiforgery.Internal", LogLevel.Critical);
                    l.AddProvider(new CustomConsoleLogProvider(processor));
                })
                       .UseStartup <Startup>()
                       .Build();
                host.StartAsync().GetAwaiter().GetResult();
                var urls = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses;
                foreach (var url in urls)
                {
                    logger.LogInformation("Listening on " + url);
                }
                host.WaitForShutdown();
            }
            catch (ConfigException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                {
                    Logs.Configuration.LogError(ex.Message);
                }
            }
            finally
            {
                processor.Dispose();
                if (host == null)
                {
                    Logs.Configuration.LogError("Configuration error");
                }
                if (host != null)
                {
                    host.Dispose();
                }
                loggerProvider.Dispose();
            }
        }
Beispiel #22
0
        private const long MAX_DEBUG_LOG_FILE_SIZE = 2000000; // If debug log is in use roll it every N MB.

        static void Main(string[] args)
        {
            ServicePointManager.DefaultConnectionLimit = 100;
            IWebHost host      = null;
            var      processor = new ConsoleLoggerProcessor();
            CustomConsoleLogProvider loggerProvider = new CustomConsoleLogProvider(processor);
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(loggerProvider);
            var logger = loggerFactory.CreateLogger("Configuration");

            try
            {
                // This is the only way that LoadArgs can print to console. Because LoadArgs is called by the HostBuilder before Logs.Configure is called
                var conf = new DefaultConfiguration()
                {
                    Logger = logger
                }.CreateConfiguration(args);
                if (conf == null)
                {
                    return;
                }
                Logs.Configure(loggerFactory);
                new BTCPayServerOptions().LoadArgs(conf);
                Logs.Configure(null);
                /////

                host = new WebHostBuilder()
                       .UseKestrel()
                       .UseIISIntegration()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseConfiguration(conf)
                       .ConfigureLogging(l =>
                {
                    l.AddFilter("Microsoft", LogLevel.Error);
                    l.AddFilter("System.Net.Http.HttpClient", LogLevel.Critical);
                    l.AddFilter("Microsoft.AspNetCore.Antiforgery.Internal", LogLevel.Critical);
                    l.AddProvider(new CustomConsoleLogProvider(processor));

                    // Use Serilog for debug log file.
                    var debugLogFile = BTCPayServerOptions.GetDebugLog(conf);
                    if (string.IsNullOrEmpty(debugLogFile) != false)
                    {
                        return;
                    }
                    Serilog.Log.Logger = new LoggerConfiguration()
                                         .Enrich.FromLogContext()
                                         .MinimumLevel.Is(BTCPayServerOptions.GetDebugLogLevel(conf))
                                         .WriteTo.File(debugLogFile, rollingInterval: RollingInterval.Day, fileSizeLimitBytes: MAX_DEBUG_LOG_FILE_SIZE, rollOnFileSizeLimit: true, retainedFileCountLimit: 1)
                                         .CreateLogger();

                    l.AddSerilog(Serilog.Log.Logger);
                })
                       .UseStartup <Startup>()
                       .Build();
                host.StartAsync().GetAwaiter().GetResult();
                var urls = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses;
                foreach (var url in urls)
                {
                    logger.LogInformation("Listening on " + url);
                }
                host.WaitForShutdown();
            }
            catch (ConfigException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                {
                    Logs.Configuration.LogError(ex.Message);
                }
            }
            finally
            {
                processor.Dispose();
                if (host == null)
                {
                    Logs.Configuration.LogError("Configuration error");
                }
                if (host != null)
                {
                    host.Dispose();
                }
                Serilog.Log.CloseAndFlush();
                loggerProvider.Dispose();
            }
        }
Beispiel #23
0
        private static void StartApi()
        {
            var address = clusterConfig.Api?.ListenAddress != null
                ? (clusterConfig.Api.ListenAddress != "*" ? IPAddress.Parse(clusterConfig.Api.ListenAddress) : IPAddress.Any)
                : IPAddress.Parse("127.0.0.1");

            var port = clusterConfig.Api?.Port ?? 4000;
            var enableApiRateLimiting = !(clusterConfig.Api?.RateLimiting?.Disabled == true);

            webHost = WebHost.CreateDefaultBuilder()
                      .ConfigureLogging(logging =>
            {
                // NLog
                logging.ClearProviders();
                logging.AddNLog();

                logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
            })
                      .ConfigureServices(services =>
            {
                // rate limiting
                if (enableApiRateLimiting)
                {
                    services.Configure <IpRateLimitOptions>(ConfigureIpRateLimitOptions);
                    services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>();
                    services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
                    services.AddSingleton <IRateLimitConfiguration, RateLimitConfiguration>();
                }

                // Controllers
                services.AddSingleton <PoolApiController, PoolApiController>();
                services.AddSingleton <AdminApiController, AdminApiController>();

                // MVC
                services.AddSingleton((IComponentContext)container);
                services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

                services.AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                .AddControllersAsServices()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.Formatting = Formatting.Indented;
                });

                // Gzip Compression
                services.AddResponseCompression();

                // Cors
                services.AddCors();

                // WebSockets
                services.AddWebSocketManager();
            })
                      .Configure(app =>
            {
                if (enableApiRateLimiting)
                {
                    app.UseIpRateLimiting();
                }

                app.UseMiddleware <ApiExceptionHandlingMiddleware>();

                UseIpWhiteList(app, true, new[] { "/api/admin" }, clusterConfig.Api?.AdminIpWhitelist);
                UseIpWhiteList(app, true, new[] { "/metrics" }, clusterConfig.Api?.MetricsIpWhitelist);

                app.UseResponseCompression();
                app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
                app.UseWebSockets();
                app.MapWebSocketManager("/notifications", app.ApplicationServices.GetService <WebSocketNotificationsRelay>());
                app.UseMetricServer();
                app.UseMvc();
            })
                      .UseKestrel(options =>
            {
                options.Listen(address, clusterConfig.Api.Port, listenOptions =>
                {
                    if (clusterConfig.Api.SSLConfig?.Enabled == true)
                    {
                        listenOptions.UseHttps(clusterConfig.Api.SSLConfig.SSLPath, clusterConfig.Api.SSLConfig.SSLPassword);
                    }
                });
            })
                      .Build();

            webHost.Start();

            logger.Info(() => $"API Online @ {address}:{port}{(!enableApiRateLimiting ? " [rate-limiting disabled]" : string.Empty)}");
            logger.Info(() => $"Prometheus Metrics Online @ {address}:{port}/metrics");
            logger.Info(() => $"WebSocket notifications streaming @ {address}:{port}/notifications");
        }
Beispiel #24
0
 private static ILoggerFactory GetLoggerFactory(IWebHost webhost)
 {
     return(webhost.Services.GetService <Microsoft.Extensions.Logging.ILoggerFactory>());
 }
Beispiel #25
0
 /// <summary>
 /// Gets the <see cref="IServiceScopeFactory"/> from the <see cref="IWebHost"/>
 /// </summary>
 /// <returns>The service scope factory.</returns>
 /// <param name="webHost">Web host.</param>
 public static IServiceScopeFactory GetServiceScopeFactory(this IWebHost webHost)
 {
     return(webHost?.Services?.GetService(typeof(IServiceScopeFactory)) as IServiceScopeFactory);
 }
Beispiel #26
0
 /// <inheritdoc />
 public WebhostContainer(IWebHost WebHost) => _webHost = WebHost;
 public AspNetCoreServiceFactory(IWebHost webHost)
 {
     _webHost = webHost;
 }
 public WebHostManager(IWebHost host, ILog log)
 {
     this.host = host;
     this.log  = log;
 }
Beispiel #29
0
 internal void Init(IWebHost webHost, string protocal, bool isZiped = false)
 {
     this.WebHost  = webHost;
     this.Protocal = protocal;
     _isZiped      = isZiped;
 }
Beispiel #30
0
 public DependencyResolverHelper(IWebHost WebHost) => _webHost = WebHost;
Beispiel #31
0
        /// <summary>
        /// 主函数
        /// </summary>
        /// <param name="args">配置参数</param>
        public static void Main(string[] args)
        {
            //未捕获异常处理
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            //启动参数配置项
            IConfigurationRoot commandConfig = new ConfigurationBuilder()
                                               .AddCommandLine(args)
                                               .Build();
            SystemType system     = commandConfig.GetValue <SystemType>("System");
            int        listenPort = commandConfig.GetValue <int>("ListenPort");

            //初始化日志
            List <string> tempArgs = args.ToList();

            tempArgs.Add($"LogName={system}");
            args = tempArgs.ToArray();
            List <ILoggerProvider> loggerProviders = new List <ILoggerProvider>
            {
                new ConsoleLogger(LogLevel.Debug, LogLevel.Error),
                new FileLogger(LogLevel.Debug, LogLevel.Error, system.ToString(), LogPool.Directory, LogPool.HoldDays)
            };

            LogPool.SetLoggerProviders(loggerProviders);
            //添加日志和监听端口
            IWebHostBuilder builder = WebHost.CreateDefaultBuilder(args)
                                      .ConfigureLogging((hostingContext, logging) =>
            {
                logging.ClearProviders();
                foreach (ILoggerProvider loggerProvider in loggerProviders)
                {
                    logging.AddProvider(loggerProvider);
                }
            })
                                      .UseUrls($"http://+:{listenPort}/");

            //http配置项
            //if (system!=(int)SystemType.系统管理中心&&systemUrl != null)
            //{
            //    builder.ConfigureAppConfiguration((hostingContext, config) =>
            //    {
            //        config.AddHttpConfiguration(systemUrl, parameterType);
            //    });
            //}

            if (system == SystemType.Flow)
            {
                builder.UseStartup <FlowStartup>();
            }
            else if (system == SystemType.Density)
            {
                builder.UseStartup <DensityStartup>();
            }
            else
            {
                builder.UseStartup <SystemStartup>();
            }

            IWebHost webHost = builder.Build();

            LogPool.Logger.LogInformation((int)LogEvent.配置项, $"System {system}");
            LogPool.Logger.LogInformation((int)LogEvent.配置项, $"ListenPort {listenPort}");
            webHost.Run();
        }
        private void startWebServer(int port, WebSocketsHandler webSockets)
        {
            var baseDirectory = AppContext.BaseDirectory;
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(baseDirectory)
                .UseUrls($"http://localhost:{port}")
                .Configure(app =>
                {
                    app.UseWebSockets();

                    app.Use(async (http, next) =>
                    {
                        if (http.WebSockets.IsWebSocketRequest)
                            await webSockets.HandleSocket(http).ConfigureAwait(false);
                        else
                            await next().ConfigureAwait(false);
                    });

#if DEBUG
                    configureStaticFiles(app);
#endif

                    app.Run(async http =>
                    {
                        if (http.Request.Path == "/favicon.ico")
                        {
                            var stream =
                                GetType()
                                    .GetTypeInfo()
                                    .Assembly.GetManifestResourceStream("StorytellerRunner.favicon.ico");

                            http.Response.ContentType = "image/x-icon";
                            await stream.CopyToAsync(http.Response.Body).ConfigureAwait(false);

                            return;
                        }

                        try
                        {
                            string html;
                            if (http.Request.Path.HasValue && http.Request.Path.Value == "/preview")
                            {
                                html = ExportWriter.BuildPage(_application);
                            }
                            else
                            {
                                html = HomeEndpoint.BuildPage(_application, _input).ToString();
                            }


                            http.Response.ContentType = "text/html";
                            await http.Response.WriteAsync(html).ConfigureAwait(false);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.ToString());
                            throw;
                        }



                    });
                });

            _server = host.Start();
        }
Beispiel #33
0
 public ServiceHost(IWebHost webHost)
 {
     _webHost = webHost;
 }
Beispiel #34
0
 private static void HostBeginRequest(HttpApplication application, IWebHost host)
 {
     application.Context.Items["originalHttpContext"] = application.Context;
     host.BeginRequest();
 }
Beispiel #35
0
 public BusBuilder(IWebHost webHost, IBusClient bus)
 {
     _webHost = webHost;
     _bus     = bus;
 }
        public virtual ServiceStackHost Start(string[] urlBases)
        {
            this.WebHost = ConfigureHost(new WebHostBuilder(), urlBases).Build();
            this.WebHost.Start();

            return this;
        }
Beispiel #37
0
 public AspNetCoreServiceFactory(IWebHost webHost)
 {
     _webHost = webHost;
 }
        Task<string> ICommunicationListener.OpenAsync(CancellationToken cancellationToken)
        {
            this.serviceCancellation = new CancellationTokenSource();

            string ip = this.serviceContext.NodeContext.IPAddressOrFQDN;
            EndpointResourceDescription serviceEndpoint = this.serviceContext.CodePackageActivationContext.GetEndpoint(this.endpointName);
            EndpointProtocol protocol = serviceEndpoint.Protocol;
            int port = serviceEndpoint.Port;
            string host = "+";

            string listenUrl;
            string path = this.appPath != null ? this.appPath.TrimEnd('/') + "/" : "";

            if (this.serviceContext is StatefulServiceContext)
            {
                StatefulServiceContext statefulContext = this.serviceContext as StatefulServiceContext;

                listenUrl =
                    $"{serviceEndpoint.Protocol}://{host}:{serviceEndpoint.Port}/{path}{statefulContext.PartitionId}/{statefulContext.ReplicaId}/{Guid.NewGuid()}";
            }
            else
            {
                listenUrl = $"{serviceEndpoint.Protocol}://{host}:{serviceEndpoint.Port}/{path}";
            }

            this.webHost = this.build(listenUrl, new ServiceCancellation(this.serviceCancellation.Token));
            this.webHost.Start();

            return Task.FromResult(listenUrl.Replace("://+", "://" + ip));
        }
Beispiel #39
0
 private void StopHost(IWebHost host)
 {
     host?.StopAsync(TimeSpan.FromSeconds(5)).ContinueWith(t => host?.Dispose());
 }
Beispiel #40
0
 public MyWebHostService(IWebHost host) : base(host)
 {
     _logger = host.Services.GetRequiredService <ILogger <MyWebHostService> >();
 }
Beispiel #41
0
        public static ChutzpahWebServerHost Create(IWebHost webHost, string rootPath, int port)
        {
            var host = new ChutzpahWebServerHost(webHost, rootPath, port);

            return(host);
        }
Beispiel #42
0
        public static void RunAsCustomService(this IWebHost host)
        {
            var webHostService = new MyWebHostService(host);

            ServiceBase.Run(webHostService);
        }
Beispiel #43
0
 public ServiceHost(IWebHost webHost)
 {
     this.webHost = webHost;
 }
Beispiel #44
0
 /// <summary>
 /// Creates an instance of <c>WebHostService</c> which hosts the specified web application.
 /// </summary>
 /// <param name="host">The configured web host containing the web application to host in the Windows service.</param>
 public WebHostService(IWebHost host)
 {
     _host = host;
 }
Beispiel #45
0
 public HostBuilder(IWebHost webHost)
 {
     this.webHost = webHost;
 }
Beispiel #46
0
 public BusBuilder(IWebHost webHost, IBusClient busClient)
 {
     this.webHost   = webHost;
     this.busClient = busClient;
 }
Beispiel #47
0
 private static void HostEndRequest(HttpApplication application, IWebHost host)
 {
     host.EndRequest();
 }
Beispiel #48
0
        /// <summary>
        /// Migrates and seeds the database in development environment,
        /// calling this method in production doesn't do anything
        /// </summary>
        /// <param name="host"></param>
        private static void MigrateAndSeedDatabasesInDevelopment(IWebHost host)
        {
            // In development mode, apply migrations and seed the database
            using (var scope = host.Services.CreateScope())
            {
                var env = scope.ServiceProvider.GetRequiredService <IHostingEnvironment>();
                if (env.IsDevelopment())
                {
                    try
                    {
                        string adminEmail  = "*****@*****.**";
                        var    idContext   = scope.ServiceProvider.GetService <IdentityContext>();
                        var    userManager = scope.ServiceProvider.GetService <UserManager <User> >();
                        string externalId  = null;
                        if (idContext != null && userManager != null)
                        {
                            idContext.Database.Migrate();
                            var adminTask = userManager.FindByEmailAsync(adminEmail);
                            adminTask.Wait();
                            var admin = adminTask.Result;

                            if (admin == null)
                            {
                                admin = new User
                                {
                                    UserName       = adminEmail,
                                    Email          = adminEmail,
                                    EmailConfirmed = true
                                };
                                userManager.CreateAsync(admin, "Banan@123").Wait();
                            }

                            externalId = admin.Id;
                        }


                        int[] tenantIds = new[] { 101, 102 };

                        // (1) Admin Context migrated the usual way, add one tenant for dev and all translations
                        var adminContext = scope.ServiceProvider.GetRequiredService <AdminContext>();
                        adminContext.Database.Migrate();
                        if (!adminContext.Tenants.Any())
                        {
                            adminContext.Tenants.Add(new Tenant
                            {
                                Id      = tenantIds[0],
                                Name    = "Contoso, Inc.",
                                ShardId = 1
                            });

                            adminContext.Tenants.Add(new Tenant
                            {
                                Id      = tenantIds[1],
                                Name    = "Fabrikam & Co.",
                                ShardId = 1
                            });

                            adminContext.SaveChanges();
                        }

                        var globalUser = adminContext.GlobalUsers.FirstOrDefault(e => e.Email == adminEmail);
                        if (globalUser == null)
                        {
                            globalUser = new GlobalUser
                            {
                                Email      = adminEmail,
                                ExternalId = externalId,
                            };

                            globalUser.Memberships = new List <TenantMembership> {
                                new TenantMembership {
                                    TenantId = tenantIds[0]
                                }
                            };

                            adminContext.GlobalUsers.Add(globalUser);
                            adminContext.SaveChanges();
                        }

                        // Translations are seeded here for a better development experience since they change
                        // frequently, in the future this seeding will be moved to migrations instead
                        adminContext.Database.ExecuteSqlCommand("DELETE FROM [dbo].[Translations]");

                        adminContext.Translations.AddRange(Translation.TRANSLATIONS);
                        adminContext.SaveChanges();

                        foreach (var tenantId in tenantIds.Take(1))
                        {
                            // (2) Application Context requires special handling in development, don't resolve it with DI
                            var shardResolver = scope.ServiceProvider.GetRequiredService <IShardResolver>();
                            var appContext    = new ApplicationContext(shardResolver,
                                                                       new DesignTimeTenantIdProvider(tenantId),
                                                                       new DesignTimeUserIdProvider(),
                                                                       new DesignTimeTenantUserInfoAccessor());

                            appContext.Database.Migrate();


                            // Add the views
                            appContext.Database.ExecuteSqlCommand($"DELETE FROM [dbo].[Views] WHERE TenantId = {tenantId}");
                            string[] viewIds = { "measurement-units", "individuals", "organizations", "roles", "local-users", "views", "settings" };

                            foreach (var viewId in viewIds)
                            {
                                var view = new View
                                {
                                    Id       = viewId,
                                    IsActive = true
                                };

                                appContext.Views.Add(view);
                                appContext.Entry(view).Property("TenantId").CurrentValue = tenantId;
                            }

                            // Add settings
                            var now = DateTimeOffset.Now;
                            if (!appContext.Settings.Any())
                            {
                                // Add the settings
                                var settings = new Settings
                                {
                                    PrimaryLanguageId       = "en",
                                    SecondaryLanguageId     = "ar",
                                    PrimaryLanguageSymbol   = "En",
                                    SecondaryLanguageSymbol = "ع",
                                    ShortCompanyName2       = "كونتوسو المحدودة",
                                    ProvisionedAt           = now,
                                    ModifiedAt       = now,
                                    ModifiedById     = 1,
                                    ShortCompanyName = "Contoso, Inc."
                                };
                                appContext.Settings.Add(settings);
                                appContext.Entry(settings).Property("TenantId").CurrentValue = tenantId;
                            }

                            appContext.SaveChanges();


                            // Add first user
                            try
                            {
                                var cmd = appContext.Database.GetDbConnection().CreateCommand();
                                appContext.Database.ExecuteSqlCommand(
                                    @"
DECLARE @NextId INT = IDENT_CURRENT('[dbo].[LocalUsers]') + 1;
INSERT INTO [dbo].[LocalUsers] (Email, ExternalId, CreatedAt, ModifiedAt, Name, Name2, CreatedById, ModifiedById, TenantId)
                            VALUES ({0}, {1}, {2}, {2}, {3}, {4}, @NextId, @NextId, {5})",
                                    adminEmail,         // {0}
                                    externalId,         // {1}
                                    now,                // {2}
                                    "Banan IT Support", // {3}
                                    "فريق مساندة بنان",
                                    tenantId);          // {4}
                            }
                            catch { }
                        }
                    }
                    catch (Exception ex)
                    {
                        var logger = scope.ServiceProvider.GetRequiredService <ILogger <Program> >();
                        logger.LogError(ex, "An error occurred while migrating or seeding the databases.");
                    }
                }
            }
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.WebHost?.Dispose();
                this.WebHost = null;
            }

            base.Dispose(disposing);
        }
        public override void Dispose()
        {
            this.WebHost?.Dispose();
            this.WebHost = null;

            base.Dispose();
        }