public static bool TryLoad(string path, out FileConfiguration fileConfiguration)
 {
     fileConfiguration = null;
     var parser = new EditorConfigParser();
     var configurations = parser.Parse(path);
     if (!configurations.Any()) return false;
     fileConfiguration = configurations.First();
     return true;
 }
 internal InitialCleanup(ITextDocument textDocument, _DTE ide, FileConfiguration settings)
 {
     _doc = ide.Documents.OfType<Document>()
         .FirstOrDefault(x => x.FullName == textDocument.FilePath);
     if (_doc != null)
         _textDoc = (TextDocument) _doc.Object("TextDocument");
     _ide = ide;
     _settings = settings;
     _eol = settings.EndOfLine();
 }
        public TextViewMonitor(IWpfTextView view, ITextDocument document, DTE app, ErrorListProvider messageList)
        {
            _view = view;
            _doc = document;
            _app = app;
            _settingsManager = new SettingsManager(view, document, messageList);
            _settings = _settingsManager.Settings;

            if (_settings != null)
            {
                _globalSettings = new GlobalSettings(view, app, _settings);
                _view.GotAggregateFocus += ViewOnGotAggregateFocus;
            }

            document.FileActionOccurred += FileActionOccurred;
            view.Closed += Closed;
        }
        internal GlobalSettings(IWpfTextView view, DTE app, FileConfiguration settings)
        {
            _view = view;
            _app = app;
            _settings = settings;

            try
            {
                var type = _view.TextDataModel.ContentType.TypeName;
                _editorProps = _app.Properties["TextEditor", type];
            }
            catch
            {
                // If the above code didn't work, this particular content type
                // didn't need its settings changed anyhow
            }

            view.GotAggregateFocus += GotAggregateFocus;
            view.LostAggregateFocus += LostAggregateFocus;
        }
        /// <summary>
        /// Loads the settings for the given file path
        /// </summary>
        internal void LoadSettings(string path)
        {
            ClearMessage();
            _settings = null;

            // Prevent parsing of internet-located documents,
            // or documents that do not have proper paths.
            if (path.StartsWith("http:", StringComparison.OrdinalIgnoreCase)
                || path.Equals("Temp.txt"))
                return;

            try
            {
                if (!ConfigLoader.TryLoad(path, out _settings))
                    return;

                _localSettings = new LocalSettings(_view, Settings);
                _localSettings.Apply();
            }
            catch (Exception e)
            {
                ShowError(path, "EditorConfig core error: " + e.Message);
            }
        }
        public void should_fix_issue_194()
        {
            var consulPort = 8503;
            var downstreamServiceOneUrl       = "http://localhost:8362";
            var downstreamServiceTwoUrl       = "http://localhost:8330";
            var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}";

            var configuration = new FileConfiguration
            {
                ReRoutes = new List <FileReRoute>
                {
                    new FileReRoute
                    {
                        DownstreamPathTemplate = "/api/user/{user}",
                        DownstreamScheme       = "http",
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = 8362,
                            }
                        },
                        UpstreamPathTemplate = "/api/user/{user}",
                        UpstreamHttpMethod   = new List <string> {
                            "Get"
                        },
                    },
                    new FileReRoute
                    {
                        DownstreamPathTemplate = "/api/product/{product}",
                        DownstreamScheme       = "http",
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = 8330,
                            }
                        },
                        UpstreamPathTemplate = "/api/product/{product}",
                        UpstreamHttpMethod   = new List <string> {
                            "Get"
                        },
                    }
                },
                GlobalConfiguration = new FileGlobalConfiguration()
                {
                    ServiceDiscoveryProvider = new FileServiceDiscoveryProvider()
                    {
                        Host = "localhost",
                        Port = consulPort
                    }
                }
            };

            this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, "/api/user/info", 200, "user"))
            .And(x => x.GivenProductServiceTwoIsRunning(downstreamServiceTwoUrl, "/api/product/info", 200, "product"))
            .And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl))
            .And(x => _steps.GivenThereIsAConfiguration(configuration))
            .And(x => _steps.GivenOcelotIsRunning())
            .When(x => _steps.WhenIGetUrlOnTheApiGateway("/api/user/info?id=1"))
            .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
            .And(x => _steps.ThenTheResponseBodyShouldBe("user"))
            .When(x => _steps.WhenIGetUrlOnTheApiGateway("/api/product/info?id=1"))
            .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
            .And(x => _steps.ThenTheResponseBodyShouldBe("product"))
            .BDDfy();
        }
 protected override Configuration CreateConfigObject()
 {
     FileConfiguration fc = new FileConfiguration(SystemName);
     fc.Initialize();
     return fc;
 }
		void RunUpEndpoint()
		{
			// OMITTED: No empty try-catch
			//try
			//{
				//this.Logger.Debug("1 RunUpEndpoint()");

				// Get configuration settings
				XDocument confDoc = XDocument.Load("SipEndpoint.config");
				this.SetAppLevelConfiguration(confDoc.Root);

				/*  Matching levels between:
				 *  -----------------------------|--------------------------------
				 *   Platform SDK logging levels | SIP Endpoint SDK logging levels
				 *  -----------------------------|--------------------------------
				 *    All = 0                    |       NA
				 *    Debug = 1                  |       4
				 *    Trace = 2                  |       3
				 *    Interaction = 3            |       2
				 *    Standard = 4               |       1
				 *    Alarm = 5                  |       0
				 *    None = 6                   |       NA
				 *  -----------------------------|--------------------------------
				 * 
				 *  SIP Endpoint SDK logging levels
				 *  ===============================
				 *   Fatal = 0
				 *   Error = 1
				 *   Warning = 2
				 *   Info = 3
				 *   Debug = 4
				 */

				if (this.enableLogging)
				{
					// Setup logger
					LogConfiguration logConf = new LogConfiguration();
					logConf.Verbose = VerboseLevel.All;
					logConf.Targets.Trace.IsEnabled = true;

					switch (this.logLevel)
					{
						case 0:
							logConf.Targets.Trace.Verbose = VerboseLevel.Alarm;
							break;
						case 1:
							logConf.Targets.Trace.Verbose = VerboseLevel.Standard;
							break;
						case 2:
							logConf.Targets.Trace.Verbose = VerboseLevel.Interaction;
							break;
						case 3:
							logConf.Targets.Trace.Verbose = VerboseLevel.Trace;
							break;
						case 4:
							logConf.Targets.Trace.Verbose = VerboseLevel.Debug;
							break;
					}

					FileConfiguration fileConf = new FileConfiguration(true, logConf.Targets.Trace.Verbose, "logs" + Path.DirectorySeparatorChar + this.logFile);
					fileConf.MessageHeaderFormat = MessageHeaderFormat.Medium;

					logConf.Targets.Files.Add(fileConf);

					this.endpointLogger = LoggerFactory.CreateRootLogger("SipEndpoint", logConf);
					this.Logger = this.endpointLogger.CreateChildLogger("QuickStart");

					this.endpoint = SipEndpoint.EndpointFactory.CreateSipEndpoint(this.endpointLogger);
				}
				else
				{
					// Setup NULL logger
					this.nullLogger = new NullLogger();
					this.Logger = this.nullLogger;
					this.endpoint = SipEndpoint.EndpointFactory.CreateSipEndpoint();
				}

				// OMITTED: Endpoint configuration

				this.provider = this.endpoint.Resolve("IEndpointPovider") as SipProvider;

				// Setup Endpoint Logger
				if (this.enableLogging)
					this.provider.SetEndpointLogger(this.endpointLogger);
				else
					this.provider.SetEndpointLogger(this.nullLogger);

				this.endpoint.ApplyConfiguration(confDoc.Root);

				// OMITTED:
				//this.endpoint.BeginActivate();

				// At this point the actual configuration can be updated and
				// Then the Endpoint can be started
				// The next two lines of the code are unnecessary if configuration
				// is not going to be changed

				// Get updated configuration settings
				//confDoc = XDocument.Load("SipEndpoint.config");
				//this.endpoint.ApplyConfiguration(confDoc.Root);

				// The actual SIP Endpoint Start
				// OMITTED:
				//this.endpoint.Start();
				//this.Logger.Debug("this.endpoint.Start()");
			
			// OMITTED: No empty try-catch
			//}
			//catch (Exception exception)
			//{
			//	//this.Logger.Debug("2 RunUpEndpoint()" + exception.Message);
			//	//System.Windows.Forms.MessageBox.Show(exception.Message);
			//}
		}
