コード例 #1
0
ファイル: Program.cs プロジェクト: wflk/canape
        protected override void ExecuteInternal()
        {
            PythonContext ctx = HostingHelpers.GetLanguageContext(Engine) as PythonContext;

            (HostingHelpers.GetLanguageContext(base.Engine) as PythonContext).SetModuleState(typeof(ScriptEngine), base.Engine);

            ctx.SetModuleState(typeof(ScriptEngine), Engine);
            Runtime.LoadAssembly(typeof(NetGraph).Assembly);
            Runtime.LoadAssembly(typeof(NetGraphDocument).Assembly);
            Runtime.LoadAssembly(typeof(ProxyNetworkService).Assembly);
            Runtime.LoadAssembly(typeof(ExpressionResolver).Assembly);
            Runtime.LoadAssembly(typeof(Program).Assembly);
            Runtime.LoadAssembly(typeof(BaseDataEndpoint).Assembly);
            Runtime.LoadAssembly(typeof(CertificateUtils).Assembly);
            Runtime.LoadAssembly(typeof(Org.BouncyCastle.Asn1.Asn1Encodable).Assembly);
            Runtime.LoadAssembly(typeof(NodeLibraryAttribute).Assembly);
            ICollection <string> searchPaths = Engine.GetSearchPaths();
            string item = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PythonLib");

            searchPaths.Add(item);
            Engine.SetSearchPaths(searchPaths);
            base.ExecuteInternal();
        }
コード例 #2
0
    private PythonAst ParseSnippet(string snippet)
    {
        var sourceUnit =
            HostingHelpers.GetSourceUnit(
                _engine.CreateScriptSourceFromString(snippet, SourceCodeKind.SingleStatement));
        var compilerContext = new CompilerContext(sourceUnit, _compilerOptions, ErrorSink.Default);
        var options         = new PythonOptions();

        var parser = Parser.CreateParser(compilerContext, options);

        PythonAst ast;

        try
        {
            ast = parser.ParseSingleStatement();
        }
        catch (SyntaxErrorException e)
        {
            throw new ArgumentException($"Failed to parse snippet '{snippet}'.", e);
        }

        return(ast);
    }
コード例 #3
0
    internal PythonScript ParseScript(string filename, string content)
    {
        var sourceUnit =
            HostingHelpers.GetSourceUnit(
                _engine.CreateScriptSourceFromString(content, filename, SourceCodeKind.File));
        var compilerContext = new CompilerContext(sourceUnit, _compilerOptions, ErrorSink.Default);
        var options         = new PythonOptions();

        var parser = Parser.CreateParser(compilerContext, options);

        PythonAst ast;

        try
        {
            ast = parser.ParseFile(false);
        }
        catch (SyntaxErrorException e)
        {
            throw new ArgumentException($"Failed to parse file '{filename}' at line {e.Line}.", e);
        }

        return(new PythonScript(filename, content, ast));
    }
コード例 #4
0
        public void Load_ConfigServerReturnsNotFoundStatus_FailFastEnabled()
        {
            // Arrange
            var envir = HostingHelpers.GetHostingEnvironment();

            TestConfigServerStartup.Reset();
            TestConfigServerStartup.ReturnStatus = new int[] { 404 };
            var builder = new WebHostBuilder().UseStartup <TestConfigServerStartup>().UseEnvironment(envir.EnvironmentName);
            var server  = new TestServer(builder);

            ConfigServerClientSettings settings = new ConfigServerClientSettings
            {
                Uri      = "http://localhost:8888",
                Name     = "myName",
                FailFast = true
            };

            server.BaseAddress = new Uri(settings.Uri);
            ConfigServerConfigurationProvider provider = new ConfigServerConfigurationProvider(settings, server.CreateClient());

            // Act and Assert
            var ex = Assert.Throws <ConfigServerException>(() => provider.LoadInternal());
        }
コード例 #5
0
        public async System.Threading.Tasks.Task SendHeartBeatAsync_InvokesServer_ReturnsStatusCodeAndHeaders()
        {
            var envir = HostingHelpers.GetHostingEnvironment();

            TestConfigServerStartup.Response     = string.Empty;
            TestConfigServerStartup.ReturnStatus = 200;
            var builder = new WebHostBuilder().UseStartup <TestConfigServerStartup>().UseEnvironment(envir.EnvironmentName);
            var server  = new TestServer(builder);

            var uri = "http://localhost:8888/";

            server.BaseAddress = new Uri(uri);
            var config = new EurekaInstanceConfig()
            {
                AppName    = "foo",
                InstanceId = "id1"
            };
            var info = InstanceInfo.FromInstanceConfig(config);

            var cconfig = new EurekaClientConfig()
            {
                EurekaServerServiceUrls = uri
            };
            var client = new EurekaHttpClient(cconfig, server.CreateClient());
            var resp   = await client.SendHeartBeatAsync("foo", "id1", info, InstanceStatus.UNKNOWN);

            Assert.NotNull(resp);
            Assert.Equal(HttpStatusCode.OK, resp.StatusCode);
            Assert.NotNull(resp.Headers);

            Assert.Equal("PUT", TestConfigServerStartup.LastRequest.Method);
            Assert.Equal("localhost:8888", TestConfigServerStartup.LastRequest.Host.Value);
            Assert.Equal("/apps/FOO/id1", TestConfigServerStartup.LastRequest.Path.Value);
            var time = DateTimeConversions.ToJavaMillis(new DateTime(info.LastDirtyTimestamp, DateTimeKind.Utc));

            Assert.Equal("?status=STARTING&lastDirtyTimestamp=" + time, TestConfigServerStartup.LastRequest.QueryString.Value);
        }
