示例#1
0
        private void StartServers()
        {
            try
            {
                IsStarted = true;
#if NETSTANDARD1_3
                _logger.Info("WireMock.Net server using netstandard1.3");
#elif NETSTANDARD2_0
                _logger.Info("WireMock.Net server using netstandard2.0");
#elif NET46
                _logger.Info("WireMock.Net server using .net 4.6.1 or higher");
#endif

#if NETSTANDARD1_3
                _host.Run(_cts.Token);
#else
                _host.RunAsync(_cts.Token).Wait();
#endif
            }
            catch (Exception e)
            {
                _runningException = e;
                _logger.Error(e.ToString());
            }
            finally
            {
                IsStarted = false;
            }
        }
示例#2
0
        private void StartServers()
        {
            try
            {
                var appLifetime = (IApplicationLifetime)_host.Services.GetService(typeof(IApplicationLifetime));
                appLifetime.ApplicationStarted.Register(() => IsStarted = true);

#if NETSTANDARD1_3
                _logger.Info("WireMock.Net server using netstandard1.3");
#elif NETSTANDARD2_0
                _logger.Info("WireMock.Net server using netstandard2.0");
#elif NET46
                _logger.Info("WireMock.Net server using .net 4.6.1 or higher");
#endif

#if NETSTANDARD1_3
                _host.Run(_cts.Token);
#else
                _host.RunAsync(_cts.Token).Wait();
#endif
            }
            catch (Exception e)
            {
                _runningException = e;
                _logger.Error(e.ToString());
            }
            finally
            {
                IsStarted = false;
            }
        }
示例#3
0
        static async Task Main(string[] args)
        {
            if (!StandAloneApp.TryStart(args, out Server, Logger))
            {
                return;
            }

            Logger.Info("Press Ctrl+C to shut down");

            Console.CancelKeyPress += (s, e) =>
            {
                Stop("CancelKeyPress");
            };

            System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx =>
            {
                Stop("AssemblyLoadContext.Default.Unloading");
            };

            while (true)
            {
                Logger.Info("Server running : {IsStarted}", Server.IsStarted);
                await Task.Delay(SleepTime);
            }
        }
示例#4
0
        private void StartServers()
        {
#if NET46
            _logger.Info("WireMock.Net server using .net 4.6.1 or higher");
#else
            _logger.Info("WireMock.Net server using .net 4.5.x");
#endif
            var servers = new List <IDisposable>();

            try
            {
                var requestMapper  = new OwinRequestMapper();
                var responseMapper = new OwinResponseMapper(_options);
                var matcher        = new MappingMatcher(_options);

                /*
                 * Action<IAppBuilder> startup = app =>
                 * {
                 * app.Use<GlobalExceptionMiddleware>(_options, responseMapper);
                 * _options.PreWireMockMiddlewareInit?.Invoke(app);
                 * app.Use<WireMockMiddleware>(_options, requestMapper, responseMapper, matcher);
                 * _options.PostWireMockMiddlewareInit?.Invoke(app);
                 * };*/
                m_appBuilder.Use <GlobalExceptionMiddleware>(_options, responseMapper);
                m_appBuilder.Use <IgnorePrefixesMiddleware>(_options);
                _options.PreWireMockMiddlewareInit?.Invoke(m_appBuilder);
                m_appBuilder.Use <WireMockMiddleware>(_options, requestMapper, responseMapper, matcher);
                _options.PostWireMockMiddlewareInit?.Invoke(m_appBuilder);

                /*foreach (var url in Urls)
                 * {
                 * servers.Add(WebApp.Start(url, startup));
                 * }*/

                IsStarted = true;

                // WaitHandle is signaled when the token is cancelled,
                // which will be more efficient than Thread.Sleep in while loop
                _cts.Token.WaitHandle.WaitOne();
            }
            catch (Exception e)
            {
                // Expose exception of starting host, otherwise it's hard to be troubleshooting if keeping quiet
                // For example, WebApp.Start will fail with System.MissingMemberException if Microsoft.Owin.Host.HttpListener.dll is being located
                // https://stackoverflow.com/questions/25090211/owin-httplistener-not-located/31369857
                _runningException = e;
                _logger.Error(e.ToString());
            }
            finally
            {
                IsStarted = false;
                // Dispose all servers in finally block to make sure clean up allocated resource on error happening
                servers.ForEach(s => s.Dispose());
            }
        }
        private Task RunHost(CancellationToken token)
        {
            try
            {
                var appLifetime = (IApplicationLifetime)_host.Services.GetService(typeof(IApplicationLifetime));
                appLifetime.ApplicationStarted.Register(() =>
                {
                    var addresses = _host.ServerFeatures
                                    .Get <Microsoft.AspNetCore.Hosting.Server.Features.IServerAddressesFeature>()
                                    .Addresses;

                    foreach (string address in addresses)
                    {
                        Urls.Add(address.Replace("0.0.0.0", "localhost"));

                        PortUtils.TryExtract(address, out string protocol, out string host, out int port);
                        Ports.Add(port);
                    }

                    IsStarted = true;
                });

#if NETSTANDARD1_3
                _logger.Info("WireMock.Net server using netstandard1.3");
#elif NETSTANDARD2_0
                _logger.Info("WireMock.Net server using netstandard2.0");
#elif NETSTANDARD2_1
                _logger.Info("WireMock.Net server using netstandard2.1");
#elif NETCOREAPP3_1
                _logger.Info("WireMock.Net server using .NET Core 3.1");
#elif NET46
                _logger.Info("WireMock.Net server using .NET Framework 4.6.1 or higher");
#endif

#if NETSTANDARD1_3
                return(Task.Run(() =>
                {
                    _host.Run(token);
                }));
#else
                return(_host.RunAsync(token));
#endif
            }
            catch (Exception e)
            {
                _runningException = e;
                _logger.Error(e.ToString());

                IsStarted = false;

                return(Task.CompletedTask);
            }
        }