Example #9
0
        public void should_clear_region()
        {
            var initialConfiguration = new FileConfiguration
            {
                GlobalConfiguration = new FileGlobalConfiguration
                {
                },
                ReRoutes = new List <FileReRoute>()
                {
                    new FileReRoute()
                    {
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = 80,
                            }
                        },
                        DownstreamScheme       = "https",
                        DownstreamPathTemplate = "/",
                        UpstreamHttpMethod     = new List <string> {
                            "get"
                        },
                        UpstreamPathTemplate = "/",
                        FileCacheOptions     = new FileCacheOptions
                        {
                            TtlSeconds = 10
                        }
                    },
                    new FileReRoute()
                    {
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = 80,
                            }
                        },
                        DownstreamScheme       = "https",
                        DownstreamPathTemplate = "/",
                        UpstreamHttpMethod     = new List <string> {
                            "get"
                        },
                        UpstreamPathTemplate = "/test",
                        FileCacheOptions     = new FileCacheOptions
                        {
                            TtlSeconds = 10
                        }
                    }
                }
            };

            var regionToClear = "gettest";

            this.Given(x => GivenThereIsAConfiguration(initialConfiguration))
            .And(x => GivenOcelotIsRunning())
            .And(x => GivenIHaveAnOcelotToken("/administration"))
            .And(x => GivenIHaveAddedATokenToMyRequest())
            .When(x => WhenIDeleteOnTheApiGateway($"/administration/outputcache/{regionToClear}"))
            .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.NoContent))
            .BDDfy();
        }
Example #10
0
        public async Task <Response <FileConfiguration> > Get()
        {
            var config = _cache.Get(_option.CachePrefix + "FileConfiguration", "");

            if (config != null)
            {
                return(new OkResponse <FileConfiguration>(config));
            }

            var file = new FileConfiguration();

            // 提取全局配置信息
            var globalResult = await _ocelotGlobalConfigurationRepository.FindByNameAsync(_option.GatewayName);

            if (globalResult != null)
            {
                var fileGlobalConfig = new FileGlobalConfiguration
                {
                    BaseUrl          = globalResult.BaseUrl,
                    DownstreamScheme = globalResult.DownstreamScheme,
                    RequestIdKey     = globalResult.RequestIdKey
                };

                if (globalResult.HttpHandlerOption != null)
                {
                    var httpHandlerOption = globalResult.HttpHandlerOption;
                    fileGlobalConfig.HttpHandlerOptions = new FileHttpHandlerOptions
                    {
                        AllowAutoRedirect       = httpHandlerOption.AllowAutoRedirect,
                        UseCookieContainer      = httpHandlerOption.UseCookieContainer,
                        UseProxy                = httpHandlerOption.UseProxy,
                        UseTracing              = httpHandlerOption.UseTracing,
                        MaxConnectionsPerServer = httpHandlerOption.MaxConnectionsPerServer
                    };
                }
                if (globalResult.LoadBalancerOption != null)
                {
                    var loadBalancerOption = globalResult.LoadBalancerOption;
                    fileGlobalConfig.LoadBalancerOptions = new FileLoadBalancerOptions
                    {
                        Expiry = loadBalancerOption.Expiry,
                        Key    = loadBalancerOption.Key,
                        Type   = loadBalancerOption.Type
                    };
                }
                if (globalResult.QoSOption != null)
                {
                    var qoSOption = globalResult.QoSOption;
                    fileGlobalConfig.QoSOptions = new FileQoSOptions
                    {
                        ExceptionsAllowedBeforeBreaking = qoSOption.ExceptionsAllowedBeforeBreaking,
                        DurationOfBreak = qoSOption.DurationOfBreak,
                        TimeoutValue    = qoSOption.TimeoutValue
                    };
                }
                if (globalResult.ServiceDiscoveryProvider != null)
                {
                    var serviceDiscoveryProvider = globalResult.ServiceDiscoveryProvider;
                    fileGlobalConfig.ServiceDiscoveryProvider = new FileServiceDiscoveryProvider
                    {
                        ConfigurationKey = serviceDiscoveryProvider.ConfigurationKey,
                        Host             = serviceDiscoveryProvider.Host,
                        Namespace        = serviceDiscoveryProvider.Namespace,
                        PollingInterval  = serviceDiscoveryProvider.PollingInterval,
                        Port             = serviceDiscoveryProvider.Port,
                        Token            = serviceDiscoveryProvider.Token,
                        Type             = serviceDiscoveryProvider.Type
                    };
                }
                if (globalResult.RateLimitOption != null)
                {
                    var rateLimitOption = globalResult.RateLimitOption;
                    fileGlobalConfig.RateLimitOptions = new FileRateLimitOptions
                    {
                        ClientIdHeader          = rateLimitOption.ClientIdHeader,
                        DisableRateLimitHeaders = rateLimitOption.DisableRateLimitHeaders,
                        HttpStatusCode          = rateLimitOption.HttpStatusCode,
                        QuotaExceededMessage    = rateLimitOption.QuotaExceededMessage,
                        RateLimitCounterPrefix  = rateLimitOption.RateLimitCounterPrefix
                    };
                }

                file.GlobalConfiguration = fileGlobalConfig;
                //TODO: Optimize code structure
                if (globalResult?.ReRoutes?.Count > 0)
                {
                    _logger.LogInformation($"ReRoute Count:{ globalResult?.ReRoutes?.Count }");
                    //提取路由信息
                    var reRoutes = globalResult.ReRoutes.OrderBy(c => c.Sort);

                    List <FileReRoute> fileReRoutes = new List <FileReRoute>();
                    foreach (var route in reRoutes)
                    {
                        _logger.LogInformation($"Loading ReRoute: {route.Name}");
                        var r = new FileReRoute
                        {
                            Key                    = route.Key,
                            Priority               = route.Priority,
                            ServiceName            = route.ServiceName,
                            Timeout                = route.Timeout,
                            DownstreamPathTemplate = route.DownstreamPathTemplate,
                            DownstreamScheme       = route.DownstreamScheme,
                            UpstreamHost           = route.UpstreamHost,
                            DangerousAcceptAnyServerCertificateValidator = route.DangerousAcceptAnyServerCertificateValidator,
                            DownstreamHttpMethod         = route.DownstreamHttpMethod,
                            RequestIdKey                 = route.RequestIdKey,
                            UpstreamPathTemplate         = route.UpstreamPathTemplate,
                            ServiceNamespace             = route.ServiceNamespace,
                            ReRouteIsCaseSensitive       = route.ReRouteIsCaseSensitive,
                            AddClaimsToRequest           = route.AddClaimsToRequests,
                            AddHeadersToRequest          = route.AddHeadersToRequests,
                            AddQueriesToRequest          = route.AddQueriesToRequests,
                            ChangeDownstreamPathTemplate = route.ChangeDownstreamPathTemplates,
                            DownstreamHeaderTransform    = route.DownstreamHeaderTransforms,
                            RouteClaimsRequirement       = route.RouteClaimsRequirements,
                            UpstreamHeaderTransform      = route.UpstreamHeaderTransforms,
                            // AuthenticationOptions = null,
                            // DelegatingHandlers = null,
                            // DownstreamHostAndPorts = null,
                            // FileCacheOptions = null,
                            // HttpHandlerOptions = null,
                            // LoadBalancerOptions = null,
                            // QoSOptions = null,
                            // RateLimitOptions = null,
                            // SecurityOptions = null,
                            // UpstreamHttpMethod = null
                        };
                        if (route.AuthenticationOption != null)
                        {
                            var authenticationOption = route.AuthenticationOption;
                            r.AuthenticationOptions = new FileAuthenticationOptions
                            {
                                AuthenticationProviderKey = authenticationOption.AuthenticationProviderKey,
                                AllowedScopes             = authenticationOption.AllowedScopes.Select(c => c.Scope).ToList()
                            };
                        }
                        if (route.DelegatingHandlers != null && route.DelegatingHandlers.Count > 0)
                        {
                            r.DelegatingHandlers = route.DelegatingHandlers.Select(c => c.Delegating).ToList();
                        }
                        if (route.DownstreamHostAndPorts != null && route.DownstreamHostAndPorts.Count > 0)
                        {
                            var downstreamHostAndPorts = new List <FileHostAndPort>();
                            foreach (var host in route.DownstreamHostAndPorts)
                            {
                                downstreamHostAndPorts.Add(new FileHostAndPort
                                {
                                    Host = host.Host,
                                    Port = host.Port
                                });
                            }
                            r.DownstreamHostAndPorts = downstreamHostAndPorts;
                        }
                        if (route.CacheOption != null)
                        {
                            var cacheOption = route.CacheOption;
                            r.FileCacheOptions = new FileCacheOptions
                            {
                                TtlSeconds = cacheOption.TtlSeconds,
                                Region     = cacheOption.Region
                            };
                        }
                        if (route.HttpHandlerOption != null)
                        {
                            var httpHandlerOption = route.HttpHandlerOption;
                            r.HttpHandlerOptions = new FileHttpHandlerOptions
                            {
                                AllowAutoRedirect       = httpHandlerOption.AllowAutoRedirect,
                                UseCookieContainer      = httpHandlerOption.UseCookieContainer,
                                UseProxy                = httpHandlerOption.UseProxy,
                                UseTracing              = httpHandlerOption.UseTracing,
                                MaxConnectionsPerServer = httpHandlerOption.MaxConnectionsPerServer
                            };
                        }
                        if (route.LoadBalancerOption != null)
                        {
                            var loadBalancerOptions = route.LoadBalancerOption;
                            r.LoadBalancerOptions = new FileLoadBalancerOptions
                            {
                                Expiry = loadBalancerOptions.Expiry,
                                Key    = loadBalancerOptions.Key,
                                Type   = loadBalancerOptions.Type
                            };
                        }
                        if (route.QoSOption != null)
                        {
                            var qoSOption = route.QoSOption;
                            r.QoSOptions = new FileQoSOptions
                            {
                                ExceptionsAllowedBeforeBreaking = qoSOption.ExceptionsAllowedBeforeBreaking,
                                DurationOfBreak = qoSOption.DurationOfBreak,
                                TimeoutValue    = qoSOption.TimeoutValue
                            };
                        }
                        if (route.RateLimitOption != null)
                        {
                            var rateLimitOption = route.RateLimitOption;
                            r.RateLimitOptions = new FileRateLimitRule
                            {
                                ClientWhitelist    = rateLimitOption.ClientWhitelist.Select(c => c.Whitelist).ToList(),
                                EnableRateLimiting = rateLimitOption.EnableRateLimiting,
                                Limit          = rateLimitOption.Limit,
                                Period         = rateLimitOption.Period,
                                PeriodTimespan = rateLimitOption.PeriodTimespan
                            };
                        }
                        if (route.SecurityOption != null)
                        {
                            var securityOption = route.SecurityOption;
                            r.SecurityOptions = new FileSecurityOptions
                            {
                                IPAllowedList = securityOption.IPAllowedList.Select(c => c.IP).ToList(),
                                IPBlockedList = securityOption.IPBlockedList.Select(c => c.IP).ToList()
                            };
                        }

                        if (route.UpstreamHttpMethods != null)
                        {
                            r.UpstreamHttpMethod = route.UpstreamHttpMethods.Select(c => c.Method).ToList();
                        }
                        r.UpstreamPathTemplate = route.UpstreamPathTemplate;

                        file.ReRoutes.Add(r);
                    }
                }
                else
                {
                    _logger.LogWarning($"Not Found ReRoute");
                }
            }
            else
            {
                throw new Exception(string.Format("Not found '{0}' gateway name config", _option.GatewayName));
            }
            if (file.ReRoutes == null || file.ReRoutes.Count == 0)
            {
                return(new OkResponse <FileConfiguration>(null));
            }
            _logger.LogDebug(JsonConvert.SerializeObject(file));

            return(new OkResponse <FileConfiguration>(file));
        }
 private void GivenIHaveAConfiguration(FileConfiguration config)
 {
     _fileConfiguration = config;
 }