コード例 #6
0
        public void GetPropertySources_ReturnsExpected()
        {
            var opts        = new EnvEndpointOptions();
            var appsettings = new Dictionary <string, string>()
            {
                ["management:endpoints:enabled"]          = "false",
                ["management:endpoints:path"]             = "/cloudfoundryapplication",
                ["management:endpoints:loggers:enabled"]  = "false",
                ["management:endpoints:heapdump:enabled"] = "true",
                ["management:endpoints:cloudfoundry:validatecertificates"] = "true",
                ["management:endpoints:cloudfoundry:enabled"] = "true"
            };
            var configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddInMemoryCollection(appsettings);
            var config = configurationBuilder.Build();
            var env    = HostingHelpers.GetHostingEnvironment();
            var ep     = new EnvEndpoint(opts, config, env);
            var result = ep.GetPropertySources(config);

            Assert.NotNull(result);
            Assert.Single(result);

            var desc = result[0];

            Assert.Equal("MemoryConfigurationProvider", desc.Name);
            var props = desc.Properties;

            Assert.NotNull(props);
            Assert.Equal(6, props.Count);
            Assert.Contains("management:endpoints:cloudfoundry:validatecertificates", props.Keys);
            var prop = props["management:endpoints:cloudfoundry:validatecertificates"];

            Assert.NotNull(prop);
            Assert.Equal("true", prop.Value);
            Assert.Null(prop.Origin);
        }
コード例 #7
0
ファイル: Python.cs プロジェクト: enigmaeth/CodeTalk
        public CodeFile Parse(string programText, string fileName)
        {
            ScriptEngine    py  = null;
            SourceUnit      src = null;
            LanguageContext pythonLanguageContext = null;
            CompilerContext cc = null;

            IronPython.PythonOptions   pyOptions;
            IronPython.Compiler.Parser pyParser = null;
            PythonAst ast = null;

            try
            {
                py  = IronPython.Hosting.Python.CreateEngine();
                src = HostingHelpers.GetSourceUnit(py.CreateScriptSourceFromString(programText));
                pythonLanguageContext = HostingHelpers.GetLanguageContext(py);
                cc        = new CompilerContext(src, pythonLanguageContext.GetCompilerOptions(), ErrorSink.Default);
                pyOptions = pythonLanguageContext.Options as IronPython.PythonOptions;
                pyParser  = Parser.CreateParser(cc, pyOptions);
                ast       = pyParser.ParseFile(true);
            }
            finally
            {
                pyParser?.Dispose();
            }

            PythonEntityCollector collector = new PythonEntityCollector();

            ast.Walk(collector);


            var cf = collector.getCodeFile();

            cf.Name = String.IsNullOrWhiteSpace(fileName) ? $"{rm.GetString("PythonString", CultureInfo.CurrentCulture)}" : fileName;

            return(cf);
        }
コード例 #8
0
        public async System.Threading.Tasks.Task RenewAsync_ReturnsTrue_WhenOKStatusReturned()
        {
            var envir = HostingHelpers.GetHostingEnvironment();

            TestConfigServerStartup.Response     = string.Empty;
            TestConfigServerStartup.ReturnStatus = 200;
            var builder = new WebHostBuilder().UseStartup <TestConfigServerStartup>().UseEnvironment(envir.EnvironmentName);
            var server  = new TestServer(builder);

            var uri = "http://localhost:8888/";

            server.BaseAddress = new Uri(uri);
            var config = new EurekaClientConfig()
            {
                ShouldFetchRegistry      = false,
                ShouldRegisterWithEureka = false,
                EurekaServerServiceUrls  = uri.ToString()
            };

            var inst = new InstanceInfo()
            {
                InstanceId = "localhost:foo",
                HostName   = "localhost",
                AppName    = "FOO",
                IpAddr     = "192.168.56.1",
                Status     = InstanceStatus.STARTING
            };

            ApplicationInfoManager.Instance.InstanceInfo = inst;

            var httpClient = new EurekaHttpClient(config, server.CreateClient());
            var client     = new DiscoveryClient(config, httpClient);
            var result     = await client.RenewAsync();

            Assert.True(result);
        }
コード例 #9
0
        public void AddConfigServer_Validate_Certificates_DisablesCertValidation()
        {
            // Arrange
            var    appsettings = @"
                {
                    ""spring"": {
                      ""cloud"": {
                        ""config"": {
                            ""validate_certificates"": false,
                            ""timeout"": 0
                        }
                      }
                    }
                }";
            var    path        = TestHelpers.CreateTempFile(appsettings);
            string directory   = Path.GetDirectoryName(path);
            string fileName    = Path.GetFileName(path);
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.SetBasePath(directory);

            var environment = HostingHelpers.GetHostingEnvironment("Production");

            configurationBuilder.AddJsonFile(fileName);

            // Act and Assert
            configurationBuilder.AddConfigServer(environment);
            var config = configurationBuilder.Build();
            ConfigServerConfigurationProvider configServerProvider = config.Providers.OfType <ConfigServerConfigurationProvider>().SingleOrDefault();

            Assert.NotNull(configServerProvider);

            ConfigServerClientSettings settings = configServerProvider.Settings;

            Assert.False(settings.ValidateCertificates);
        }
