Example #1
0
        public async Task TestEmbedded_RuntimeFrameworkVersionMatcher()
        {
            var paths = CopyServer();

            using (var embedded = new EmbeddedServer())
            {
                var options = new ServerOptions
                {
                    ServerDirectory = paths.ServerDirectory,
                    DataDirectory   = paths.DataDirectory,
                };

                var frameworkVersion = new RuntimeFrameworkVersionMatcher.RuntimeFrameworkVersion(options.FrameworkVersion)
                {
                    Patch = null
                };

                options.FrameworkVersion = frameworkVersion.ToString();

                embedded.StartServer(options);

                var pid1 = await embedded.GetServerProcessIdAsync();

                Assert.True(pid1 > 0);
            }
        }
Example #2
0
        public async Task SmugglerImportStreamShouldThrowTimeout()
        {
            var paths = CopyServer();

            using (var embedded = new EmbeddedServer())
            {
                embedded.StartServer(new ServerOptions
                {
                    ServerDirectory = paths.ServerDirectory,
                    DataDirectory   = paths.DataDirectory,
                });

                const string databaseName = "test";
                var          dummyDump    = CreateDummyDump(1);

                using (var ctx = JsonOperationContext.ShortTermSingleUse())
                    using (var bjro = ctx.ReadObject(dummyDump, "dump"))
                        using (var ms = new MemoryStream())
                            using (var zipStream = new GZipStream(ms, CompressionMode.Compress))
                            {
                                await bjro.WriteJsonToAsync(zipStream);

                                zipStream.Flush();
                                ms.Position = 0;

                                using (var store = embedded.GetDocumentStore(new DatabaseOptions(databaseName)))
                                {
                                    var testingStuff = store.Smuggler.ForTestingPurposesOnly();
                                    using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(1)))
                                        using (testingStuff.CallBeforeSerializeToStreamAsync(() =>
                                        {
                                            Thread.Sleep(2000);
                                        }))
                                        {
                                            Exception e = null;
                                            try
                                            {
                                                var operation = await store.Smuggler.ForDatabase(databaseName)
                                                                .ImportAsync(
                                                    new DatabaseSmugglerImportOptions
                                                {
                                                    OperateOnTypes = DatabaseItemType.Documents | DatabaseItemType.Identities | DatabaseItemType.CompareExchange
                                                }, ms, cts.Token);


                                                await operation.WaitForCompletionAsync();
                                            }
                                            catch (Exception exception)
                                            {
                                                e = exception;
                                            }

                                            Assert.NotNull(e);
                                            AssertException(e);
                                        }
                                }
                            }
            }
        }
        public void ServerBuilderShouldResolveUrl()
        {
            var serverBuilder = EmbeddedServer.NewServer(9999)
                                .WithVirtualDirectory("/", solutionFiles.ResolvePath("Tests\\ExampleApps\\RootApp"));

            Assert.That(serverBuilder.ResolveUrl("Default.aspx"),
                        Is.EqualTo("http://localhost:9999/Default.aspx"));
        }
Example #4
0
        public void TestEmbedded()
        {
            var paths = CopyServer();

            using (var embedded = new EmbeddedServer())
            {
                embedded.StartServer(new ServerOptions
                {
                    ServerDirectory = paths.ServerDirectory,
                    DataDirectory   = paths.DataDirectory,
                });

                using (var store = embedded.GetDocumentStore(new DatabaseOptions("Test")
                {
                    Conventions = new DocumentConventions
                    {
                        SaveEnumsAsIntegers = true
                    }
                }))
                {
                    Assert.True(store.Conventions.SaveEnumsAsIntegers);
                    Assert.True(store.GetRequestExecutor().Conventions.SaveEnumsAsIntegers);

                    using (var session = store.OpenSession())
                    {
                        session.Store(new Person
                        {
                            Name = "John"
                        }, "people/1");

                        session.SaveChanges();
                    }
                }
            }

            using (var embedded = new EmbeddedServer())
            {
                embedded.StartServer(new ServerOptions
                {
                    ServerDirectory = paths.ServerDirectory,
                    DataDirectory   = paths.DataDirectory,
                });

                using (var store = embedded.GetDocumentStore("Test"))
                {
                    Assert.False(store.Conventions.SaveEnumsAsIntegers);
                    Assert.False(store.GetRequestExecutor().Conventions.SaveEnumsAsIntegers);

                    using (var session = store.OpenSession())
                    {
                        var person = session.Load <Person>("people/1");

                        Assert.NotNull(person);
                        Assert.Equal("John", person.Name);
                    }
                }
            }
        }