Example #12
0
        public void should_get_file_configuration_edit_and_post_updated_version()
        {
            var initialConfiguration = new FileConfiguration
            {
                GlobalConfiguration = new FileGlobalConfiguration
                {
                },
                ReRoutes = new List <FileReRoute>()
                {
                    new FileReRoute()
                    {
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = 80,
                            }
                        },
                        DownstreamScheme       = "https",
                        DownstreamPathTemplate = "/",
                        UpstreamHttpMethod     = new List <string> {
                            "get"
                        },
                        UpstreamPathTemplate = "/"
                    },
                    new FileReRoute()
                    {
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = 80,
                            }
                        },
                        DownstreamScheme       = "https",
                        DownstreamPathTemplate = "/",
                        UpstreamHttpMethod     = new List <string> {
                            "get"
                        },
                        UpstreamPathTemplate = "/test"
                    }
                },
            };

            var updatedConfiguration = new FileConfiguration
            {
                GlobalConfiguration = new FileGlobalConfiguration
                {
                },
                ReRoutes = new List <FileReRoute>()
                {
                    new FileReRoute()
                    {
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = 80,
                            }
                        },
                        DownstreamScheme       = "http",
                        DownstreamPathTemplate = "/geoffrey",
                        UpstreamHttpMethod     = new List <string> {
                            "get"
                        },
                        UpstreamPathTemplate = "/"
                    },
                    new FileReRoute()
                    {
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "123.123.123",
                                Port = 443,
                            }
                        },
                        DownstreamScheme       = "https",
                        DownstreamPathTemplate = "/blooper/{productId}",
                        UpstreamHttpMethod     = new List <string> {
                            "post"
                        },
                        UpstreamPathTemplate = "/test"
                    }
                }
            };

            this.Given(x => GivenThereIsAConfiguration(initialConfiguration))
            .And(x => GivenOcelotIsRunning())
            .And(x => GivenIHaveAnOcelotToken("/administration"))
            .And(x => GivenIHaveAddedATokenToMyRequest())
            .When(x => WhenIGetUrlOnTheApiGateway("/administration/configuration"))
            .When(x => WhenIPostOnTheApiGateway("/administration/configuration", updatedConfiguration))
            .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
            .And(x => ThenTheResponseShouldBe(updatedConfiguration))
            .When(x => WhenIGetUrlOnTheApiGateway("/administration/configuration"))
            .And(x => ThenTheResponseShouldBe(updatedConfiguration))
            .And(_ => ThenTheConfigurationIsSavedCorrectly(updatedConfiguration))
            .BDDfy();
        }
Example #13
0
 private void GivenIHaveAConfiguration(FileConfiguration fileConfiguration)
 {
     _fileConfiguration = fileConfiguration;
 }
Example #14
0
 private void WhenISetTheConfiguration()
 {
     _repo.Set(_fileConfiguration);
     _result = _repo.Get().Result.Data;
 }
