public void Stop()
 {
     if (_connector != null)
     {
         _connector.Disconnect();
         _connector.Dispose();
         _connector = null;
     }
 }
Exemple #2
0
        static async Task <int> Main(string[] args)
        {
            try
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.Verbose()
                             .WriteTo.Console()
                             .WriteTo.Seq("http://localhost:5341")
                             .CreateLogger();

                Log.Logger.Information("Starting interceptor sample.");

                // Config
                var configBuilder = new ConfigurationBuilder();
                configBuilder.AddJsonFile("appsettings.json", true, false);
                var config = configBuilder.Build();

                // DI
                var services = new ServiceCollection();
                services.AddSingleton <ILogger>(Log.Logger);
                services.AddOnPremiseConnectorServices();

                // Add Interceptors
                services.AddTransient <IOnPremiseRequestInterceptor, SampleRequestInterceptor>();
                services.AddTransient <IOnPremiseResponseInterceptor, SampleResponseInterceptor>();

                var serviceProvider = services.BuildServiceProvider();

                // Connector
                var connector = new RelayServerConnector(typeof(Program).Assembly, config["RelayServer:User"], config["RelayServer:Password"], new Uri(config["RelayServer:Url"]), 30, serviceProvider);
                connector.RegisterOnPremiseTarget("lh", new Uri("http://localhost:5000"), false);

                await connector.ConnectAsync();

                // Main loop
                bool cancelled = false;
                connector.Disconnected += (s, e) => cancelled = true;
                Console.CancelKeyPress += (s, e) => cancelled = true;

                while (!cancelled)
                {
                    await Task.Delay(150);
                }
            }
            catch (Exception ex)
            {
                Log.Logger.Fatal(ex, "A fatal error occured.");
                return(1);
            }
            finally
            {
                Log.CloseAndFlush();
            }

            Log.Logger.Information("Interceptor sample quit.");
            return(0);
        }
        public async Task Start()
        {
            try
            {
                var section = (RelayServerSection)ConfigurationManager.GetSection("relayServer");

                if (section.OnPremiseTargets.Count == 0)
                {
                    throw new ConfigurationErrorsException("At least one On-Premise Target needs to be configured.");
                }

                switch (section.Security.AuthenticationType)
                {
                case AuthenticationType.Identity:
                    if (String.IsNullOrEmpty(section.Security.Identity.UserName))
                    {
                        throw new ConfigurationErrorsException(
                                  "The user name cannot be null or empty when using authentication type 'Identity'.");
                    }

                    _connector = new RelayServerConnector(section.Security.Identity.UserName,
                                                          section.Security.Identity.Password, new Uri(section.BaseUrl),
                                                          (int)section.RequestTimeout.TotalSeconds);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                _connector.RelayedRequestHeader = "X-Relayed";

                foreach (var onPremiseTarget in section.OnPremiseTargets.Cast <OnPremiseTargetElement>())
                {
                    _connector.RegisterOnPremiseTarget(onPremiseTarget.Key, new Uri(onPremiseTarget.BaseUrl));
                }


                await _connector.Connect();
            }
            catch (Exception e)
            {
                _logger.FatalException("Fatal exception occured", e);
                throw;
            }
        }
Exemple #4
0
        public async Task StartAsync()
        {
            try
            {
                var section = (RelayServerSection)ConfigurationManager.GetSection("relayServer");

                if (section.OnPremiseTargets.Count == 0)
                {
                    throw new ConfigurationErrorsException("At least one on-premise target needs to be configured");
                }

                if (section.IgnoreSslErrors)
                {
                    ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true;
                }

                switch (section.Security.AuthenticationType)
                {
                case AuthenticationType.Identity:
                    if (String.IsNullOrEmpty(section.Security.Identity.UserName))
                    {
                        throw new ConfigurationErrorsException("The user name cannot be null or empty when using authentication type 'Identity'");
                    }

#pragma warning disable CS0618 // Type or member is obsolete; Justification: Backward-compatibility with older servers that do not yet provide server-side config

                    _connector = new RelayServerConnector(Assembly.GetEntryAssembly(),
                                                          section.Security.Identity.UserName,
                                                          section.Security.Identity.Password,
                                                          new Uri(section.BaseUrl),
                                                          (int)section.RequestTimeout.TotalSeconds,
                                                          (int)section.Security.AccessTokenRefreshWindow.TotalSeconds,
                                                          null,
                                                          section.LogSensitiveData);

#pragma warning restore CS0618 // Type or member is obsolete

                    _connector.Disconnected += (s, e) =>
                    {
                        _logger.Warning("Connection to the RelayServer was actively closed. In a non-demo environment you could shutdown the service now.");
                    };

                    break;

                case AuthenticationType.None:
                    throw new ConfigurationErrorsException("Authentication type 'None' is not a valid value.");

                default:
                    throw new ArgumentOutOfRangeException();
                }

                _connector.RelayedRequestHeader = "X-Relayed";

                foreach (var onPremiseTarget in section.OnPremiseTargets.OfType <OnPremiseWebTargetElement>())
                {
                    _connector.RegisterOnPremiseTarget(onPremiseTarget.Key, new Uri(onPremiseTarget.BaseUrl), onPremiseTarget.FollowRedirects);
                }

                foreach (var onPremiseTarget in section.OnPremiseTargets.OfType <OnPremiseInProcTargetElement>())
                {
                    Type handlerType;

                    var parts = onPremiseTarget.TypeName.Split(',');
                    if (parts.Length == 2)
                    {
                        var assembly = Assembly.Load(parts[1].Trim());
                        handlerType = assembly.GetType(parts[0].Trim());
                    }
                    else
                    {
                        handlerType = Type.GetType(parts[0].Trim());
                    }

                    if (handlerType == null)
                    {
                        throw new ConfigurationErrorsException("Unknown handler type: " + onPremiseTarget.TypeName);
                    }

                    if (!typeof(IOnPremiseInProcHandler).IsAssignableFrom(handlerType))
                    {
                        throw new ConfigurationErrorsException("The handler type " + handlerType.Name + " does not implement the interface \"IOnPremiseInProcHandler\".");
                    }

                    _connector.RegisterOnPremiseTarget(onPremiseTarget.Key, handlerType);
                }

                var timeout = (int)section.RequestTimeout.TotalMilliseconds;
                ServicePointManager.FindServicePoint(new Uri(section.BaseUrl)).ConnectionLeaseTimeout = timeout;
                if (timeout < ServicePointManager.DnsRefreshTimeout)
                {
                    ServicePointManager.DnsRefreshTimeout = timeout;
                }

                await _connector.ConnectAsync().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger?.Fatal(ex, "Fatal exception occured");
                throw;
            }
        }