Example #5
0
        public static bool IsRunning(this EmbeddedServer instance)
        {
            // HACK: check RavenDB running state using private field to avoid multiple starts
            // https://github.com/ravendb/ravendb/blob/release/v4.2/src/Raven.Embedded/EmbeddedServer.cs#L45-L46
            const BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance;
            var result = instance.GetType().GetField("_serverTask", bindingFlags)?.GetValue(instance);

            return(result != null);
        }
        public void LoadRootAppAtPath()
        {
            var server = EmbeddedServer.NewServer()
                         .WithVirtualDirectory("/Sub", solutionFiles.ResolvePath("Tests/ExampleApps/RootApp"))
                         .Start();

            Assert.That(httpClient.Get(server.ResolveUrl("Sub/Default.aspx")),
                        Does.Contain("Hello, I'm RootApp"));
        }
        public void LoadStaticsForSubRootApp()
        {
            var server = EmbeddedServer.NewServer()
                         .WithVirtualDirectory("/", solutionFiles.ResolvePath("Tests/ExampleApps/RootApp"))
                         .WithVirtualDirectory("/Sub", solutionFiles.ResolvePath("Tests/ExampleApps/SubRootApp"))
                         .Start();

            Assert.That(httpClient.Get(server.ResolveUrl("Sub/static/file.js")),
                        Does.Contain("function"));
        }
Example #8
0
        public async Task TcpCompressionOnSubscriptionShouldNotWorkInNetStandard2()
        {
            var file = Path.GetTempFileName();

            try
            {
                var paths = CopyServer();
                using (var embedded = new EmbeddedServer())
                {
                    var options = new ServerOptions
                    {
                        ServerDirectory = paths.ServerDirectory,
                        DataDirectory   = paths.DataDirectory
                    };
                    embedded.StartServer(options);

                    using (var store1 = embedded.GetDocumentStore(new DatabaseOptions("Test-1")))
                        using (var store2 = embedded.GetDocumentStore(new DatabaseOptions("Test-2")))
                        {
                            store1.Subscriptions.Create(new SubscriptionCreationOptions <Person>()
                            {
                                Name = "sub1"
                            });
                            store1.Subscriptions.Create(new SubscriptionCreationOptions <Person>()
                            {
                                Name = "sub2"
                            });
                            store1.Subscriptions.Create(new SubscriptionCreationOptions <Person>());

                            var subscriptionStataList = store1.Subscriptions.GetSubscriptions(0, 10);

                            Assert.Equal(3, subscriptionStataList.Count);

                            var operation = await store1.Smuggler.ExportAsync(new DatabaseSmugglerExportOptions(), file);

                            await operation.WaitForCompletionAsync(TimeSpan.FromMinutes(1));

                            operation = await store2.Smuggler.ImportAsync(new DatabaseSmugglerImportOptions(), file);

                            await operation.WaitForCompletionAsync(TimeSpan.FromMinutes(1));

                            subscriptionStataList = store2.Subscriptions.GetSubscriptions(0, 10, store2.Database);

                            Assert.Equal(3, subscriptionStataList.Count);
                            Assert.True(subscriptionStataList.Any(x => x.SubscriptionName.Equals("sub1")));
                            Assert.True(subscriptionStataList.Any(x => x.SubscriptionName.Equals("sub2")));
                        }
                }
            }
            finally
            {
                File.Delete(file);
            }
        }