Example #15
0
        private async Task <ConfigurationValidationResult> CheckForUnsupportedAuthenticationProviders(FileConfiguration configuration)
        {
            var errors = new List <Error>();

            foreach (var reRoute in configuration.ReRoutes)
            {
                var isAuthenticated = !string.IsNullOrEmpty(reRoute.AuthenticationOptions.AuthenticationProviderKey);

                if (!isAuthenticated)
                {
                    continue;
                }

                var data = await _provider.GetAllSchemesAsync();

                var schemes = data.ToList();
                if (schemes.Any(x => x.Name == reRoute.AuthenticationOptions.AuthenticationProviderKey))
                {
                    continue;
                }

                var error = new UnsupportedAuthenticationProviderError($"{reRoute.AuthenticationOptions.AuthenticationProviderKey} is unsupported authentication provider, upstream template is {reRoute.UpstreamPathTemplate}, upstream method is {reRoute.UpstreamHttpMethod}");
                errors.Add(error);
            }

            return(errors.Count > 0
                ? new ConfigurationValidationResult(true, errors)
                : new ConfigurationValidationResult(false));
        }
Example #16
0
        private ConfigurationValidationResult CheckForReRoutesContainingDownstreamSchemeInDownstreamPathTemplate(FileConfiguration configuration)
        {
            var errors = new List <Error>();

            foreach (var reRoute in configuration.ReRoutes)
            {
                if (reRoute.DownstreamPathTemplate.Contains("https://") ||
                    reRoute.DownstreamPathTemplate.Contains("http://"))
                {
                    errors.Add(new DownstreamPathTemplateContainsSchemeError($"{reRoute.DownstreamPathTemplate} contains scheme"));
                }
            }

            if (errors.Any())
            {
                return(new ConfigurationValidationResult(true, errors));
            }

            return(new ConfigurationValidationResult(false, errors));
        }
Example #17
0
 /// <summary>
 /// Add a new log file
 /// </summary>
 /// <param name="fileName">Target file without path (Path is configured in <paramref name="configuration"/>).</param>
 /// <param name="configuration">Configuration used to control how entries should be written to the file</param>
 public void AddFile(string fileName, FileConfiguration configuration)
 {
     Targets.Add(new PaddedFileTarget(fileName, configuration));
 }
Example #18
0
        public void should_send_request_to_service_after_it_becomes_available_in_consul()
        {
            var consulPort                    = 8501;
            var serviceName                   = "product";
            var downstreamServiceOneUrl       = "http://localhost:50879";
            var downstreamServiceTwoUrl       = "http://localhost:50880";
            var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}";
            var serviceEntryOne               = new ServiceEntry()
            {
                Service = new AgentService()
                {
                    Service = serviceName,
                    Address = "localhost",
                    Port    = 50879,
                    ID      = Guid.NewGuid().ToString(),
                    Tags    = new string[0]
                },
            };
            var serviceEntryTwo = new ServiceEntry()
            {
                Service = new AgentService()
                {
                    Service = serviceName,
                    Address = "localhost",
                    Port    = 50880,
                    ID      = Guid.NewGuid().ToString(),
                    Tags    = new string[0]
                },
            };

            var configuration = new FileConfiguration
            {
                ReRoutes = new List <FileReRoute>
                {
                    new FileReRoute
                    {
                        DownstreamPathTemplate = "/",
                        DownstreamScheme       = "http",
                        UpstreamPathTemplate   = "/",
                        UpstreamHttpMethod     = new List <string> {
                            "Get"
                        },
                        ServiceName         = serviceName,
                        LoadBalancerOptions = new FileLoadBalancerOptions {
                            Type = "LeastConnection"
                        },
                    }
                },
                GlobalConfiguration = new FileGlobalConfiguration()
                {
                    ServiceDiscoveryProvider = new FileServiceDiscoveryProvider()
                    {
                        Host = "localhost",
                        Port = consulPort
                    }
                }
            };

            this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200))
            .And(x => x.GivenProductServiceTwoIsRunning(downstreamServiceTwoUrl, 200))
            .And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, serviceName))
            .And(x => x.GivenTheServicesAreRegisteredWithConsul(serviceEntryOne, serviceEntryTwo))
            .And(x => _steps.GivenThereIsAConfiguration(configuration))
            .And(x => _steps.GivenOcelotIsRunningWithConsul())
            .And(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimes("/", 10))
            .And(x => x.ThenTheTwoServicesShouldHaveBeenCalledTimes(10))
            .And(x => x.ThenBothServicesCalledRealisticAmountOfTimes(4, 6))
            .And(x => WhenIRemoveAService(serviceEntryTwo))
            .And(x => GivenIResetCounters())
            .And(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimes("/", 10))
            .And(x => ThenOnlyOneServiceHasBeenCalled())
            .And(x => WhenIAddAServiceBackIn(serviceEntryTwo))
            .And(x => GivenIResetCounters())
            .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimes("/", 10))
            .Then(x => x.ThenTheTwoServicesShouldHaveBeenCalledTimes(10))
            .And(x => x.ThenBothServicesCalledRealisticAmountOfTimes(4, 6))
            .BDDfy();
        }
Example #19
0
        public void should_use_consul_service_discovery_and_load_balance_request()
        {
            var consulPort                    = 8502;
            var serviceName                   = "product";
            var downstreamServiceOneUrl       = "http://localhost:50881";
            var downstreamServiceTwoUrl       = "http://localhost:50882";
            var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}";
            var serviceEntryOne               = new ServiceEntry()
            {
                Service = new AgentService()
                {
                    Service = serviceName,
                    Address = "localhost",
                    Port    = 50881,
                    ID      = Guid.NewGuid().ToString(),
                    Tags    = new string[0]
                },
            };
            var serviceEntryTwo = new ServiceEntry()
            {
                Service = new AgentService()
                {
                    Service = serviceName,
                    Address = "localhost",
                    Port    = 50882,
                    ID      = Guid.NewGuid().ToString(),
                    Tags    = new string[0]
                },
            };

            var configuration = new FileConfiguration
            {
                ReRoutes = new List <FileReRoute>
                {
                    new FileReRoute
                    {
                        DownstreamPathTemplate = "/",
                        DownstreamScheme       = "http",
                        UpstreamPathTemplate   = "/",
                        UpstreamHttpMethod     = new List <string> {
                            "Get"
                        },
                        ServiceName         = serviceName,
                        LoadBalancerOptions = new FileLoadBalancerOptions {
                            Type = "LeastConnection"
                        },
                    }
                },
                GlobalConfiguration = new FileGlobalConfiguration()
                {
                    ServiceDiscoveryProvider = new FileServiceDiscoveryProvider()
                    {
                        Host = "localhost",
                        Port = consulPort
                    }
                }
            };

            this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200))
            .And(x => x.GivenProductServiceTwoIsRunning(downstreamServiceTwoUrl, 200))
            .And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, serviceName))
            .And(x => x.GivenTheServicesAreRegisteredWithConsul(serviceEntryOne, serviceEntryTwo))
            .And(x => _steps.GivenThereIsAConfiguration(configuration))
            .And(x => _steps.GivenOcelotIsRunningWithConsul())
            .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimes("/", 50))
            .Then(x => x.ThenTheTwoServicesShouldHaveBeenCalledTimes(50))
            .And(x => x.ThenBothServicesCalledRealisticAmountOfTimes(24, 26))
            .BDDfy();
        }