コード例 #10
0
        public static void run(string path, Mml2vgmInfo info, int index)
        {
            ScriptEngine  engine  = null;
            ScriptRuntime runtime = null;

            try
            {
                engine = Python.CreateEngine();
                var pc    = HostingHelpers.GetLanguageContext(engine) as PythonContext;
                var hooks = pc.SystemState.Get__dict__()["path_hooks"] as List;
                hooks.Clear();
                ScriptSource source = engine.CreateScriptSourceFromFile(path);
                CompiledCode code   = source.Compile();
                ScriptScope  scope  = engine.CreateScope();
                runtime = engine.Runtime;
                Assembly assembly = typeof(Program).Assembly;
                runtime.LoadAssembly(Assembly.LoadFile(assembly.Location));
                source.Execute(scope);

                dynamic    pyClass       = scope.GetVariable("Mml2vgmScript");
                dynamic    mml2vgmScript = pyClass();
                ScriptInfo si            = mml2vgmScript.run(info, index);
                if (si != null && info.document != null)
                {
                    info.document.editor.azukiControl.Document.Replace(si.responseMessage);
                }
            }
            catch (Exception ex)
            {
                log.ForcedWrite(ex);
            }
            finally
            {
                runtime.Shutdown();
            }
        }
コード例 #11
0
        public void AddMetricsActuator_AddsCorrectServices()
        {
            var services = new ServiceCollection();
            var config   = GetConfiguration();

            services.AddOptions();
            services.AddLogging();
            services.AddSingleton(HostingHelpers.GetHostingEnvironment());
            services.AddMetricsActuator(config);

            var serviceProvider = services.BuildServiceProvider();

            var mgr = serviceProvider.GetService <IDiagnosticsManager>();

            Assert.NotNull(mgr);
            var hst = serviceProvider.GetService <IHostedService>();

            Assert.NotNull(hst);
            var opts = serviceProvider.GetService <IMetricsObserverOptions>();

            Assert.NotNull(opts);

            var observers = serviceProvider.GetServices <IDiagnosticObserver>();
            var list      = observers.ToList();

            Assert.Single(list);

            var polled = serviceProvider.GetServices <EventListener>();
            var list2  = polled.ToList();

            Assert.Equal(2, list2.Count);

            var ep = serviceProvider.GetService <MetricsEndpoint>();

            Assert.NotNull(ep);
        }
コード例 #12
0
        private static ScriptEngine CreateEngine(bool fromFile = false)
        {
            var engine = fromFile
                            ? Python.CreateEngine(new Dictionary <string, object> {
                ["Debug"] = true
            })
                            : Python.CreateEngine();
            var pc    = HostingHelpers.GetLanguageContext(engine) as PythonContext;
            var hooks = pc?.SystemState.Get__dict__()["path_hooks"] as List;

            hooks?.Clear();
            var searchPaths   = engine.GetSearchPaths();
            var pythonLibPath = ConfigurationManager.AppSettings["PythonLibPath"];

            if (pythonLibPath != null)
            {
                foreach (var path in pythonLibPath.Split(';'))
                {
                    searchPaths.Add(path);
                }
            }
            engine.SetSearchPaths(searchPaths);
            return(engine);
        }