Example #9
0
        public async Task TestEmbeddedRestart()
        {
            var paths = CopyServer();

            using (var embedded = new EmbeddedServer())
            {
                embedded.StartServer(new ServerOptions
                {
                    ServerDirectory = paths.ServerDirectory,
                    DataDirectory   = paths.DataDirectory,
                });

                var pid1 = await embedded.GetServerProcessIdAsync();

                Assert.True(pid1 > 0);

                var mre = new ManualResetEventSlim();

                embedded.ServerProcessExited += (s, args) => mre.Set();

                using (var process = Process.GetProcessById(pid1))
                {
                    try
                    {
                        process.Kill();
                    }
                    catch
                    {
                        // ignored
                    }
                }

                Assert.True(mre.Wait(TimeSpan.FromSeconds(15)));

                await embedded.RestartServerAsync();

                var pid2 = await embedded.GetServerProcessIdAsync();

                Assert.True(pid2 > 0);
                Assert.NotEqual(pid1, pid2);

                mre.Reset();
                await embedded.RestartServerAsync();

                Assert.True(mre.Wait(TimeSpan.FromSeconds(15)));

                var pid3 = await embedded.GetServerProcessIdAsync();

                Assert.True(pid3 > 0);
                Assert.NotEqual(pid2, pid3);
            }
        }