示例#6
0
        private Task RunHost(CancellationToken token)
        {
            try
            {
                var appLifetime = (IApplicationLifetime)_host.Services.GetService(typeof(IApplicationLifetime));
                appLifetime.ApplicationStarted.Register(() =>
                {
                    IsStarted = true;
                });

#if NETSTANDARD1_3
                _logger.Info("WireMock.Net server using netstandard1.3");
#elif NETSTANDARD2_0
                _logger.Info("WireMock.Net server using netstandard2.0");
#elif NET46
                _logger.Info("WireMock.Net server using .net 4.6.1 or higher");
#endif
#if NETSTANDARD1_3
                return(Task.Run(() =>
                {
                    _host.Run(token);
                }));
#else
                return(_host.RunAsync(token));
#endif
            }
            catch (Exception e)
            {
                _runningException = e;
                _logger.Error(e.ToString());

                IsStarted = false;

                return(Task.CompletedTask);
            }
        }
 public void AllowPartialMapping(bool allow = true)
 {
     _logger.Info("AllowPartialMapping is set to {0}", allow);
     _options.AllowPartialMapping = allow;
 }
        private FluentMockServer(IFluentMockServerSettings settings)
        {
            settings.Logger = settings.Logger ?? new WireMockConsoleLogger();

            _logger            = settings.Logger;
            _fileSystemHandler = settings.FileSystemHandler ?? new LocalFileSystemHandler();

            _logger.Info("WireMock.Net by Stef Heyenrath (https://github.com/WireMock-Net/WireMock.Net)");
            _logger.Debug("WireMock.Net server settings {0}", JsonConvert.SerializeObject(settings, Formatting.Indented));

            if (settings.Urls != null)
            {
                Urls = settings.Urls.ToArray();
            }
            else
            {
                int port = settings.Port > 0 ? settings.Port.Value : PortUtils.FindFreeTcpPort();
                Urls = new[] { $"{(settings.UseSSL == true ? "https" : "http")}://localhost:{port}" };
            }

            _options.PreWireMockMiddlewareInit  = settings.PreWireMockMiddlewareInit;
            _options.PostWireMockMiddlewareInit = settings.PostWireMockMiddlewareInit;
            _options.Logger = _logger;

#if USE_ASPNETCORE
            _httpServer = new AspNetCoreSelfHost(_options, Urls);
#else
            _httpServer = new OwinSelfHost(_options, Urls);
#endif
            Ports = _httpServer.Ports;

            var startTask = _httpServer.StartAsync();

            using (var ctsStartTimeout = new CancellationTokenSource(settings.StartTimeout))
            {
                while (!_httpServer.IsStarted)
                {
                    // Throw exception if service start fails
                    if (_httpServer.RunningException != null)
                    {
                        throw new WireMockException($"Service start failed with error: {_httpServer.RunningException.Message}", _httpServer.RunningException);
                    }

                    if (ctsStartTimeout.IsCancellationRequested)
                    {
                        // In case of an aggregate exception, throw the exception.
                        if (startTask.Exception != null)
                        {
                            throw new WireMockException($"Service start failed with error: {startTask.Exception.Message}", startTask.Exception);
                        }

                        // Else throw TimeoutException
                        throw new TimeoutException($"Service start timed out after {TimeSpan.FromMilliseconds(settings.StartTimeout)}");
                    }

                    ctsStartTimeout.Token.WaitHandle.WaitOne(ServerStartDelayInMs);
                }
            }

            if (settings.AllowPartialMapping == true)
            {
                AllowPartialMapping();
            }

            if (settings.StartAdminInterface == true)
            {
                if (!string.IsNullOrEmpty(settings.AdminUsername) && !string.IsNullOrEmpty(settings.AdminPassword))
                {
                    SetBasicAuthentication(settings.AdminUsername, settings.AdminPassword);
                }

                InitAdmin();
            }

            if (settings.ReadStaticMappings == true)
            {
                ReadStaticMappings();
            }

            if (settings.WatchStaticMappings == true)
            {
                WatchStaticMappings();
            }

            if (settings.ProxyAndRecordSettings != null)
            {
                InitProxyAndRecord(settings);
            }

            if (settings.RequestLogExpirationDuration != null)
            {
                SetRequestLogExpirationDuration(settings.RequestLogExpirationDuration);
            }

            if (settings.MaxRequestLogCount != null)
            {
                SetMaxRequestLogCount(settings.MaxRequestLogCount);
            }
        }