コード例 #13
0
        private Parser CreatePythonParser(string script)
        {
            var src = HostingHelpers.GetSourceUnit(Engine.CreateScriptSourceFromString(script));

            return(Parser.CreateParser(new CompilerContext(src, Engine.GetCompilerOptions(), ErrorSink.Default), new PythonOptions()));
        }
        public void AddConfigServer_JsonAppSettingsConfiguresClient()
        {
            // Arrange
            var appsettings = @"
                {
                    ""spring"": {
                        ""application"": {
                            ""name"": ""myName""
                    },
                      ""cloud"": {
                        ""config"": {
                            ""uri"": ""https://*****:*****@foo.com:9999"",
                            ""enabled"": false,
                            ""failFast"": false,
                            ""label"": ""myLabel"",
                            ""username"": ""myUsername"",
                            ""password"": ""myPassword"",
                            ""timeout"": 10000,
                            ""token"" : ""vaulttoken"",
                            ""tokenRenewRate"": 50000,
                            ""disableTokenRenewal"": true,    
                            ""tokenTtl"": 50000,
                            ""retry"": {
                                ""enabled"":""false"",
                                ""initialInterval"":55555,
                                ""maxInterval"": 55555,
                                ""multiplier"": 5.5,
                                ""maxAttempts"": 55555
                            }
                        }
                      }
                    }
                }";

            var    path      = TestHelpers.CreateTempFile(appsettings);
            string directory = Path.GetDirectoryName(path);
            string fileName  = Path.GetFileName(path);
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.SetBasePath(directory);

            var environment = HostingHelpers.GetHostingEnvironment("Production");

            configurationBuilder.AddJsonFile(fileName);

            // Act and Assert
            configurationBuilder.AddConfigServer(environment);
            IConfigurationRoot config = configurationBuilder.Build();
            ConfigServerConfigurationProvider configServerProvider = config.Providers.OfType <ConfigServerConfigurationProvider>().SingleOrDefault();

            Assert.NotNull(configServerProvider);
            ConfigServerClientSettings settings = configServerProvider.Settings;

            Assert.False(settings.Enabled);
            Assert.False(settings.FailFast);
            Assert.Equal("https://*****:*****@foo.com:9999", settings.Uri);
            Assert.Equal(ConfigServerClientSettings.DEFAULT_ENVIRONMENT, settings.Environment);
            Assert.Equal("myName", settings.Name);
            Assert.Equal("myLabel", settings.Label);
            Assert.Equal("myUsername", settings.Username);
            Assert.Equal("myPassword", settings.Password);
            Assert.False(settings.RetryEnabled);
            Assert.Equal(55555, settings.RetryAttempts);
            Assert.Equal(55555, settings.RetryInitialInterval);
            Assert.Equal(55555, settings.RetryMaxInterval);
            Assert.Equal(5.5, settings.RetryMultiplier);
            Assert.Equal(10000, settings.Timeout);
            Assert.Equal("vaulttoken", settings.Token);
            Assert.Null(settings.AccessTokenUri);
            Assert.Null(settings.ClientId);
            Assert.Null(settings.ClientSecret);
            Assert.Equal(50000, settings.TokenRenewRate);
            Assert.True(settings.DisableTokenRenewal);
            Assert.Equal(50000, settings.TokenTtl);
        }
        public void AddConfigServer_WithCloudfoundryEnvironmentSCS3_ConfiguresClientCorrectly()
        {
            // Arrange
            var vcap_application = @" 
                {
                    ""vcap"": {
                        ""application"": {
                            ""application_id"": ""fa05c1a9-0fc1-4fbd-bae1-139850dec7a3"",
                            ""application_name"": ""my-app"",
                            ""application_uris"": [
                                ""my-app.10.244.0.34.xip.io""
                            ],
                            ""application_version"": ""fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca"",
                            ""limits"": {
                                ""disk"": 1024,
                                ""fds"": 16384,
                                ""mem"": 256
                            },
                            ""name"": ""my-app"",
                            ""space_id"": ""06450c72-4669-4dc6-8096-45f9777db68a"",
                            ""space_name"": ""my-space"",
                            ""uris"": [
                                ""my-app.10.244.0.34.xip.io"",
                                ""my-app2.10.244.0.34.xip.io""
                            ],
                            ""users"": null,
                            ""version"": ""fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca""
                        }
                    }
                }";

            var vcap_services = @"
                {
                    ""vcap"": {
                        ""services"": {
                            ""p.config-server"": [{
                                ""binding_name"":"""",
                                ""credentials"": {
                                     ""client_secret"":""e8KF1hXvAnGd"",
                                     ""uri"":""https://config-ba6b6079-163b-45d2-8932-e2eca0d1e49a.wise.com"",
                                     ""client_id"":""config-client-ea5e13c2-def2-4a3b-b80c-38e690ec284f"",
                                     ""access_token_uri"":""https://p-spring-cloud-services.uaa.wise.com/oauth/token""
                                },
                                ""instance_name"": ""myConfigServer"",
                                ""label"": ""p.config-server"",
                                ""name"": ""myConfigServer"",
                                ""plan"": ""standard"",
                                ""provider"": null,
                                ""syslog_drain_url"": null,
                                ""tags"": [
                                    ""configuration"",
                                    ""spring-cloud""
                                ],
                                ""volume_mounts"": []
                            }]
                         }
                    }
                }";

            var    appsettings         = @"
                {
                    ""spring"": {
                        ""application"": {
                            ""name"": ""${vcap:application:name?foobar}""   
                        }
                    }
                }";
            var    tempPath            = Path.GetTempPath();
            var    appsettingsPath     = TestHelpers.CreateTempFile(appsettings);
            string appsettingsfileName = Path.GetFileName(appsettingsPath);

            var    vcapAppPath     = TestHelpers.CreateTempFile(vcap_application);
            string vcapAppfileName = Path.GetFileName(vcapAppPath);

            var    vcapServicesPath     = TestHelpers.CreateTempFile(vcap_services);
            string vcapServicesfileName = Path.GetFileName(vcapServicesPath);

            var environment = HostingHelpers.GetHostingEnvironment("Production");

            var configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.SetBasePath(tempPath);
            configurationBuilder.AddJsonFile(appsettingsfileName);
            configurationBuilder.AddJsonFile(vcapAppfileName);
            configurationBuilder.AddJsonFile(vcapServicesfileName);

            // Act and Assert
            configurationBuilder.AddConfigServer(environment);
            IConfigurationRoot config = configurationBuilder.Build();
            ConfigServerConfigurationProvider configServerProvider = config.Providers.OfType <ConfigServerConfigurationProvider>().SingleOrDefault();

            Assert.NotNull(configServerProvider);

            // Check settings
            ConfigServerClientSettings settings = configServerProvider.Settings;

            Assert.True(settings.Enabled);
            Assert.False(settings.FailFast);
            Assert.Equal("https://config-ba6b6079-163b-45d2-8932-e2eca0d1e49a.wise.com", settings.Uri);
            Assert.Equal("https://p-spring-cloud-services.uaa.wise.com/oauth/token", settings.AccessTokenUri);
            Assert.Equal("config-client-ea5e13c2-def2-4a3b-b80c-38e690ec284f", settings.ClientId);
            Assert.Equal("e8KF1hXvAnGd", settings.ClientSecret);
            Assert.Equal(ConfigServerClientSettings.DEFAULT_ENVIRONMENT, settings.Environment);
            Assert.Equal("my-app", settings.Name);
            Assert.Null(settings.Label);
            Assert.Null(settings.Username);
            Assert.Null(settings.Password);
        }
コード例 #16
0
        public async System.Threading.Tasks.Task GetInstanceAsync_FirstServerFails_InvokesSecondServer_ReturnsExpectedInstances()
        {
            var json  = @"
                { 
                    ""instance"":{
                        ""instanceId"":""DESKTOP-GNQ5SUT"",
                        ""app"":""FOOBAR"",
                        ""appGroupName"":null,
                        ""ipAddr"":""192.168.0.147"",
                        ""sid"":""na"",
                        ""port"":{""@enabled"":true,""$"":80},
                        ""securePort"":{""@enabled"":false,""$"":443},
                        ""homePageUrl"":""http://*****:*****@class"":""com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo"",""name"":""MyOwn""},
                        ""hostName"":""DESKTOP-GNQ5SUT"",
                        ""status"":""UP"",
                        ""overriddenstatus"":""UNKNOWN"",
                        ""leaseInfo"":{""renewalIntervalInSecs"":30,""durationInSecs"":90,""registrationTimestamp"":0,""lastRenewalTimestamp"":0,""renewalTimestamp"":0,""evictionTimestamp"":0,""serviceUpTimestamp"":0},
                        ""isCoordinatingDiscoveryServer"":false,
                        ""metadata"":{""@class"":""java.util.Collections$EmptyMap"",""metadata"":null},
                        ""lastUpdatedTimestamp"":1458116137663,
                        ""lastDirtyTimestamp"":1458116137663,
                        ""actionType"":""ADDED"",
                        ""asgName"":null
                    }
                }";
            var envir = HostingHelpers.GetHostingEnvironment();

            TestConfigServerStartup.Response     = json;
            TestConfigServerStartup.ReturnStatus = 200;
            TestConfigServerStartup.Host         = "localhost:8888";
            var builder = new WebHostBuilder().UseStartup <TestConfigServerStartup>().UseEnvironment(envir.EnvironmentName);
            var server  = new TestServer(builder);

            var uri = "http://localhost:8888/";

            server.BaseAddress = new Uri(uri);

            var cconfig = new EurekaClientConfig()
            {
                EurekaServerServiceUrls = "https://bad.host:9999/," + uri
            };
            var client = new EurekaHttpClient(cconfig, server.CreateClient());
            var resp   = await client.GetInstanceAsync("DESKTOP-GNQ5SUT");

            Assert.NotNull(resp);
            Assert.Equal(HttpStatusCode.OK, resp.StatusCode);
            Assert.Equal("GET", TestConfigServerStartup.LastRequest.Method);
            Assert.Equal("localhost:8888", TestConfigServerStartup.LastRequest.Host.Value);
            Assert.Equal("/instances/DESKTOP-GNQ5SUT", TestConfigServerStartup.LastRequest.Path.Value);
            Assert.NotNull(resp.Headers);
            Assert.NotNull(resp.Response);
            Assert.Equal("DESKTOP-GNQ5SUT", resp.Response.InstanceId);
            Assert.Equal("DESKTOP-GNQ5SUT:80", resp.Response.VipAddress);
            Assert.Equal("DESKTOP-GNQ5SUT", resp.Response.HostName);
            Assert.Equal("192.168.0.147", resp.Response.IpAddr);
            Assert.Equal(InstanceStatus.UP, resp.Response.Status);

            Assert.Equal("http://localhost:8888/", client._serviceUrl);
        }
コード例 #17
0
        public async System.Threading.Tasks.Task GetApplicationAsync__FirstServerFails_InvokesSecondServer_ReturnsExpectedApplications()
        {
            var json  = @"
                {
                    ""application"": {
                        ""name"":""FOO"",
                        ""instance"":[{
                            ""instanceId"":""localhost:foo"",
                            ""hostName"":""localhost"",
                            ""app"":""FOO"",
                            ""ipAddr"":""192.168.56.1"",
                            ""status"":""UP"",
                            ""overriddenstatus"":""UNKNOWN"",
                            ""port"":{""$"":8080,""@enabled"":""true""},
                            ""securePort"":{""$"":443,""@enabled"":""false""},
                            ""countryId"":1,
                            ""dataCenterInfo"":{""@class"":""com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo"",""name"":""MyOwn""},
                            ""leaseInfo"":{""renewalIntervalInSecs"":30,""durationInSecs"":90,""registrationTimestamp"":1458152330783,""lastRenewalTimestamp"":1458243422342,""evictionTimestamp"":0,""serviceUpTimestamp"":1458152330783},
                            ""metadata"":{""@class"":""java.util.Collections$EmptyMap""},
                            ""homePageUrl"":""http://localhost:8080/"",
                            ""statusPageUrl"":""http://localhost:8080/info"",
                            ""healthCheckUrl"":""http://localhost:8080/health"",
                            ""vipAddress"":""foo"",
                            ""isCoordinatingDiscoveryServer"":""false"",
                            ""lastUpdatedTimestamp"":""1458152330783"",
                            ""lastDirtyTimestamp"":""1458152330696"",
                            ""actionType"":""ADDED""
                        }]
                    }
                }";
            var envir = HostingHelpers.GetHostingEnvironment();

            TestConfigServerStartup.Response     = json;
            TestConfigServerStartup.ReturnStatus = 200;
            TestConfigServerStartup.Host         = "localhost:8888";
            var builder = new WebHostBuilder().UseStartup <TestConfigServerStartup>().UseEnvironment(envir.EnvironmentName);
            var server  = new TestServer(builder);

            var uri = "http://localhost:8888/";

            server.BaseAddress = new Uri(uri);

            var cconfig = new EurekaClientConfig()
            {
                EurekaServerServiceUrls = "https://bad.host:9999/," + uri
            };
            var client = new EurekaHttpClient(cconfig, server.CreateClient());
            var resp   = await client.GetApplicationAsync("foo");

            Assert.NotNull(resp);
            Assert.Equal(HttpStatusCode.OK, resp.StatusCode);
            Assert.Equal("GET", TestConfigServerStartup.LastRequest.Method);
            Assert.Equal("localhost:8888", TestConfigServerStartup.LastRequest.Host.Value);
            Assert.Equal("/apps/foo", TestConfigServerStartup.LastRequest.Path.Value);
            Assert.NotNull(resp.Headers);
            Assert.NotNull(resp.Response);
            Assert.Equal("FOO", resp.Response.Name);

            var instances = resp.Response.Instances;

            Assert.NotNull(instances);
            Assert.Equal(1, instances.Count);
            foreach (var instance in instances)
            {
                Assert.Equal("localhost:foo", instance.InstanceId);
                Assert.Equal("foo", instance.VipAddress);
                Assert.Equal("localhost", instance.HostName);
                Assert.Equal("192.168.56.1", instance.IpAddr);
                Assert.Equal(InstanceStatus.UP, instance.Status);
            }

            Assert.Equal("http://localhost:8888/", client._serviceUrl);
        }
コード例 #18
0
 public static EssenceSharpContext essenceSharpContext(this ScriptEngine engine)
 {
     return((EssenceSharpContext)HostingHelpers.GetLanguageContext(engine));
 }
コード例 #19
0
ファイル: Python.cs プロジェクト: zpeach68/ironpython2
 private static PythonContext /*!*/ GetPythonContext(ScriptEngine /*!*/ engine)
 {
     return(HostingHelpers.GetLanguageContext(engine) as PythonContext);
 }
コード例 #20
0
        protected override bool ShouldEvaluateForCompletion(string source)
        {
            var scriptSrc = _localEngine.CreateScriptSource(new StringTextContentProvider(source), "", SourceCodeKind.Expression);
            var context   = new CompilerContext(HostingHelpers.GetSourceUnit(scriptSrc), HostingHelpers.GetLanguageContext(_localEngine).GetCompilerOptions(), ErrorSink.Null);
            var parser    = Parser.CreateParser(context, new PythonOptions());

            var stmt       = parser.ParseSingleStatement();
            var exprWalker = new ExprWalker();

            stmt.Walk(exprWalker);
            return(exprWalker.ShouldExecute);
        }
コード例 #21
0
        public async System.Threading.Tasks.Task FetchFullRegistryAsync_InvokesServer_ReturnsValidResponse()
        {
            var json = @"
                { 
                    ""applications"": { 
                        ""versions__delta"":""1"",
                        ""apps__hashcode"":""UP_1_"",
                        ""application"":[{
                            ""name"":""FOO"",
                            ""instance"":[{ 
                                ""instanceId"":""localhost:foo"",
                                ""hostName"":""localhost"",
                                ""app"":""FOO"",
                                ""ipAddr"":""192.168.56.1"",
                                ""status"":""UP"",
                                ""overriddenstatus"":""UNKNOWN"",
                                ""port"":{""$"":8080,""@enabled"":""true""},
                                ""securePort"":{""$"":443,""@enabled"":""false""},
                                ""countryId"":1,
                                ""dataCenterInfo"":{""@class"":""com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo"",""name"":""MyOwn""},
                                ""leaseInfo"":{""renewalIntervalInSecs"":30,""durationInSecs"":90,""registrationTimestamp"":1457714988223,""lastRenewalTimestamp"":1457716158319,""evictionTimestamp"":0,""serviceUpTimestamp"":1457714988223},
                                ""metadata"":{""@class"":""java.util.Collections$EmptyMap""},
                                ""homePageUrl"":""http://localhost:8080/"",
                                ""statusPageUrl"":""http://localhost:8080/info"",
                                ""healthCheckUrl"":""http://localhost:8080/health"",
                                ""vipAddress"":""foo"",
                                ""isCoordinatingDiscoveryServer"":""false"",
                                ""lastUpdatedTimestamp"":""1457714988223"",
                                ""lastDirtyTimestamp"":""1457714988172"",
                                ""actionType"":""ADDED""
                            }]
                        }]
                    }
                }";

            var envir = HostingHelpers.GetHostingEnvironment();

            TestConfigServerStartup.Response     = json;
            TestConfigServerStartup.ReturnStatus = 200;
            var builder = new WebHostBuilder().UseStartup <TestConfigServerStartup>().UseEnvironment(envir.EnvironmentName);
            var server  = new TestServer(builder);

            var uri = "http://localhost:8888/";

            server.BaseAddress = new Uri(uri);
            var config = new EurekaClientConfig()
            {
                ShouldFetchRegistry      = false,
                ShouldRegisterWithEureka = false,
                EurekaServerServiceUrls  = uri.ToString()
            };

            var httpClient = new EurekaHttpClient(config, server.CreateClient());
            var client     = new DiscoveryClient(config, httpClient);
            var result     = await client.FetchFullRegistryAsync();

            Assert.NotNull(result);
            Assert.Equal(1, result.Version);
            Assert.Equal("UP_1_", result.AppsHashCode);

            var apps = result.GetRegisteredApplications();

            Assert.NotNull(apps);
            Assert.Equal(1, apps.Count);
            Assert.Equal("FOO", apps[0].Name);
        }
コード例 #22
0
 internal static Scope scope(this ScriptScope aScriptScope)
 {
     return(HostingHelpers.GetScope(aScriptScope));
 }
コード例 #23
0
 // TODO:
 public static RubyContext /*!*/ GetExecutionContext(ScriptEngine /*!*/ engine)
 {
     ContractUtils.RequiresNotNull(engine, "engine");
     return((RubyContext)HostingHelpers.GetLanguageContext(engine));
 }
コード例 #24
0
        public void ReLoad_DataDictionary_With_New_Configurations()
        {
            // Arrange
            var environment = @"
                    {
                        ""name"": ""testname"",
                        ""profiles"": [""Production""],
                        ""label"": ""testlabel"",
                        ""version"": ""testversion"",
                        ""propertySources"": [ 
                            { 
                                ""name"": ""source"",
                                ""source"": {
                                            ""featureToggles.ShowModule[0]"": ""FT1"",
                                            ""featureToggles.ShowModule[1]"": ""FT2"",
                                            ""featureToggles.ShowModule[2]"": ""FT3"",
                                            ""enableSettings"":""true""
                                    }
                            }
                        ]
                    }";

            var envir = HostingHelpers.GetHostingEnvironment();

            TestConfigServerStartup.Reset();
            TestConfigServerStartup.Response = environment;
            var builder = new WebHostBuilder().UseStartup <TestConfigServerStartup>().UseEnvironment(envir.EnvironmentName);
            var server  = new TestServer(builder);

            var settings = new ConfigServerClientSettings
            {
                Uri  = "http://*****:*****@"
                {
                    ""name"": ""testname"",
                    ""profiles"": [""Production""],
                    ""label"": ""testlabel"",
                    ""version"": ""testversion"",
                    ""propertySources"": [ 
                        { 
                            ""name"": ""source"",
                            ""source"": {
                                ""featureToggles.ShowModule[0]"": ""none""
                            }
                        }
                    ]
                }";
            provider.Load();
            Assert.True(provider.TryGet("featureToggles:ShowModule:0", out var val));
            Assert.Equal("none", val);
            Assert.False(provider.TryGet("featureToggles:ShowModule:1", out _));
            Assert.False(provider.TryGet("featureToggles:ShowModule:2", out _));
            Assert.False(provider.TryGet("enableSettings", out _));
        }
コード例 #25
0
        protected SourceUnit CreateSourceUnit(string code)
        {
            var context = HostingHelpers.GetLanguageContext(_engine);

            return(context.CreateSnippet(code, SourceCodeKind.InteractiveCode));
        }
コード例 #26
0
        public PythonEnvironmentModule(IEventAggregator aggregator, IEntityManagerViewModel entityManager,
                                       IThermodynamicSystemImporter importer,
                                       IChartViewModelFactory chartFactory,
                                       IFlowsheetEntityEditorFactory flowsheetFactory,
                                       IPureComponentPropertyDatabase pureDB,
                                       IThermodynamicSystemViewModelFactory thermoEditorFactory
                                       )
        {
            _aggregator          = aggregator;
            _entityManager       = entityManager;
            _importer            = importer;
            _chartFactory        = chartFactory;
            _flowsheetFactory    = flowsheetFactory;
            _pyEngine            = Python.CreateEngine();
            _pyScope             = _pyEngine.CreateScope();
            _pureComponentDB     = pureDB;
            _thermoEditorFactory = thermoEditorFactory;

            _pyScope.SetVariable("_host", this);
            _pyScope.SetVariable("Items", _entityManager);
            _pyEngine.SetSearchPaths(new List <string> {
                Environment.CurrentDirectory
            });
            var pc    = HostingHelpers.GetLanguageContext(_pyEngine) as PythonContext;
            var hooks = pc.SystemState.Get__dict__()["path_hooks"] as List;

            hooks.Clear();
            Run("import sys");
            Run("import clr");
            Run("clr.AddReferenceToFile(\"OpenFMSL.Core.dll\")");
            Run("clr.AddReferenceToFile(\"OpenFMSL.Contracts.dll\")");

            Run("from OpenFMSL.Core.Expressions import *");
            Run("from OpenFMSL.Core.Flowsheeting import *");
            Run("from OpenFMSL.Core.Flowsheeting.Documentation import *");
            Run("from OpenFMSL.Core.Numerics import *");
            Run("from OpenFMSL.Core.Numerics.Solvers import *");
            Run("from OpenFMSL.Core.UnitsOfMeasure import *");
            Run("from OpenFMSL.Core.ModelLibrary import *");
            Run("from OpenFMSL.Core.Thermodynamics import *");

            Run("from OpenFMSL.Contracts.Entities import *");
            Run("from OpenFMSL.Contracts.Infrastructure.Reporting import *");

            Run("from System import Math");
            Run("sys.stdout=_host");
            Run("runFile= _host.RunFile");
            Run("run= _host.RunEntity");
            Run("pause= _host.WaitThread");
            Run("CreateThermo= _host.LoadThermodynamicSystem");

            _pureComponentDB.SetLogCallback(Write);

            ipopt       = new IpoptSolver();
            ipopt.OnLog = (x) => Write("    " + x + Environment.NewLine);
            _pyScope.SetVariable("_ipopt", ipopt);
            _pyScope.SetVariable("Database", _pureComponentDB);

            newton              = new Newton();
            newton.OnLog        = (x) => Write("    " + x + Environment.NewLine);
            newton.OnLogDebug   = (x) => Write(x + Environment.NewLine);
            newton.OnLogError   = (x) => Write("!!! " + x + Environment.NewLine);
            newton.OnLogSuccess = (x) => Write("+++ " + x + Environment.NewLine);
            newton.OnLogWarning = (x) => Write("*** " + x + Environment.NewLine);
            newton.OnLogInfo    = (x) => Write("--- " + x + Environment.NewLine);
            _pyScope.SetVariable("_newton", newton);

            var flash = new FlashRoutines(newton);

            _pyScope.SetVariable("_flash", flash);

            decomp              = new Decomposer();
            decomp.OnLog        = (x) => Write("    " + x + Environment.NewLine);
            decomp.OnLogDebug   = (x) => Write(x + Environment.NewLine);
            decomp.OnLogError   = (x) => Write("!!! " + x + Environment.NewLine);
            decomp.OnLogSuccess = (x) => Write("+++ " + x + Environment.NewLine);
            decomp.OnLogWarning = (x) => Write("*** " + x + Environment.NewLine);
            decomp.OnLogInfo    = (x) => Write("--- " + x + Environment.NewLine);

            _pyScope.SetVariable("_decomp", decomp);

            Run("solve= _host.Solve");
            Run("decomp= _host.Decompose");
            Run("report= _host.Report");

            Run("show= _host.Show");
            Run("check= _host.Check");

            Run("info= _host.SendLogMessage");
            Run("warn= _host.SendWarningMessage");
            Run("error= _host.SendErrorMessage");

            Run("FlashPT= _flash.CalculateTP");
            Run("FlashPZ= _flash.CalculateZP");



            Run("status= _host.SendStatusTextChangeMessage");

            Run("print 'Python console running...");
        }
コード例 #27
0
ファイル: Driver.cs プロジェクト: ife/IronLanguages
        public static int Run(List <string> /*!*/ args, string baseDirectory)
        {
#if !WIN8
            if (Thread.CurrentThread.CurrentCulture.ToString() != "en-US")
            {
                WriteOutput("Current culture: {0}", Thread.CurrentThread.CurrentCulture);
            }
#endif
            if (!ParseArguments(args))
            {
                return(-3);
            }

#if !WIN8
            if (_runTokenizerDriver)
            {
                TokenizerTestDriver tokenizerDriver = new TokenizerTestDriver((RubyContext)HostingHelpers.GetLanguageContext(Ruby.CreateEngine()));
                if (!tokenizerDriver.ParseArgs(args))
                {
                    return(-3);
                }

                return(tokenizerDriver.RunTests());
            }
#endif
            InitializeDomain();
            Driver driver = new Driver(baseDirectory);

            if (Manual.TestCode.Trim().Length == 0)
            {
                return(driver.RunUnitTests(args));
            }

#if !WIN8
            driver.RunManualTest();
#endif
            // for case the test is forgotten, this would fail the test suite:
            return(-2);
        }
コード例 #28
0
 /// <summary>
 /// Loads a given script file using the semantics of Kernel#require method.
 /// The script is executed within the context of a given <see cref="ScriptScope"/>.
 /// </summary>
 /// <param name="engine">The Ruby engine.</param>
 /// <param name="path">The path to the file to load.</param>
 /// <param name="scope">The scope to use for the script execution.</param>
 /// <returns>Whether the file has already been required.</returns>
 /// <remarks>
 /// If a relative path is given the current search paths are used to locate the script file.
 /// The current search paths could be read and modified via <see cref="ScriptEngine.GetSearchPaths"/> and <see cref="ScriptEngine.SetSearchPaths"/>,
 /// respectively.
 /// </remarks>
 public bool RequireFile(string /*!*/ path, ScriptScope /*!*/ scope)
 {
     ContractUtils.RequiresNotNull(path, "path");
     ContractUtils.RequiresNotNull(scope, "scope");
     return(RequireFile(path, HostingHelpers.GetScope(scope)));
 }
コード例 #29
0
        public void TestAnalyzeStdLib()
        {
            //string dir = Path.Combine(Environment.GetEnvironmentVariable("ProgramFiles"), "IronPython 2.6 for .NET 4.0 RC\\Lib");
            string        dir   = Path.Combine("C:\\Python27\\Lib");
            List <string> files = new List <string>();

            CollectFiles(dir, files);

            List <SourceUnit> sourceUnits = new List <SourceUnit>();

            foreach (string file in files)
            {
                sourceUnits.Add(
                    new SourceUnit(
                        HostingHelpers.GetLanguageContext(_engine),
                        new FileTextContentProvider(new FileStreamContentProvider(file)),
                        Path.GetFileNameWithoutExtension(file),
                        SourceCodeKind.File
                        )
                    );
            }

            Stopwatch sw = new Stopwatch();

            sw.Start();
            long start0                      = sw.ElapsedMilliseconds;
            var  projectState                = new ProjectState(_engine);
            List <ProjectEntry> modules      = new List <ProjectEntry>();
            PythonOptions       EmptyOptions = new PythonOptions();

            foreach (var sourceUnit in sourceUnits)
            {
                modules.Add(projectState.AddModule(Path.GetFileNameWithoutExtension(sourceUnit.Path), sourceUnit.Path, null));
            }
            long start1 = sw.ElapsedMilliseconds;

            Console.WriteLine("AddSourceUnit: {0} ms", start1 - start0);

            List <PythonAst> nodes = new List <PythonAst>();

            for (int i = 0; i < modules.Count; i++)
            {
                PythonAst ast = null;
                try {
                    var sourceUnit = sourceUnits[i];

                    var context = new CompilerContext(sourceUnit, HostingHelpers.GetLanguageContext(_engine).GetCompilerOptions(), ErrorSink.Null);
                    ast = Parser.CreateParser(context, EmptyOptions).ParseFile(false);
                } catch (Exception) {
                }
                nodes.Add(ast);
            }
            long start2 = sw.ElapsedMilliseconds;

            Console.WriteLine("Parse: {0} ms", start2 - start1);

            for (int i = 0; i < modules.Count; i++)
            {
                var ast = nodes[i];

                if (ast != null)
                {
                    modules[i].UpdateTree(ast, null);
                }
            }

            long start3 = sw.ElapsedMilliseconds;

            for (int i = 0; i < modules.Count; i++)
            {
                Console.WriteLine("Analyzing {1}: {0} ms", sw.ElapsedMilliseconds - start3, sourceUnits[i].Path);
                var ast = nodes[i];
                if (ast != null)
                {
                    modules[i].Analyze();
                }
            }
            long start4 = sw.ElapsedMilliseconds;

            Console.WriteLine("Analyze: {0} ms", start4 - start3);
            Console.ReadLine();
        }
コード例 #30
0
 public override void ErrorReported(ScriptSource source, string message, SourceSpan span, int errorCode, Severity severity)
 {
     throw new SyntaxErrorException(message, HostingHelpers.GetSourceUnit(source), span, errorCode, severity);
 }