Example #10
0
        public void Start()
        {
            Console.WriteLine("Starting");

            try
            {
                this.server = serverBuilder.Start();
                Console.WriteLine("Started");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        public void CollectConsoleOutputFromTheApp()
        {
            var output     = new StringWriter();
            var serverPath = solutionFiles.ResolvePath("Tests/ExampleApps/OutputtingApp");

            var server = EmbeddedServer.NewServer()
                         .WithVirtualDirectory("/", serverPath)
                         .WithOutputCollectionTo(output)
                         .Start();

            Assert.That(httpClient.Get(server.ResolveUrl("Default.aspx")),
                        Does.Contain("Hello, I'm OutputtingApp"));

            Assert.That(output.ToString().Trim(), Is.EqualTo("Hello!"));
        }
        public void LoadAppWithConfigurationOverwrite()
        {
            var serverPath         = solutionFiles.ResolvePath("Tests/ExampleApps/ConfigurableApp");
            var givenConfigRewrite = new ConfigReplacementsBuilder()
                                     .ForPathWithValues("appSettings", new
            {
                applicationName = "ConfiguredApp!"
            })
                                     .Build();

            var server = EmbeddedServer.NewServer()
                         .WithVirtualDirectory("/", new DeployedApp(serverPath, givenConfigRewrite))
                         .Start();

            Assert.That(httpClient.Get(server.ResolveUrl("Default.aspx")),
                        Does.Contain("Hello, I'm ConfiguredApp!"));
        }
Example #13
0
        public void TestEmbedded()
        {
            var paths = CopyServer();

            using (var embedded = new EmbeddedServer())
            {
                embedded.StartServer(new ServerOptions
                {
                    ServerDirectory = paths.ServerDirectory,
                    DataDirectory   = paths.DataDirectory,
                });

                using (var store = embedded.GetDocumentStore("Test"))
                {
                    using (var session = store.OpenSession())
                    {
                        session.Store(new Person
                        {
                            Name = "John"
                        }, "people/1");

                        session.SaveChanges();
                    }
                }
            }

            using (var embedded = new EmbeddedServer())
            {
                embedded.StartServer(new ServerOptions
                {
                    ServerDirectory = paths.ServerDirectory,
                    DataDirectory   = paths.DataDirectory,
                });

                using (var store = embedded.GetDocumentStore("Test"))
                {
                    using (var session = store.OpenSession())
                    {
                        var person = session.Load <Person>("people/1");

                        Assert.NotNull(person);
                        Assert.Equal("John", person.Name);
                    }
                }
            }
        }
Example #14
0
    static Tests()
    {
        server = EmbeddedServer.Instance;
        var path = Path.Combine(Path.GetTempPath(), "RavenTestData");

        if (Directory.Exists(path))
        {
            Directory.Delete(path, true);
        }

        Directory.CreateDirectory(path);
        server.StartServer(
            new()
        {
            DataDirectory = path
        });
    }
Example #15
0
        public void Can_Use_Custom_Analyzer()
        {
            var paths = CopyServer();

            CopyCustomAnalyzer(paths.ServerDirectory);

            using (var embedded = new EmbeddedServer())
            {
                embedded.StartServer(new ServerOptions
                {
                    ServerDirectory = paths.ServerDirectory,
                    DataDirectory   = paths.DataDirectory,
                });

                using (var store = embedded.GetDocumentStore("DatabaseWithCustomAnalyzers"))
                {
                    new Index_With_Custom_Analyzer().Execute(store);
                }
            }
        }
        public void StartAndStop()
        {
            string pageUrl;

            HostRemovedEventArgs removedArgs = null;

            using (var server = EmbeddedServer.NewServer(1)
                                .WithVirtualDirectory("/", solutionFiles.ResolvePath("Tests/CassiniDev4.Tests.Web"))
                                .Start())
            {
                HostCreatedEventArgs receivedArgs = null;

                server.HostCreated += (s, e) =>
                {
                    receivedArgs = e;
                };

                server.HostRemoved += (s, e) =>
                {
                    removedArgs = e;
                };

                pageUrl = server.ResolveUrl("Default.aspx");

                Assert.That(httpClient.Get(pageUrl), Does.Contain("Welcome to ASP.NET!"));
                Assert.That(receivedArgs, Is.Not.Null);
                Assert.That(receivedArgs.VirtualPath, Is.EqualTo("/"));
            }

            Assert.That(removedArgs, Is.Not.Null);
            Assert.That(removedArgs.VirtualPath, Is.EqualTo("/"));

            try
            {
                httpClient.Get(pageUrl);

                Assert.Fail("Should not be a success");
            } catch (SimpleHttpClient.UnableToConnect e)
            {
            }
        }
        public void SetupAppWithStart()
        {
            int setupCalled = 0;

            using (var server = EmbeddedServer.NewServer()
                                .WithVirtualDirectory("/", solutionFiles.ResolvePath("Tests\\ExampleApps\\RootApp"))
                                .WithSetup((serverSetUp) =>
            {
                setupCalled++;

                Assert.That(httpClient.Get(serverSetUp.ResolveUrl("Default.aspx")),
                            Does.Contain("Hello, I'm RootApp"));
            })
                                .Start())
            {
                Assert.That(httpClient.Get(server.ResolveUrl("Default.aspx")),
                            Does.Contain("Hello, I'm RootApp"));

                Assert.That(setupCalled, Is.EqualTo(1));
            }
        }
        public void GenerateACrossDomainProxyToInjectClass()
        {
            var serverPath   = solutionFiles.ResolvePath("Tests/ExampleApps/ConfigurableApp");
            var serviceClass = "A.B.C.SomeClass";

            var spanishGreeter = new SpanishGreeter();

            var givenConfigRewrite = new ConfigReplacementsBuilder()
                                     .ForPathWithValues("appSettings", new
            {
                serviceClass = serviceClass
            })
                                     .Build();

            var server = EmbeddedServer.NewServer()
                         .WithVirtualDirectory("/", new DeployedApp(serverPath, givenConfigRewrite)
                                               .WithSyntheticTypeFor <IGreeterService>(serviceClass, spanishGreeter))
                         .Start();

            Assert.That(httpClient.Get(server.ResolveUrl("Default.aspx?Name=Mantas")),
                        Does.Contain("Mantas: Hola, Mantas"));
        }
Example #19
0
        private static IEnumerable <IEnvironmentLifecycle> StartServerWithVirtualMappings(ProgramOptions options)
        {
            if (options.VirtualPathMappings.Count > 0)
            {
                var serverPrototype = EmbeddedServer.NewServer(options.Port);

                foreach (var mapping in options.VirtualPathMappings)
                {
                    Console.WriteLine("Adding {0} -> {1}", mapping.VirtualPath, mapping.PhysicalPath);
                    serverPrototype = serverPrototype.WithVirtualDirectory(mapping.VirtualPath, mapping.PhysicalPath);
                }

                var server = serverPrototype.Start();

                Console.WriteLine("Server listening at {0}", options.Port);

                return(new List <IEnvironmentLifecycle>()
                {
                    new EmbeddedServerLifecycle(server)
                });
            }

            return(new List <IEnvironmentLifecycle>());
        }
Example #20
0
        /// <summary>
        /// Create a schedule
        /// </summary>
        /// <param name="scheduleLocation"></param>
        public Schedule(string scheduleLocation, ref CacheManager cacheManager, ref ClientInfo clientInfoForm)
        {
            Trace.WriteLine(string.Format("XMDS Location: {0}", ApplicationSettings.Default.XiboClient_xmds_xmds));

            // Get the key for this display
            _hardwareKey = new HardwareKey();

            // Save the schedule location
            _scheduleLocation = scheduleLocation;

            // Create a new collection for the layouts in the schedule
            _layoutSchedule = new Collection <ScheduleItem>();

            // Set cachemanager
            _cacheManager = cacheManager;

            // Set client info form
            _clientInfoForm = clientInfoForm;

            // Create a Register Agent
            _registerAgent = new RegisterAgent();
            _registerAgent.OnXmrReconfigure += _registerAgent_OnXmrReconfigure;
            _registerAgentThread             = new Thread(new ThreadStart(_registerAgent.Run));
            _registerAgentThread.Name        = "RegisterAgentThread";

            // Create a schedule manager
            _scheduleManager = new ScheduleManager(_cacheManager, scheduleLocation);
            _scheduleManager.OnNewScheduleAvailable         += new ScheduleManager.OnNewScheduleAvailableDelegate(_scheduleManager_OnNewScheduleAvailable);
            _scheduleManager.OnRefreshSchedule              += new ScheduleManager.OnRefreshScheduleDelegate(_scheduleManager_OnRefreshSchedule);
            _scheduleManager.OnScheduleManagerCheckComplete += _scheduleManager_OnScheduleManagerCheckComplete;
            _scheduleManager.ClientInfoForm = _clientInfoForm;

            // Create a schedule manager thread
            _scheduleManagerThread      = new Thread(new ThreadStart(_scheduleManager.Run));
            _scheduleManagerThread.Name = "ScheduleManagerThread";

            // Create a RequiredFilesAgent
            _scheduleAndRfAgent = new ScheduleAndFilesAgent();
            _scheduleAndRfAgent.CurrentCacheManager    = cacheManager;
            _scheduleAndRfAgent.CurrentScheduleManager = _scheduleManager;
            _scheduleAndRfAgent.ScheduleLocation       = scheduleLocation;
            _scheduleAndRfAgent.HardwareKey            = _hardwareKey.Key;
            _scheduleAndRfAgent.OnFullyProvisioned    += _requiredFilesAgent_OnFullyProvisioned;
            _scheduleAndRfAgent.ClientInfoForm         = _clientInfoForm;
            _scheduleAndRfAgent.OnComplete            += new ScheduleAndFilesAgent.OnCompleteDelegate(LayoutFileModified);

            // Create a thread for the RequiredFiles Agent to run in - but dont start it up yet.
            _scheduleAndRfAgentThread      = new Thread(new ThreadStart(_scheduleAndRfAgent.Run));
            _scheduleAndRfAgentThread.Name = "RequiredFilesAgentThread";

            // Library Agent
            _libraryAgent = new LibraryAgent();
            _libraryAgent.CurrentCacheManager = _cacheManager;

            // Create a thread for the Library Agent to run in - but dont start it up yet.
            _libraryAgentThread      = new Thread(new ThreadStart(_libraryAgent.Run));
            _libraryAgentThread.Name = "LibraryAgent";

            // Log Agent
            _logAgent            = new LogAgent();
            _logAgentThread      = new Thread(new ThreadStart(_logAgent.Run));
            _logAgentThread.Name = "LogAgent";

            // XMR Subscriber
            _xmrSubscriber                = new XmrSubscriber();
            _xmrSubscriber.HardwareKey    = _hardwareKey;
            _xmrSubscriber.ClientInfoForm = _clientInfoForm;
            _xmrSubscriber.OnAction      += _xmrSubscriber_OnAction;

            // Thread start
            _xmrSubscriberThread      = new Thread(new ThreadStart(_xmrSubscriber.Run));
            _xmrSubscriberThread.Name = "XmrSubscriber";

            // Embedded Server
            _server = new EmbeddedServer();
            _server.ClientInfoForm  = _clientInfoForm;
            _server.OnServerClosed += _server_OnServerClosed;
            _serverThread           = new Thread(new ThreadStart(_server.Run));
            _serverThread.Name      = "EmbeddedServer";
        }
 public EmbeddedServerLifecycle(EmbeddedServer server)
 {
     this.server = server;
 }