Example #20
0
        public void should_forward_tracing_information_from_ocelot_and_downstream_services()
        {
            int port1         = RandomPortFinder.GetRandomPort();
            int port2         = RandomPortFinder.GetRandomPort();
            var configuration = new FileConfiguration
            {
                Routes = new List <FileRoute>
                {
                    new FileRoute
                    {
                        DownstreamPathTemplate = "/api/values",
                        DownstreamScheme       = "http",
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = port1,
                            }
                        },
                        UpstreamPathTemplate = "/api001/values",
                        UpstreamHttpMethod   = new List <string> {
                            "Get"
                        },
                        HttpHandlerOptions = new FileHttpHandlerOptions
                        {
                            UseTracing = true
                        }
                    },
                    new FileRoute
                    {
                        DownstreamPathTemplate = "/api/values",
                        DownstreamScheme       = "http",
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = port2,
                            }
                        },
                        UpstreamPathTemplate = "/api002/values",
                        UpstreamHttpMethod   = new List <string> {
                            "Get"
                        },
                        HttpHandlerOptions = new FileHttpHandlerOptions
                        {
                            UseTracing = true
                        }
                    }
                }
            };

            var butterflyPort = RandomPortFinder.GetRandomPort();
            var butterflyUrl  = $"http://localhost:{butterflyPort}";

            this.Given(x => GivenFakeButterfly(butterflyUrl))
            .And(x => GivenServiceOneIsRunning($"http://localhost:{port1}", "/api/values", 200, "Hello from Laura", butterflyUrl))
            .And(x => GivenServiceTwoIsRunning($"http://localhost:{port2}", "/api/values", 200, "Hello from Tom", butterflyUrl))
            .And(x => _steps.GivenThereIsAConfiguration(configuration))
            .And(x => _steps.GivenOcelotIsRunningUsingButterfly(butterflyUrl))
            .When(x => _steps.WhenIGetUrlOnTheApiGateway("/api001/values"))
            .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
            .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura"))
            .When(x => _steps.WhenIGetUrlOnTheApiGateway("/api002/values"))
            .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
            .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Tom"))
            .BDDfy();

            var commandOnAllStateMachines = Wait.WaitFor(10000).Until(() => _butterflyCalled >= 4);

            _output.WriteLine($"_butterflyCalled is {_butterflyCalled}");

            commandOnAllStateMachines.ShouldBeTrue();
        }
Example #21
0
 private void WhenIGetTheReRoutes()
 {
     _result = _repo.Get().Result.Data;
 }
Example #22
0
        public async Task should_persist_command_to_five_servers()
        {
            var peers = new List <FilePeer>
            {
                new FilePeer {
                    HostAndPort = "http://localhost:5000"
                },

                new FilePeer {
                    HostAndPort = "http://localhost:5001"
                },

                new FilePeer {
                    HostAndPort = "http://localhost:5002"
                },

                new FilePeer {
                    HostAndPort = "http://localhost:5003"
                },

                new FilePeer {
                    HostAndPort = "http://localhost:5004"
                }
            };

            var configuration = new FileConfiguration
            {
                GlobalConfiguration = new FileGlobalConfiguration
                {
                }
            };

            var updatedConfiguration = new FileConfiguration
            {
                GlobalConfiguration = new FileGlobalConfiguration
                {
                },
                ReRoutes = new List <FileReRoute>()
                {
                    new FileReRoute()
                    {
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "127.0.0.1",
                                Port = 80,
                            }
                        },
                        DownstreamScheme       = "http",
                        DownstreamPathTemplate = "/geoffrey",
                        UpstreamHttpMethod     = new List <string> {
                            "get"
                        },
                        UpstreamPathTemplate = "/"
                    },
                    new FileReRoute()
                    {
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "123.123.123",
                                Port = 443,
                            }
                        },
                        DownstreamScheme       = "https",
                        DownstreamPathTemplate = "/blooper/{productId}",
                        UpstreamHttpMethod     = new List <string> {
                            "post"
                        },
                        UpstreamPathTemplate = "/test"
                    }
                }
            };

            var command = new UpdateFileConfiguration(updatedConfiguration);

            GivenThePeersAre(peers);
            GivenThereIsAConfiguration(configuration);
            GivenFiveServersAreRunning();
            await GivenIHaveAnOcelotToken("/administration");
            await WhenISendACommandIntoTheCluster(command);

            Thread.Sleep(5000);
            await ThenTheCommandIsReplicatedToAllStateMachines(command);
        }
        public void should_return_response_200_and_foward_claim_as_query_string()
        {
            var user = new TestUser()
            {
                Username  = "******",
                Password  = "******",
                SubjectId = "registered|1231231",
                Claims    = new List <Claim>
                {
                    new Claim("CustomerId", "123"),
                    new Claim("LocationId", "1"),
                },
            };

            int port = RandomPortFinder.GetRandomPort();

            var configuration = new FileConfiguration
            {
                Routes = new List <FileRoute>
                {
                    new FileRoute
                    {
                        DownstreamPathTemplate = "/",
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = port,
                            },
                        },
                        DownstreamScheme     = "http",
                        UpstreamPathTemplate = "/",
                        UpstreamHttpMethod   = new List <string> {
                            "Get"
                        },
                        AuthenticationOptions = new FileAuthenticationOptions
                        {
                            AuthenticationProviderKey = "Test",
                            AllowedScopes             = new List <string>
                            {
                                "openid", "offline_access", "api",
                            },
                        },
                        AddQueriesToRequest =
                        {
                            { "CustomerId", "Claims[CustomerId] > value" },
                            { "LocationId", "Claims[LocationId] > value" },
                            { "UserType",   "Claims[sub] > value[0] > |" },
                            { "UserId",     "Claims[sub] > value[1] > |" },
                        },
                    },
                },
            };

            this.Given(x => x.GivenThereIsAnIdentityServerOn(_identityServerRootUrl, "api", AccessTokenType.Jwt, user))
            .And(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200))
            .And(x => _steps.GivenIHaveAToken(_identityServerRootUrl))
            .And(x => _steps.GivenThereIsAConfiguration(configuration))
            .And(x => _steps.GivenOcelotIsRunning(_options, "Test"))
            .And(x => _steps.GivenIHaveAddedATokenToMyRequest())
            .When(x => _steps.WhenIGetUrlOnTheApiGateway("/"))
            .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
            .And(x => _steps.ThenTheResponseBodyShouldBe("CustomerId: 123 LocationId: 1 UserType: registered UserId: 1231231"))
            .BDDfy();
        }
Example #24
0
        public void should_return_file_configuration()
        {
            var configuration = new FileConfiguration
            {
                GlobalConfiguration = new FileGlobalConfiguration
                {
                    RequestIdKey             = "RequestId",
                    ServiceDiscoveryProvider = new FileServiceDiscoveryProvider
                    {
                        Host = "127.0.0.1",
                    }
                },
                ReRoutes = new List <FileReRoute>()
                {
                    new FileReRoute()
                    {
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = 80,
                            }
                        },
                        DownstreamScheme       = "https",
                        DownstreamPathTemplate = "/",
                        UpstreamHttpMethod     = new List <string> {
                            "get"
                        },
                        UpstreamPathTemplate = "/",
                        FileCacheOptions     = new FileCacheOptions
                        {
                            TtlSeconds = 10,
                            Region     = "Geoff"
                        }
                    },
                    new FileReRoute()
                    {
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = 80,
                            }
                        },
                        DownstreamScheme       = "https",
                        DownstreamPathTemplate = "/",
                        UpstreamHttpMethod     = new List <string> {
                            "get"
                        },
                        UpstreamPathTemplate = "/test",
                        FileCacheOptions     = new FileCacheOptions
                        {
                            TtlSeconds = 10,
                            Region     = "Dave"
                        }
                    }
                }
            };

            this.Given(x => GivenThereIsAConfiguration(configuration))
            .And(x => GivenOcelotIsRunning())
            .And(x => GivenIHaveAnOcelotToken("/administration"))
            .And(x => GivenIHaveAddedATokenToMyRequest())
            .When(x => WhenIGetUrlOnTheApiGateway("/administration/configuration"))
            .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
            .And(x => ThenTheResponseShouldBe(configuration))
            .BDDfy();
        }
Example #25
0
 private void GivenThe(FileConfiguration fileConfig)
 {
     _fileConfig = fileConfig;
 }
