public void CatchesSimpleImportCollision()
    {
        var fileSystem = new InMemoryFileProvider();

        fileSystem.RegisterFileWithIdentifier("root.lsystem", @"
#axiom Y
#iterations 1000
#symbols XY

#include lib0.lsyslib (Exported->X)
#include lib1.lsyslib (Exported->X)
");

        fileSystem.RegisterFileWithIdentifier("lib0.lsyslib", @"
#symbols AB
#export Exported A
");
        fileSystem.RegisterFileWithIdentifier("lib1.lsyslib", @"
#symbols CD
#export Exported C
");
        var linker = new FileLinker(fileSystem);

        try
        {
            linker.LinkFiles("root.lsystem");
        }
        catch (LinkException e)
        {
            Assert.AreEqual(LinkExceptionType.IMPORT_COLLISION, e.exceptionType);
            return;
        }
        Assert.Fail("linker must prevent importing symbols in such a way that it attempts to represent multiple symbols with the same character");
    }
    public void TryGetResponseContentReturnsCorrectContentTypeForNonPhysicalFile()
    {
        // Arrange
        const string cssFilePath          = "folder/file.css";
        const string cssFileContent       = "this is css";
        var          inMemoryFileProvider = new InMemoryFileProvider(
            new Dictionary <string, string>
        {
            { cssFilePath, cssFileContent },
        });
        var appBase = "fake://0.0.0.0/";
        var scp     = new StaticContentProvider(inMemoryFileProvider, new Uri(appBase), "fakehost.html");

        // Act
        Assert.True(scp.TryGetResponseContent(
                        requestUri: appBase + cssFilePath,
                        allowFallbackOnHostPage: false,
                        out var statusCode,
                        out var statusMessage,
                        out var content,
                        out var headers));

        // Assert
        var contentString = new StreamReader(content).ReadToEnd();

        Assert.Equal(200, statusCode);
        Assert.Equal("OK", statusMessage);
        Assert.Equal("this is css", contentString);
        Assert.True(headers.TryGetValue("Content-Type", out var contentTypeValue));
        Assert.Equal("text/css", contentTypeValue);
    }
    public void CatchesRunTimeVariableCollision()
    {
        var fileSystem = new InMemoryFileProvider();

        fileSystem.RegisterFileWithIdentifier("root.lsystem", @"
#axiom Y
#iterations 1000
#symbols XY

#runtime runTime 1992.01
#include lib0.lsyslib
");

        fileSystem.RegisterFileWithIdentifier("lib0.lsyslib", @"
#symbols AB
#runtime runTime 1992.01
#export Exported A
");
        var linker = new FileLinker(fileSystem);

        try
        {
            linker.LinkFiles("root.lsystem");
        }
        catch (LinkException e)
        {
            Assert.AreEqual(LinkExceptionType.GLOBAL_VARIABLE_COLLISION, e.exceptionType);
            return;
        }
        Assert.Fail("linker must prevent declaration of multiple global runtime variables with the same name");
    }
    public void CatchesMissingInclude()
    {
        var fileSystem = new InMemoryFileProvider();

        fileSystem.RegisterFileWithIdentifier("root.lsystem", @"
#axiom Y
#iterations 1000
#symbols XYZ

#include missinglib.lsyslib
");

        fileSystem.RegisterFileWithIdentifier("lib0.lsyslib", @"
#symbols AB
");
        var linker = new FileLinker(fileSystem);

        try
        {
            linker.LinkFiles("root.lsystem");
        }
        catch (LinkException e)
        {
            Assert.AreEqual(LinkExceptionType.MISSING_FILE, e.exceptionType);
            return;
        }
        Assert.Fail("linker must gracefully fail when it cannot find a file");
    }
예제 #5
0
        public void Can_Search_For_Files()
        {
            // Arrange

            var directory = new InMemoryDirectory();

            // Add some files
            directory.AddFile("/foo", new StringFileInfo("greetings", "bar.txt"));
            directory.AddFile("/foo", new StringFileInfo("another", "baz.txt"));
            directory.AddFile("/bar", new StringFileInfo("hi", "bar.txt"));
            directory.AddFile("/foo", new StringFileInfo("foo", "bar.txt.min"));

            var testProvider = new InMemoryFileProvider(directory);

            // Act


            // Assert
            // Assert that we can get the file from the directory using its full path.
            var results = testProvider.Search("/foo/*.txt").ToArray();

            Assert.NotNull(results);
            Assert.Equal(2, results.Length);
            Assert.Equal(results[0].Item1, "/foo");
            Assert.Equal(results[0].Item2.Name, "bar.txt");
            Assert.Equal(results[1].Item1, "/foo");
            Assert.Equal(results[1].Item2.Name, "baz.txt");
        }
        public void FullSimulation()
        {
            //var temp = Path.GetTempPath();

            //var fileNames = new[]
            //{
            //    Path.GetRandomFileName(),
            //    Path.GetRandomFileName(),
            //    Path.GetRandomFileName(),
            //};

            var fileProvider = new InMemoryFileProvider
            {
                { @"C:\temp" },
                { @"C:\temp\foo.txt", "foo" },
                { @"C:\temp\bar.txt", "bar" },
                { @"C:\temp\sub" },
                { @"C:\temp\sub\baz.txt", "baz" },
            };

            //Assert.AreEqual(5, fileProvider.GetFileInfo(@"C:\temp").Count());
            //Assert.AreEqual(2, fileProvider.GetFileInfo(@"C:\temp\sub").Count());

            var foo = fileProvider.GetFileInfoAsync(@"C:\temp\foo.txt").Result;

            Assert.IsTrue(foo.Exists);
            Assert.IsFalse(foo.IsDirectory);
            Assert.AreEqual("foo", foo.ReadAllTextAsync().GetAwaiter().GetResult());

            var sub = fileProvider.GetFileInfoAsync(@"C:\temp\sub").Result;

            Assert.IsTrue(sub.Exists);
            Assert.IsTrue(sub.IsDirectory);
            //Assert.AreEqual(2, sub.Count());
        }
        public void MethodEchoWritesLog()
        {
            var services = new ServiceCollection();

            services.AddSingleton <IFileProvider, InMemoryFileProvider>();
            services.AddSingleton <IApplicationRuntime, WebApplicationEngine>();
            services.AddSingleton <IConfiguration>(Mock.Of <Func <IServiceProvider, IConfiguration> >());
            var fakeFS = new InMemoryFileProvider();

            fakeFS.AddFile("main.os", "Сообщить(\"Я строка лога\")");
            services.AddSingleton <IFileProvider>(fakeFS);

            var loggerMock = new Mock <ILogger <ApplicationInstance> >();

            services.TryAddSingleton(loggerMock.Object);
            services.AddTransient <IApplicationFactory, AppStarter>();

            var provider = services.BuildServiceProvider();
            var starter  = provider.GetService <IApplicationFactory>();

            starter.CreateApp();
            loggerMock.Verify(x =>
                              x.Log(
                                  LogLevel.Information,
                                  It.IsAny <EventId>(),
                                  It.Is <It.IsAnyType>((v, t) => true),
                                  null,
                                  It.Is <Func <It.IsAnyType, Exception, string> >((v, t) => true)),
                              Times.Once);
        }
        public void CheckIfCustomHandlerIsRegistered()
        {
            var services = new ServiceCollection();

            services.AddSingleton <IApplicationRuntime>(CreateWebEngineMock());
            services.AddCustomAuthorization();

            var fakeFs = new InMemoryFileProvider();

            fakeFs.AddFile("auth.os", "Процедура ПриРегистрацииОбработчиков(Список)\n" +
                           "   Список.Добавить(\"customAuth.os\");\n" +
                           "КонецПроцедуры");
            fakeFs.AddFile("customAuth.os", "");

            services.AddSingleton <IFileProvider>(fakeFs);

            var provider = services.BuildServiceProvider();

            var handlers = provider.GetRequiredService <IAuthorizationHandlerProvider>();
            var context  = new AuthorizationHandlerContext(new IAuthorizationRequirement[0], new ClaimsPrincipal(), null);
            var result   = handlers.GetHandlersAsync(context).Result;

            Assert.IsType <OneScriptAuthorizationHandlerProvider>(handlers);
            Assert.True(result.Count() == 1);
        }
    public void CatchesMissingExport()
    {
        var fileSystem = new InMemoryFileProvider();

        fileSystem.RegisterFileWithIdentifier("root.lsystem", @"
#axiom Y
#iterations 1000
#symbols XYZ

#include lib0.lsyslib (NotExported->X)
");

        fileSystem.RegisterFileWithIdentifier("lib0.lsyslib", @"
#symbols AB
#export Exported A
");
        var linker = new FileLinker(fileSystem);

        try
        {
            linker.LinkFiles("root.lsystem");
        }
        catch (LinkException e)
        {
            Assert.AreEqual(LinkExceptionType.MISSING_EXPORT, e.exceptionType);
            return;
        }
        Assert.Fail("linker must prevent importing symbols which are not exported");
    }
예제 #10
0
        public void CanActivateVC_Through_Activator()
        {
            lock (TestOrderingLock.Lock)
            {
                var services = new ServiceCollection();
                var fakefs   = new InMemoryFileProvider();
                fakefs.AddFile("viewComponents/test.os", "Функция ОбработкаВызова() КонецФункции");
                services.AddSingleton <IFileProvider>(fakefs);

                var serviceProvider = services.BuildServiceProvider();

                var cp = new ScriptedViewComponentFeatureProvider();
                cp.Engine             = new ScriptingEngine();
                cp.Engine.Environment = new RuntimeEnvironment();
                cp.ScriptsProvider    = serviceProvider.GetService <IFileProvider>();

                var feature = new ViewComponentFeature();
                var pm      = new ApplicationPartManager();
                pm.ApplicationParts.Add(new AssemblyPart(Assembly.GetExecutingAssembly()));
                pm.FeatureProviders.Add(cp);
                pm.PopulateFeature(feature);

                var descriptorProvider = new DefaultViewComponentDescriptorProvider(pm);
                var activator          = new OscriptViewComponentActivator();
                var descriptor         = descriptorProvider.GetViewComponents().First();
                var context            = new ViewComponentContext();
                context.ViewComponentDescriptor = descriptor;
                var result = activator.Create(context);

                Assert.IsType <ScriptedViewComponent>(result);
            }
        }
예제 #11
0
        public void Can_Search_For_Files_Using_Multiple_Includes_And_Excludes()
        {
            // Arrange

            var directory = new InMemoryDirectory();

            // Add some files
            directory.AddFile("/foo", new StringFileInfo("greetings", "bar.txt"));
            directory.AddFile("/foo", new StringFileInfo("another", "baz.txt"));
            directory.AddFile("/bar", new StringFileInfo("hi", "bar.txt"));
            directory.AddFile("/foo", new StringFileInfo("foo", "bar.txt.min"));

            var testProvider = new InMemoryFileProvider(directory);

            // Act


            // Assert
            // Assert that we can get the file from the directory using its full path.
            var includes = new string[] { "/foo/*.txt", "/bar/bar.txt" };

            var results = testProvider.Search(includes, "/foo/baz.txt").ToArray();

            Assert.NotNull(results);
            Assert.Equal(2, results.Length);
        }
        public void TokensFiredOnFileDeleted()
        {
            var rootDir = new InMemoryDirectory("root");

            // add a file at root/a.txt
            var fileItem = rootDir.AddFile("", new StringFileInfo("some content", "b.txt"));

            using (var provider = new InMemoryFileProvider(rootDir))
            {
                var filePath = "root/b.txt";
                // var fileInfo = provider.GetFileInfo("root/b.txt");
                var token = provider.Watch(filePath);
                Assert.NotNull(token);
                Assert.False(token.HasChanged);
                Assert.True(token.ActiveChangeCallbacks);

                bool callbackInvoked = false;
                token.RegisterChangeCallback(state =>
                {
                    callbackInvoked = true;
                }, state: null);

                // Trigger a change.
                fileItem.Delete();
                Assert.True(token.HasChanged);
                Assert.True(callbackInvoked);
            }
        }
        public void CheckIfControllerThisObjectAccessible()
        {
            var fakefs = new InMemoryFileProvider();

            fakefs.AddFile("controllers/test.os", "Процедура Б() А = ЭтотОбъект; КонецПроцедуры");
            fakefs.AddFile("main.os", "");
            var appEngine = new WebApplicationEngine();
            var app       = ApplicationInstance.Create(new FileInfoCodeSource(fakefs.GetFileInfo("main.os")), appEngine);
            var provider  = new OscriptApplicationModelProvider(app, appEngine, fakefs, Mock.Of <IAuthorizationPolicyProvider>());

            var context = new ApplicationModelProviderContext(new TypeInfo[0]);

            provider.OnProvidersExecuting(context);

            var cc = new ControllerContext();
            var ad = new ControllerActionDescriptor();

            ad.Properties["type"]            = context.Result.Controllers[0].Properties["type"];
            ad.Properties["CompilationInfo"] = context.Result.Controllers[0].Properties["CompilationInfo"];
            cc.ActionDescriptor    = ad;
            cc.HttpContext         = new DefaultHttpContext();
            cc.HttpContext.Session = null;

            var activator  = new ScriptedControllerActivator(appEngine);
            var controller = (ScriptedController)activator.Create(cc);

            Assert.Equal(controller, controller.GetPropValue(0));
        }
        public void CheckIfControllerCreatedFromScript()
        {
            var fakefs = new InMemoryFileProvider();

            fakefs.AddFile("controllers/test.os", "");
            fakefs.AddFile("main.os", "");
            var appEngine = new WebApplicationEngine();
            var app       = ApplicationInstance.Create(new FileInfoCodeSource(fakefs.GetFileInfo("main.os")), appEngine);
            var provider  = new OscriptApplicationModelProvider(app, appEngine, fakefs, Mock.Of <IAuthorizationPolicyProvider>());

            var context = new ApplicationModelProviderContext(new TypeInfo[0]);

            provider.OnProvidersExecuting(context);

            var cc = new ControllerContext();
            var ad = new ControllerActionDescriptor();

            ad.Properties["type"]   = context.Result.Controllers[0].Properties["type"];
            ad.Properties["module"] = context.Result.Controllers[0].Properties["module"];
            cc.ActionDescriptor     = ad;
            cc.HttpContext          = new DefaultHttpContext();
            cc.HttpContext.Session  = null;

            var activator  = new ScriptedControllerActivator(appEngine);
            var controller = (ScriptedController)activator.Create(cc);

            Assert.Equal("Контроллер.test", controller.SystemType.Name);
        }
    public void AllowsImportCollisionToPreventDissonance()
    {
        var fileSystem = new InMemoryFileProvider();

        fileSystem.RegisterFileWithIdentifier("root.lsystem", @"
#axiom Y
#iterations 1000
#symbols XY

#include lib0.lsyslib (Exported->X)
#include lib1.lsyslib (Exported->X)
");

        fileSystem.RegisterFileWithIdentifier("lib0.lsyslib", @"
#symbols AB
#include lib2.lsyslib (Exported->A)
#export Exported A
");
        fileSystem.RegisterFileWithIdentifier("lib1.lsyslib", @"
#symbols CD
#include lib2.lsyslib (Exported->C)
#export Exported C
");
        fileSystem.RegisterFileWithIdentifier("lib2.lsyslib", @"
#symbols EF
#export Exported E
");
        var linker    = new FileLinker(fileSystem);
        var linkedSet = linker.LinkFiles("root.lsystem");

        var rootFile = linkedSet.allFiles.data[linkedSet.fileIndexesByFullIdentifier["root.lsystem"]];

        Assert.AreEqual(4, rootFile.allSymbolAssignments.Count);
        Assert.AreEqual(4, rootFile.allSymbolAssignments.Select(x => x.sourceCharacter).Intersect("XY[]").Count());

        var lib0File = linkedSet.allFiles.data[linkedSet.fileIndexesByFullIdentifier["lib0.lsyslib"]];

        Assert.AreEqual(4, lib0File.allSymbolAssignments.Count);
        Assert.AreEqual(4, lib0File.allSymbolAssignments.Select(x => x.sourceCharacter).Intersect("AB[]").Count());

        var lib1File = linkedSet.allFiles.data[linkedSet.fileIndexesByFullIdentifier["lib1.lsyslib"]];

        Assert.AreEqual(4, lib1File.allSymbolAssignments.Count);
        Assert.AreEqual(4, lib1File.allSymbolAssignments.Select(x => x.sourceCharacter).Intersect("CD[]").Count());

        var lib2File = linkedSet.allFiles.data[linkedSet.fileIndexesByFullIdentifier["lib2.lsyslib"]];

        Assert.AreEqual(4, lib2File.allSymbolAssignments.Count);
        Assert.AreEqual(4, lib2File.allSymbolAssignments.Select(x => x.sourceCharacter).Intersect("EF[]").Count());

        var importedInRoot = rootFile.GetSymbolInFile('X');
        var exportedInLib0 = lib0File.GetSymbolInFile('A');
        var exportedInLib1 = lib1File.GetSymbolInFile('C');
        var exportedInLib2 = lib2File.GetSymbolInFile('E');

        Assert.AreEqual(exportedInLib2, exportedInLib1);
        Assert.AreEqual(exportedInLib2, exportedInLib0);
        Assert.AreEqual(exportedInLib2, importedInRoot);
    }
 public void GetFileInfo_ReturnsNotFoundFileInfo_ForEmptyPath()
 {
     using (var provider = new InMemoryFileProvider())
     {
         var info = provider.GetFileInfo(string.Empty);
         Assert.IsType(typeof(NotFoundFileInfo), info);
     }
 }
 public void GetFileInfo_ReturnsNotFoundFileInfo_ForRelativePathAboveRootPath()
 {
     using (var provider = new InMemoryFileProvider())
     {
         var info = provider.GetFileInfo(Path.Combine("..", Guid.NewGuid().ToString()));
         Assert.IsType(typeof(NotFoundFileInfo), info);
     }
 }
 public void GetFileInfo_ReturnsNonExistentFileInfo_ForIllegalPath(string path)
 {
     using (var provider = new InMemoryFileProvider())
     {
         var info = provider.GetFileInfo(path);
         Assert.False(info.Exists);
     }
 }
예제 #19
0
    public void LinksSimpleDependencyAndExecutes()
    {
        var fileSystem = new InMemoryFileProvider();

        fileSystem.RegisterFileWithIdentifier("root.lsystem", @"
#axiom Y
#iterations 10
#symbols XY

#include lib.lsyslib (Exported->X)
Y -> YX
");

        fileSystem.RegisterFileWithIdentifier("lib.lsyslib", @"
#symbols AB
#export Exported B

B -> AB
");
        var linker      = new FileLinker(fileSystem);
        var linkedFiles = linker.LinkFiles("root.lsystem");

        using var system = linkedFiles.CompileSystem();
        LSystemState <float> currentState = new DefaultLSystemState(
            linkedFiles.GetAxiom(),
            (uint)UnityEngine.Random.Range(int.MinValue, int.MaxValue));

        var X = linkedFiles.GetSymbol("root.lsystem", 'X');
        var Y = linkedFiles.GetSymbol("root.lsystem", 'Y');
        var A = linkedFiles.GetSymbol("lib.lsyslib", 'A');
        var B = linkedFiles.GetSymbol("lib.lsyslib", 'B');

        Assert.AreEqual(B, X);

        var symbolStringMapping = new Dictionary <int, char>()
        {
            { X, 'X' },
            { Y, 'Y' },
            { A, 'A' }
        };

        /**
         * system equivalent with remapped symbol names:
         * Y -> YX
         * X -> AX
         */

        Assert.AreEqual("Y", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("YX", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("YXAX", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("YXAXAAX", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("YXAXAAXAAAX", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState.currentSymbols.DisposeImmediate();
    }
        /// <summary>
        /// Adds the specified JSON into the IConfigurationBuilder as if adding a real JSON file.
        /// </summary>
        /// <param name="configurationBuilder"></param>
        /// <param name="inMemoryJson">The JSON data to use in the configuration.</param>
        /// <returns></returns>
        public static IConfigurationBuilder AddInMemoryJson(this IConfigurationBuilder configurationBuilder, string inMemoryJson)
        {
            string temporaryFileName = "in_memory_json_" + _random.Next(-1, int.MaxValue).ToString("D16") + ".json";

            InMemoryFileInfo     fileInfo = new InMemoryFileInfo(temporaryFileName, Encoding.UTF8.GetBytes(inMemoryJson), DateTimeOffset.Now);
            InMemoryFileProvider @in      = new InMemoryFileProvider(fileInfo);

            return(configurationBuilder.AddJsonFile(@in, temporaryFileName, optional: false, reloadOnChange: false));
        }
        private InMemoryFileProvider SetUpFileProvider()
        {
            var fileProvider = new InMemoryFileProvider();

            fileProvider.Directory.AddFile("", new StringFileInfo("this file exists", "exists.txt"));
            fileProvider.Directory.AddFile("", new StringFileInfo("file contents", "foo.txt"));
            fileProvider.Directory.AddFile("", new StringFileInfo("{ \"another\":\"file\" }", "bar.json"));
            return(fileProvider);
        }
예제 #22
0
    public void LinksBuiltinLibraryAndExecutes()
    {
        var builtins = new BuiltinLibraries();

        builtins.Add(new DiffusionLibrary());

        var fileSystem = new InMemoryFileProvider(builtins);

        fileSystem.RegisterFileWithIdentifier("root.lsystem", @"
#axiom n(0.5, 0, 10)ST(3)
#iterations 10
#symbols naFTS

#include diffusion (Node->n) (Amount->a)

T(x) : x > 0 -> n(.5, 0, 10)FT(x - 1)
S -> a(3)S
");
        var linker      = new FileLinker(fileSystem);
        var linkedFiles = linker.LinkFiles("root.lsystem");

        using var system = linkedFiles.CompileSystem();
        LSystemState <float> currentState = new DefaultLSystemState(
            linkedFiles.GetAxiom(),
            (uint)UnityEngine.Random.Range(int.MinValue, int.MaxValue));

        var n = linkedFiles.GetSymbol("root.lsystem", 'n');
        var a = linkedFiles.GetSymbol("root.lsystem", 'a');
        var F = linkedFiles.GetSymbol("root.lsystem", 'F');
        var T = linkedFiles.GetSymbol("root.lsystem", 'T');
        var S = linkedFiles.GetSymbol("root.lsystem", 'S');

        var symbolStringMapping = new Dictionary <int, char>()
        {
            { n, 'n' },
            { a, 'a' },
            { F, 'F' },
            { T, 'T' },
            { S, 'S' },
        };

        Assert.AreEqual("n(0.5, 0, 10)ST(3)", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("n(0.5, 0, 10)a(3)Sn(0.5, 0, 10)FT(2)", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("n(0.5, 1.5, 10)aa(3)Sn(0.5, 1.5, 10)Fn(0.5, 0, 10)FT(1)", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("n(0.5, 3, 10)aa(3)Sn(0.5, 2.25, 10)Fn(0.5, 0.75, 10)Fn(0.5, 0, 10)FT(0)", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("n(0.5, 4.125, 10)aa(3)Sn(0.5, 3.375, 10)Fn(0.5, 1.125, 10)Fn(0.5, 0.375, 10)FT(0)", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("n(0.5, 5.25, 10)aa(3)Sn(0.5, 4.125, 10)Fn(0.5, 1.875, 10)Fn(0.5, 0.75, 10)FT(0)", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("n(0.5, 6.1875, 10)aa(3)Sn(0.5, 5.0625, 10)Fn(0.5, 2.4375, 10)Fn(0.5, 1.3125, 10)FT(0)", currentState.currentSymbols.Data.ToString(symbolStringMapping));

        currentState.currentSymbols.DisposeImmediate();
    }
예제 #23
0
        public override IFileProvider CreateFileProvider(string contentRootDir)
        {
            var inMemoryFiles = new InMemoryFileProvider(new Dictionary <string, string>
            {
                { "wwwroot/index.html", IndexHtml },
            }, contentRootDir);

            return(inMemoryFiles);
        }
예제 #24
0
    public void LinksBuiltinLibraryWithCustomParameterAndExecutes()
    {
        var builtins = new BuiltinLibraries();

        builtins.Add(new DiffusionLibrary());

        var fileSystem = new InMemoryFileProvider(builtins);

        fileSystem.RegisterFileWithIdentifier("root.lsystem", @"
#axiom n(0.25, 18, 20)Fn(0.25, 0, 20)Fn(0.25, 0, 20)
#iterations 10
#symbols naF

#define diffusionStepsPerStep 2
#include diffusion (Node->n) (Amount->a)

");
        var linker      = new FileLinker(fileSystem);
        var linkedFiles = linker.LinkFiles("root.lsystem");

        using var system = linkedFiles.CompileSystem();
        LSystemState <float> currentState = new DefaultLSystemState(
            linkedFiles.GetAxiom(),
            (uint)UnityEngine.Random.Range(int.MinValue, int.MaxValue));

        var n = linkedFiles.GetSymbol("root.lsystem", 'n');
        var a = linkedFiles.GetSymbol("root.lsystem", 'a');
        var F = linkedFiles.GetSymbol("root.lsystem", 'F');

        var symbolStringMapping = new Dictionary <int, char>()
        {
            { n, 'n' },
            { a, 'a' },
            { F, 'F' },
        };

        Assert.AreEqual("n(0.25, 18, 20)Fn(0.25, 0, 20)Fn(0.25, 0, 20)", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("n(0.25, 11.25, 20)Fn(0.25, 5.625, 20)Fn(0.25, 1.125, 20)", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("n(0.25, 8.859375, 20)Fn(0.25, 5.976563, 20)Fn(0.25, 3.164063, 20)", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("n(0.25, 7.602539, 20)Fn(0.25, 5.998535, 20)Fn(0.25, 4.398926, 20)", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("n(0.25, 6.901062, 20)Fn(0.25, 5.999908, 20)Fn(0.25, 5.09903, 20)", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("n(0.25, 6.506824, 20)Fn(0.25, 5.999994, 20)Fn(0.25, 5.493181, 20)", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("n(0.25, 6.285088, 20)Fn(0.25, 6, 20)Fn(0.25, 5.714913, 20)", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("n(0.25, 6.160362, 20)Fn(0.25, 6, 20)Fn(0.25, 5.839638, 20)", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("n(0.25, 6.090203, 20)Fn(0.25, 6, 20)Fn(0.25, 5.909797, 20)", currentState.currentSymbols.Data.ToString(symbolStringMapping));

        currentState.currentSymbols.DisposeImmediate();
    }
예제 #25
0
    public void CompilesWithImmaturityMarkers()
    {
        var fileSystem = new InMemoryFileProvider();

        fileSystem.RegisterFileWithIdentifier("root.lsystem", @"
#axiom Y(2)
#iterations 20
#symbols XY

#immature Y
Y(x) : x > 0 -> Y(x - 1)
Y(x) : x <= 0 -> X
");
        var linker      = new FileLinker(fileSystem);
        var linkedFiles = linker.LinkFiles("root.lsystem");

        using var system = linkedFiles.CompileSystem();
        LSystemState <float> currentState = new DefaultLSystemState(
            linkedFiles.GetAxiom(),
            (uint)UnityEngine.Random.Range(int.MinValue, int.MaxValue));

        var X = linkedFiles.GetSymbol("root.lsystem", 'X');
        var Y = linkedFiles.GetSymbol("root.lsystem", 'Y');

        var symbolStringMapping = new Dictionary <int, char>()
        {
            { X, 'X' },
            { Y, 'Y' }
        };

        /**
         * system equivalent with remapped symbol names:
         * Y -> YX
         * X -> AX
         */

        Assert.AreEqual("Y(2)", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        currentState = system.StepSystem(currentState);
        Assert.AreEqual("Y(1)", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        Assert.IsTrue(currentState.hasImmatureSymbols);

        currentState = system.StepSystem(currentState);
        Assert.AreEqual("Y(0)", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        Assert.IsTrue(currentState.hasImmatureSymbols);

        currentState = system.StepSystem(currentState);
        Assert.AreEqual("X", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        Assert.IsFalse(currentState.hasImmatureSymbols);

        currentState = system.StepSystem(currentState);
        Assert.AreEqual("X", currentState.currentSymbols.Data.ToString(symbolStringMapping));
        Assert.IsFalse(currentState.hasImmatureSymbols);

        currentState.currentSymbols.DisposeImmediate();
    }
예제 #26
0
        public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
        {
            Logger.Log(LogLevel.Info, "Service Starting.");

            string url = null;
            string dynamoDbConfigJson = null;

            var builder = new ConfigurationBuilder();

            builder.AddCommandLine(startupArguments);

            if (!this.StartupConfig.IsTest)
            {
                // No need to spend time checking dynamo db if in test mode
                dynamoDbConfigJson = DynamoDbConfigurationProviderFactory.Create().GetJson();

                if (!string.IsNullOrWhiteSpace(dynamoDbConfigJson))
                {
                    var dynamoAppSettingsFileName = "appsettings.dynamodb.json";
                    var provider = new InMemoryFileProvider();
                    provider.Directory.AddFile("/", new StringFileInfo(dynamoDbConfigJson, dynamoAppSettingsFileName));
                    provider.EnsureFile($"/{dynamoAppSettingsFileName}");

                    builder.AddJsonFile(provider, $"/{dynamoAppSettingsFileName}", false, false);
                }
            }

            var config = builder.Build();

            url = config.GetValue <string>("SurveillanceApiUrl");

            if (string.IsNullOrWhiteSpace(url))
            {
                url = "https://localhost:8888";
            }

            this._webHost = CreateWebHostBuilder(startupArguments, dynamoDbConfigJson, url, this.StartupConfig).Build();

            // Make sure the windows service is stopped if the
            // ASP.NET Core stack stops for any reason
            this._webHost.Services.GetRequiredService <IHostApplicationLifetime>().ApplicationStopped.Register(
                () =>
            {
                if (this._stopRequestedByWindows == false)
                {
                    serviceStoppedCallback();
                }
            });

            Logger.Log(LogLevel.Info, "WebHost Starting.");
            this._webHost.Start();
            Logger.Log(LogLevel.Info, "WebHost Started.");

            Logger.Log(LogLevel.Info, "Service Started.");
        }
예제 #27
0
        public static void Main(string[] args)
        {
            var jsonString         = LoadAppsettingValuesFromSomewhere();
            var memoryFileProvider = new InMemoryFileProvider(jsonString);
            var configuration      = new ConfigurationBuilder()
                                     .AddJsonFile(memoryFileProvider, "appsettingsss.json", false, false).Build();

            string keyFromappsettings = configuration["MyKey"];

            CreateHostBuilder(args).Build().Run();
        }
    public static IConfiguration GetSettingsFromReleaseFile()
    {
        var json = Utils.LoadSettingsFromFile("Release");
        var memoryFileProvider = new InMemoryFileProvider(json);

        var config = new ConfigurationBuilder()
                     .AddJsonFile(memoryFileProvider, "appsettings.json", false, false)
                     .Build();

        return(config);
    }
        public void GetFileInfo_ReturnsNotFoundFileInfo_IfNoDirectoryItems()
        {
            // Arrange
            var provider = new InMemoryFileProvider();

            // Act
            var fileInfo = provider.GetFileInfo("DoesNotExist.txt");

            // Assert
            Assert.NotNull(fileInfo);
            Assert.False(fileInfo.Exists);
        }
예제 #30
0
        protected override void InitializeCore()
        {
            base.InitializeCore();

            // Setup our own effect compiler
            using var fileProvider = new InMemoryFileProvider(EffectSystem.FileProvider);
            fileProvider.Register("shaders/WebRendererShader.sdsl", GetShaderSource());
            using var compiler = new EffectCompiler(fileProvider);
            compiler.SourceDirectories.Add("shaders");

            // Switch effect compiler
            var currentCompiler = EffectSystem.Compiler;

            EffectSystem.Compiler = compiler;
            try
            {
                shader = ToLoadAndUnload(new ImageEffectShader("WebRendererShader"));
                // The incoming texture uses premultiplied alpha
                shader.BlendState = BlendStates.AlphaBlend;
                shader.EffectInstance.UpdateEffect(GraphicsDevice);
            }
            finally
            {
                EffectSystem.Compiler = currentCompiler;
            }

            string GetShaderSource()
            {
                return(@"
shader WebRendererShader : ImageEffectShader
{
stage override float4 Shading()
{
    float2 samplePosition = float2(streams.TexCoord.x, 1 - streams.TexCoord.y);
    float4 color = Texture0.Sample(PointSampler, samplePosition);

    // The render pipeline expects a linear color space
    return float4(ToLinear(color.r), ToLinear(color.g), ToLinear(color.b), color.a);
}

// There're faster approximations, see http://chilliant.blogspot.com/2012/08/srgb-approximations-for-hlsl.html
float ToLinear(float C_srgb)
{
    if (C_srgb <= 0.04045)
        return C_srgb / 12.92;
    else
        return pow((C_srgb + 0.055) / 1.055, 2.4);
}
};
");
            }
        }