Example #26
0
        public void should_get_file_configuration_edit_and_post_updated_version_redirecting_reroute()
        {
            var fooPort = 47689;
            var barPort = 47690;

            var initialConfiguration = new FileConfiguration
            {
                ReRoutes = new List <FileReRoute>()
                {
                    new FileReRoute()
                    {
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = fooPort,
                            }
                        },
                        DownstreamScheme       = "http",
                        DownstreamPathTemplate = "/foo",
                        UpstreamHttpMethod     = new List <string> {
                            "get"
                        },
                        UpstreamPathTemplate = "/foo"
                    }
                }
            };

            var updatedConfiguration = new FileConfiguration
            {
                GlobalConfiguration = new FileGlobalConfiguration
                {
                },
                ReRoutes = new List <FileReRoute>()
                {
                    new FileReRoute()
                    {
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = barPort,
                            }
                        },
                        DownstreamScheme       = "http",
                        DownstreamPathTemplate = "/bar",
                        UpstreamHttpMethod     = new List <string> {
                            "get"
                        },
                        UpstreamPathTemplate = "/foo"
                    }
                }
            };

            this.Given(x => GivenThereIsAConfiguration(initialConfiguration))
            .And(x => GivenThereIsAFooServiceRunningOn($"http://localhost:{fooPort}"))
            .And(x => GivenThereIsABarServiceRunningOn($"http://localhost:{barPort}"))
            .And(x => GivenOcelotIsRunning())
            .And(x => WhenIGetUrlOnTheApiGateway("/foo"))
            .Then(x => ThenTheResponseBodyShouldBe("foo"))
            .And(x => GivenIHaveAnOcelotToken("/administration"))
            .And(x => GivenIHaveAddedATokenToMyRequest())
            .When(x => WhenIPostOnTheApiGateway("/administration/configuration", updatedConfiguration))
            .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
            .And(x => ThenTheResponseShouldBe(updatedConfiguration))
            .And(x => WhenIGetUrlOnTheApiGateway("/foo"))
            .Then(x => ThenTheResponseBodyShouldBe("bar"))
            .When(x => WhenIPostOnTheApiGateway("/administration/configuration", initialConfiguration))
            .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
            .And(x => ThenTheResponseShouldBe(initialConfiguration))
            .And(x => WhenIGetUrlOnTheApiGateway("/foo"))
            .Then(x => ThenTheResponseBodyShouldBe("foo"))
            .BDDfy();
        }
Example #27
0
 public Task <Response> Set(FileConfiguration fileConfiguration)
 {
     throw new NotImplementedException();
 }
Example #28
0
 public Task <Response> Set(FileConfiguration fileConfiguration)
 {
     _cache.AddAndDelete(_option.CachePrefix + "FileConfiguration", fileConfiguration, TimeSpan.FromSeconds(1800), "");
     return(Task.FromResult((Response) new OkResponse()));
 }
        private ICollection<CodeTypeMember> GenerateConstructor(IClassConfiguration classConfiguration, CodeNamespace classSpace, CodeTypeDeclaration testBaseClass, ICollection<IFileConfiguration> files)
        {
            var memberList = new List<CodeTypeMember>();

            var constructor = new CodeConstructor
            {
                Attributes = MemberAttributes.Public,
            };

            memberList.Add(constructor);

            if (classConfiguration.ClassType == ClassTypes.Data)
            {
                foreach (var propertyConfiguration in classConfiguration.Properties)
                {
                    var field = new CodeMemberField
                    {
                        Attributes = MemberAttributes.Private,
                        Name = "_" + propertyConfiguration.Name.ToPrivate(),
                        Type = new CodeTypeReference(propertyConfiguration.Type)
                    };

                    var expression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name);

                    var returnStatement = new CodeMethodReturnStatement { Expression = expression };

                    var property = new CodeMemberProperty
                    {
                        Attributes = MemberAttributes.Public | MemberAttributes.Final,
                        Name = propertyConfiguration.Name,
                        Type = field.Type,
                        HasGet = true,
                        GetStatements = { returnStatement }
                    };

                    var parameter = new CodeParameterDeclarationExpression(field.Type, property.Name.ToPrivate());

                    constructor.Parameters.Add(parameter);

                    var referenceExpression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name);

                    var constructorBody = new CodeAssignStatement(referenceExpression,
                                                                  new CodeArgumentReferenceExpression(parameter.Name));

                    constructor.Statements.Add(constructorBody);

                    memberList.Add(field);
                    memberList.Add(property);
                }

                return memberList;
            }

            if (classConfiguration.ClassType != ClassTypes.Dependent && classConfiguration.Methods.All(m => m.ReturnType.Type != ReturnTypes.Normal.Type))
                return memberList;

            var dependencyInterface = new CodeTypeDeclaration("I" + classConfiguration.Name + "Dependencies")
            {
                IsInterface = true
            };

            var dependencyConstructor = new CodeConstructor
            {
                Attributes = MemberAttributes.Public
            };

            var dependencyClass = new CodeTypeDeclaration(classConfiguration.Name + "Dependencies")
            {
                IsClass = true,
                BaseTypes = { dependencyInterface.Name },
                Members = { dependencyConstructor }
            };

            var dependencySpace = new CodeNamespace("Types")
            {
                Types = { dependencyInterface, dependencyClass }
            };

            var initializeMethod = (CodeMemberMethod)testBaseClass.Members[0];

            var dependencyMock = new CodeMemberField("Mock<" + dependencyInterface.Name + ">", "DependenciesMock")
            {
                Attributes = MemberAttributes.Family
            };

            testBaseClass.Members.Add(dependencyMock);

            var testReferenceExpression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), dependencyMock.Name);

            var initializeBody = new CodeAssignStatement(testReferenceExpression, new CodeObjectCreateExpression(dependencyMock.Name));

            initializeMethod.Statements.Add(initializeBody);

            classSpace.Imports.Add(new CodeNamespaceImport(dependencySpace.Name));

            var dependencyFile = new FileConfiguration(dependencyClass.Name, dependencySpace);

            files.Add(dependencyFile);

            var constructorParameter = new CodeParameterDeclarationExpression("IDependencies",
                                                                   "dependencies");

            constructor.Parameters.Add(constructorParameter);

            foreach (var methodConfiguration in classConfiguration.Methods.Where(m => m.ReturnType.Type == ReturnTypes.Normal.Type))
            {
                var resultClassName = classConfiguration.Name + GetReturnName(classConfiguration, methodConfiguration);

                var resultInterface = new CodeTypeDeclaration("I" + resultClassName)
                {
                    IsInterface = true
                };

                var resultClass = new CodeTypeDeclaration(resultClassName)
                {
                    IsClass = true,
                    BaseTypes = { resultInterface.Name }
                };

                var resultSpace = new CodeNamespace("Types")
                {
                    Types = { resultInterface, resultClass }
                };

                var resultFile = new FileConfiguration(resultClassName, resultSpace);

                files.Add(resultFile);

                var resultFactoryName = GetReturnFactoryName(classConfiguration, methodConfiguration);

                var resultFactoryCreateExpression = new CodeObjectCreateExpression(resultClassName);

                var resultFactoryReturnStatement = new CodeMethodReturnStatement { Expression = resultFactoryCreateExpression };

                var factoryMethod = new CodeMemberMethod
                {
                    Attributes = MemberAttributes.Public | MemberAttributes.Final,
                    Name = "Produce",
                    ReturnType = new CodeTypeReference("I" + resultClassName),
                    Statements = { resultFactoryReturnStatement }
                };

                var resultFactoryInterface = new CodeTypeDeclaration("I" + classConfiguration.Name + resultFactoryName)
                {
                    IsInterface = true,
                    Members = { factoryMethod }
                };

                var resultFactoryClass = new CodeTypeDeclaration(classConfiguration.Name + resultFactoryName)
                {
                    IsClass = true,
                    BaseTypes = { resultFactoryInterface.Name },
                    Members = { factoryMethod }
                };

                var dependencyPrivateField = new CodeMemberField(resultFactoryInterface.Name, "_" + resultFactoryName.ToPrivate())
                {
                    Attributes = MemberAttributes.Private
                };

                var expression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), dependencyPrivateField.Name);

                var returnStatement = new CodeMethodReturnStatement { Expression = expression };

                var dependencyProperty = new CodeMemberProperty
                {
                    Name = resultFactoryName,
                    Attributes = MemberAttributes.Public | MemberAttributes.Final,
                    Type = new CodeTypeReference(resultFactoryInterface.Name),
                    HasGet = true,
                    GetStatements = { returnStatement }
                };

                var classDependencyField = new CodeMemberField("I" + resultFactoryName, "_" + resultFactoryName.ToPrivate())
                {
                    Attributes = MemberAttributes.Private
                };

                var referenceExpression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), classDependencyField.Name);

                var constructorBody = new CodeAssignStatement(referenceExpression,
                                                              new CodeArgumentReferenceExpression(constructorParameter.Name + "." + resultFactoryName));

                constructor.Statements.Add(constructorBody);

                memberList.Add(classDependencyField);

                dependencyInterface.Members.Add(dependencyProperty);
                dependencyClass.Members.Add(dependencyProperty);
                dependencyClass.Members.Add(dependencyPrivateField);

                var dependencyConstructorParameter = new CodeParameterDeclarationExpression(resultFactoryInterface.Name, resultFactoryName.ToPrivate());

                dependencyConstructor.Parameters.Add(dependencyConstructorParameter);

                var dependencyReferenceExpression = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), dependencyPrivateField.Name);

                dependencyConstructor.Statements.Add(new CodeAssignStatement(dependencyReferenceExpression,
                                                                             new CodeArgumentReferenceExpression(
                                                                                 dependencyConstructorParameter.Name)));

                var resultFactorySpace = new CodeNamespace("Logics")
                {
                    Types = { resultFactoryInterface, resultFactoryClass }
                };

                var resultFactoryFile = new FileConfiguration(classConfiguration.Name + resultFactoryName, resultFactorySpace);

                files.Add(resultFactoryFile);
            }

            return memberList;
        }
Example #30
0
        public void should_forward_tracing_information_from_ocelot_and_downstream_services()
        {
            var configuration = new FileConfiguration
            {
                ReRoutes = new List <FileReRoute>
                {
                    new FileReRoute
                    {
                        DownstreamPathTemplate = "/api/values",
                        DownstreamScheme       = "http",
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = 51887,
                            }
                        },
                        UpstreamPathTemplate = "/api001/values",
                        UpstreamHttpMethod   = new List <string> {
                            "Get"
                        },
                        HttpHandlerOptions = new FileHttpHandlerOptions
                        {
                            UseTracing = true
                        },
                        QoSOptions = new FileQoSOptions
                        {
                            ExceptionsAllowedBeforeBreaking = 3,
                            DurationOfBreak = 10,
                            TimeoutValue    = 5000
                        }
                    },
                    new FileReRoute
                    {
                        DownstreamPathTemplate = "/api/values",
                        DownstreamScheme       = "http",
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = 51388,
                            }
                        },
                        UpstreamPathTemplate = "/api002/values",
                        UpstreamHttpMethod   = new List <string> {
                            "Get"
                        },
                        HttpHandlerOptions = new FileHttpHandlerOptions
                        {
                            UseTracing = true
                        },
                        QoSOptions = new FileQoSOptions
                        {
                            ExceptionsAllowedBeforeBreaking = 3,
                            DurationOfBreak = 10,
                            TimeoutValue    = 5000
                        }
                    }
                }
            };

            var butterflyUrl = "http://localhost:9618";

            this.Given(x => GivenServiceOneIsRunning("http://localhost:51887", "/api/values", 200, "Hello from Laura", butterflyUrl))
            .And(x => GivenServiceTwoIsRunning("http://localhost:51388", "/api/values", 200, "Hello from Tom", butterflyUrl))
            .And(x => GivenFakeButterfly(butterflyUrl))
            .And(x => _steps.GivenThereIsAConfiguration(configuration))
            .And(x => _steps.GivenOcelotIsRunningUsingButterfly(butterflyUrl))
            .When(x => _steps.WhenIGetUrlOnTheApiGateway("/api001/values"))
            .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
            .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura"))
            .When(x => _steps.WhenIGetUrlOnTheApiGateway("/api002/values"))
            .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
            .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Tom"))
            .BDDfy();

            var commandOnAllStateMachines = WaitFor(5000).Until(() => _butterflyCalled == 4);

            commandOnAllStateMachines.ShouldBeTrue();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="PaddedFileTarget"/> class.
 /// </summary>
 /// <param name="name">File name without extension</param>
 /// <param name="configuration">The configuration.</param>
 public PaddedFileTarget(string name, FileConfiguration configuration) : base(name, configuration)
 {
 }
 internal LocalSettings(IWpfTextView view, FileConfiguration settings)
 {
     _view = view;
     _settings = settings;
 }
Example #33
0
        private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificConfig)
        {
            if (!string.IsNullOrEmpty(folder))
            {
                Directory.CreateDirectory(folder);
            }

            _globalConfig = new FileConfiguration
            {
                GlobalConfiguration = new FileGlobalConfiguration
                {
                    BaseUrl          = "BaseUrl",
                    RateLimitOptions = new FileRateLimitOptions
                    {
                        HttpStatusCode          = 500,
                        ClientIdHeader          = "ClientIdHeader",
                        DisableRateLimitHeaders = true,
                        QuotaExceededMessage    = "QuotaExceededMessage",
                        RateLimitCounterPrefix  = "RateLimitCounterPrefix"
                    },
                    ServiceDiscoveryProvider = new FileServiceDiscoveryProvider
                    {
                        Scheme = "https",
                        Host   = "Host",
                        Port   = 80,
                        Type   = "Type"
                    },
                    RequestIdKey = "RequestIdKey"
                }
            };

            _routeA = new FileConfiguration
            {
                Routes = new List <FileRoute>
                {
                    new FileRoute
                    {
                        DownstreamScheme       = "DownstreamScheme",
                        DownstreamPathTemplate = "DownstreamPathTemplate",
                        Key                = "Key",
                        UpstreamHost       = "UpstreamHost",
                        UpstreamHttpMethod = new List <string>
                        {
                            "UpstreamHttpMethod"
                        },
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "Host",
                                Port = 80
                            }
                        }
                    }
                }
            };

            _routeB = new FileConfiguration
            {
                Routes = new List <FileRoute>
                {
                    new FileRoute
                    {
                        DownstreamScheme       = "DownstreamSchemeB",
                        DownstreamPathTemplate = "DownstreamPathTemplateB",
                        Key                = "KeyB",
                        UpstreamHost       = "UpstreamHostB",
                        UpstreamHttpMethod = new List <string>
                        {
                            "UpstreamHttpMethodB"
                        },
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "HostB",
                                Port = 80
                            }
                        }
                    },
                    new FileRoute
                    {
                        DownstreamScheme       = "DownstreamSchemeBB",
                        DownstreamPathTemplate = "DownstreamPathTemplateBB",
                        Key                = "KeyBB",
                        UpstreamHost       = "UpstreamHostBB",
                        UpstreamHttpMethod = new List <string>
                        {
                            "UpstreamHttpMethodBB"
                        },
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "HostBB",
                                Port = 80
                            }
                        }
                    }
                }
            };

            _aggregate = new FileConfiguration
            {
                Aggregates = new List <FileAggregateRoute>
                {
                    new FileAggregateRoute
                    {
                        RouteKeys = new List <string>
                        {
                            "KeyB",
                            "KeyBB"
                        },
                        UpstreamPathTemplate = "UpstreamPathTemplate",
                    },
                    new FileAggregateRoute
                    {
                        RouteKeys = new List <string>
                        {
                            "KeyB",
                            "KeyBB"
                        },
                        UpstreamPathTemplate = "UpstreamPathTemplate",
                    }
                }
            };

            _envSpecific = new FileConfiguration
            {
                Routes = new List <FileRoute>
                {
                    new FileRoute
                    {
                        DownstreamScheme       = "DownstreamSchemeSpec",
                        DownstreamPathTemplate = "DownstreamPathTemplateSpec",
                        Key                = "KeySpec",
                        UpstreamHost       = "UpstreamHostSpec",
                        UpstreamHttpMethod = new List <string>
                        {
                            "UpstreamHttpMethodSpec"
                        },
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "HostSpec",
                                Port = 80
                            }
                        }
                    }
                }
            };

            string globalFilename     = Path.Combine(folder, "ocelot.global.json");
            string routesAFilename    = Path.Combine(folder, "ocelot.routesA.json");
            string routesBFilename    = Path.Combine(folder, "ocelot.routesB.json");
            string aggregatesFilename = Path.Combine(folder, "ocelot.aggregates.json");

            File.WriteAllText(globalFilename, JsonConvert.SerializeObject(_globalConfig));
            File.WriteAllText(routesAFilename, JsonConvert.SerializeObject(_routeA));
            File.WriteAllText(routesBFilename, JsonConvert.SerializeObject(_routeB));
            File.WriteAllText(aggregatesFilename, JsonConvert.SerializeObject(_aggregate));

            if (addEnvSpecificConfig)
            {
                string envSpecificFilename = Path.Combine(folder, "ocelot.Env.json");
                File.WriteAllText(envSpecificFilename, JsonConvert.SerializeObject(_envSpecific));
            }
        }
Example #34
0
 public FileService(AppConfiguration appConfig)
 {
     _config = appConfig.File;
 }
Example #35
0
        public async Task should_persist_command_to_five_servers_when_using_administration_api()
        {
            var peers = new List <FilePeer>
            {
                new FilePeer {
                    HostAndPort = "http://localhost:5005"
                },

                new FilePeer {
                    HostAndPort = "http://localhost:5006"
                },

                new FilePeer {
                    HostAndPort = "http://localhost:5007"
                },

                new FilePeer {
                    HostAndPort = "http://localhost:5008"
                },

                new FilePeer {
                    HostAndPort = "http://localhost:5009"
                }
            };

            var configuration = new FileConfiguration
            {
            };

            var updatedConfiguration = new FileConfiguration
            {
                ReRoutes = new List <FileReRoute>()
                {
                    new FileReRoute()
                    {
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "127.0.0.1",
                                Port = 80,
                            }
                        },
                        DownstreamScheme       = "http",
                        DownstreamPathTemplate = "/geoffrey",
                        UpstreamHttpMethod     = new List <string> {
                            "get"
                        },
                        UpstreamPathTemplate = "/"
                    },
                    new FileReRoute()
                    {
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "123.123.123",
                                Port = 443,
                            }
                        },
                        DownstreamScheme       = "https",
                        DownstreamPathTemplate = "/blooper/{productId}",
                        UpstreamHttpMethod     = new List <string> {
                            "post"
                        },
                        UpstreamPathTemplate = "/test"
                    }
                }
            };

            var command = new UpdateFileConfiguration(updatedConfiguration);

            GivenThePeersAre(peers);
            GivenThereIsAConfiguration(configuration);
            GivenFiveServersAreRunning();
            await GivenIHaveAnOcelotToken("/administration");

            GivenIHaveAddedATokenToMyRequest();
            await WhenIPostOnTheApiGateway("/administration/configuration", updatedConfiguration);
            await ThenTheCommandIsReplicatedToAllStateMachines(command);
        }
Example #36
0
        public async Task <Response <IOcelotConfiguration> > Create(FileConfiguration fileConfiguration)
        {
            var config = await SetUpConfiguration(fileConfiguration);

            return(new OkResponse <IOcelotConfiguration>(config));
        }
Example #37
0
 private void GivenTheFollowingConfiguration(FileConfiguration fileConfiguration)
 {
     _fileConfiguration = fileConfiguration;
 }
        private CodeParameterDeclarationExpression GenerateMethodArgument(IClassConfiguration classConfiguration, IMethodConfiguration methodConfiguration, ICollection<IFileConfiguration> files)
        {
            var className = classConfiguration.Name + methodConfiguration.Name + "Arguments";

            var argumentinterface = new CodeTypeDeclaration("I" + className) { IsInterface = true };

            var argumentsClass = new CodeTypeDeclaration(className)
            {
                IsClass = true,
                BaseTypes = { argumentinterface.Name }
            };

            var argumentSpace = new CodeNamespace("Types")
            {
                Types = { argumentinterface, argumentsClass }
            };

            var argumentFile = new FileConfiguration(className, argumentSpace);

            files.Add(argumentFile);

            var argumentFactoryName = className + "Factory";

            var expression = new CodeObjectCreateExpression(className);

            var returnStatement = new CodeMethodReturnStatement { Expression = expression };

            var factoryMethod = new CodeMemberMethod()
            {
                Name = "Produce",
                Attributes = MemberAttributes.Public | MemberAttributes.Final,
                ReturnType = new CodeTypeReference(argumentinterface.Name),
                Statements = { returnStatement }
            };

            var argumentFactoryInterface = new CodeTypeDeclaration("I" + argumentFactoryName)
            {
                IsInterface = true,
                Members = { factoryMethod }
            };

            var argumentFactoryClass = new CodeTypeDeclaration(argumentFactoryName)
            {
                IsClass = true,
                BaseTypes = { argumentFactoryInterface.Name },
                Members = { factoryMethod }
            };

            var argumentFactorySpace = new CodeNamespace("Logics")
            {
                Types = { argumentFactoryInterface, argumentFactoryClass }
            };

            var argumentFactoryFile = new FileConfiguration(argumentFactoryClass.Name, argumentFactorySpace);

            files.Add(argumentFactoryFile);

            return new CodeParameterDeclarationExpression("I" + methodConfiguration.Name + "Arguments", "argument");
        }
Example #39
0
        public void should_wait_for_period_timespan_to_elapse_before_making_next_request()
        {
            var configuration = new FileConfiguration
            {
                ReRoutes = new List <FileReRoute>
                {
                    new FileReRoute
                    {
                        DownstreamPathTemplate = "/api/ClientRateLimit",
                        DownstreamHostAndPorts = new List <FileHostAndPort>
                        {
                            new FileHostAndPort
                            {
                                Host = "localhost",
                                Port = 51926,
                            }
                        },
                        DownstreamScheme     = "http",
                        UpstreamPathTemplate = "/api/ClientRateLimit",
                        UpstreamHttpMethod   = new List <string> {
                            "Get"
                        },
                        RequestIdKey = _steps.RequestIdKey,

                        RateLimitOptions = new FileRateLimitRule()
                        {
                            EnableRateLimiting = true,
                            ClientWhitelist    = new List <string>(),
                            Limit          = 3,
                            Period         = "1s",
                            PeriodTimespan = 2
                        }
                    }
                },
                GlobalConfiguration = new FileGlobalConfiguration()
                {
                    RateLimitOptions = new FileRateLimitOptions()
                    {
                        ClientIdHeader          = "ClientId",
                        DisableRateLimitHeaders = false,
                        QuotaExceededMessage    = "",
                        RateLimitCounterPrefix  = "",
                        HttpStatusCode          = 428
                    },
                    RequestIdKey = "oceclientrequest"
                }
            };

            this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51926", "/api/ClientRateLimit"))
            .And(x => _steps.GivenThereIsAConfiguration(configuration))
            .And(x => _steps.GivenOcelotIsRunning())
            .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 1))
            .Then(x => _steps.ThenTheStatusCodeShouldBe(200))
            .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 2))
            .Then(x => _steps.ThenTheStatusCodeShouldBe(200))
            .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 1))
            .Then(x => _steps.ThenTheStatusCodeShouldBe(428))
            .And(x => _steps.GivenIWait(1000))
            .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 1))
            .Then(x => _steps.ThenTheStatusCodeShouldBe(428))
            .And(x => _steps.GivenIWait(1000))
            .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 1))
            .Then(x => _steps.ThenTheStatusCodeShouldBe(200))
            .BDDfy();
        }
        private async Task <HttpResponseResult <FileConfiguration> > AddOrUpdateConfiguration(FileConfiguration data, string accessToken)
        {
            var result = await _httpUtilityService.PostAsync <FileConfiguration>("/administration/configuration", data, accessToken);

            return(result);
        }
Example #41
0
 public Task <Response> Set(FileConfiguration fileConfiguration)
 {
     SetExtended(new FileConfigurationExtended(fileConfiguration));
     return(Task.FromResult <Response>(new OkResponse()));
 }