Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            Console.WriteLine("Press any key to start...");
            Console.ReadKey();
            using (var db = new Database("db")) {
                var config = new ReplicatorConfiguration(db, new URLEndpoint(new Uri("ws://localhost:5984/db")))
                {
                    Continuous = true
                };
                var repl = new Replicator(config);
                repl.Start();

                var key = new ConsoleKeyInfo();
                var r   = new Random();
                do
                {
                    Console.WriteLine("Press A to add document, Press E to end");
                    key = Console.ReadKey();
                    if (key.Key == ConsoleKey.A)
                    {
                        using (var doc = new MutableDocument()) {
                            doc.SetInt("rand", r.Next());
                            db.Save(doc);
                        }
                    }
                } while (key.Key != ConsoleKey.E);

                repl.Stop();
                while (repl.Status.Activity != ReplicatorActivityLevel.Stopped)
                {
                    Console.WriteLine("Waiting for replicator to stop...");
                    Thread.Sleep(2000);
                }
            }
        }
        private void RunReplication(ReplicatorConfiguration config, int expectedErrCode, C4ErrorDomain expectedErrDomain)
        {
            Misc.SafeSwap(ref _repl, new Replicator(config));
            _waitAssert = new WaitAssert();
            var token = _repl.AddChangeListener((sender, args) =>
            {
                _waitAssert.RunConditionalAssert(() =>
                {
                    VerifyChange(args, expectedErrCode, expectedErrDomain);
                    if (config.Continuous && args.Status.Activity == ReplicatorActivityLevel.Idle &&
                        args.Status.Progress.Completed == args.Status.Progress.Total)
                    {
                        ((Replicator)sender).Stop();
                    }

                    return(args.Status.Activity == ReplicatorActivityLevel.Stopped);
                });
            });

            _repl.Start();
            try {
                _waitAssert.WaitForResult(TimeSpan.FromSeconds(10));
            } catch {
                _repl.Stop();
                throw;
            } finally {
                _repl.RemoveChangeListener(token);
            }
        }
Ejemplo n.º 3
0
 public void StopReplication()
 {
     if (_replicator != null)
     {
         _replicator.RemoveChangeListener(_replicatorListenerToken);
         _replicator.Stop();
     }
 }
Ejemplo n.º 4
0
        private void StopReplicator()
        {
            //tag::StopReplication[]
            _repl?.Stop();
            //end::StopReplication[]

            IsStarted = false;
        }
Ejemplo n.º 5
0
        public void Run()
        {
            // Create docs
            Console.WriteLine($"Saving: {_maxDocs} docs");
            _db.InBatch(() =>
            {
                for (int i = 0; i < _maxDocs; i++)
                {
                    var doc             = new Document($"doc_{i}");
                    doc["random"].Value = Guid.NewGuid().ToString();
                    _db.Save(doc);
                }
            });

            // Update docs
            var stopWatch = new Stopwatch();

            stopWatch.Start();
            var r = new Random();

            while (true)
            {
                double totalMin = stopWatch.Elapsed.TotalMinutes;


                if (totalMin > _scenarioRuntimeMinutes)
                {
                    // We have reached the total time we would like to run
                    // for. Exit
                    break;
                }

                // Update a random doc
                int      rInt = r.Next(0, _maxDocs);
                Document doc  = _db.GetDocument($"doc_{rInt}");

                Console.WriteLine($"Updating doc: {doc.Id}");

                doc["random"].Value = Guid.NewGuid().ToString();
                _db.Save(doc);

                // Sleep between each update
                Task.Delay(100).Wait();
            }

            // Delete docs
            Console.WriteLine($"Deleting: {_maxDocs} docs");
            for (int i = 0; i < _maxDocs; i++)
            {
                var doc = _db.GetDocument($"doc_{i}");
                _db.Delete(doc);
            }

            stopWatch.Stop();
            _replicator.Stop();
            _db.Delete();
        }
 /// <inheritdoc />
 public void Dispose()
 {
     Ended?.Invoke(this, null);
     Database?.Dispose();
     Replicator?.Stop();
     // Uncomment after DB019 (https://github.com/couchbase/couchbase-lite-net/issues/908)
     //_replicator?.Dispose();
     HttpClient.Dispose();
 }
Ejemplo n.º 7
0
        private void Restart()
        {
            try
            {
                _replicator.RemoveChangeListener(_token);
                _replicator.Stop();
                _replicator = null;
                _replicator.Dispose();
            }
            catch (Exception)
            { }

            Connect();
        }
        private void RunReplicatorServerCert(Replicator repl, bool hasIdle, X509Certificate2 serverCert)
        {
            using (var waitIdle = new ManualResetEventSlim())
                using (var waitStopped = new ManualResetEventSlim()) {
                    repl.AddChangeListener((sender, args) =>
                    {
                        var level        = args.Status.Activity;
                        var correctError = hasIdle ? args.Status.Error == null : args.Status.Error != null;
                        if (level == ReplicatorActivityLevel.Idle)
                        {
                            waitIdle.Set();
                        }
                        else if (level == ReplicatorActivityLevel.Stopped && correctError)
                        {
                            waitStopped.Set();
                        }
                    });

                    repl.ServerCertificate.Should().BeNull();
                    repl.Start();

                    if (hasIdle)
                    {
                        waitIdle.Wait(_timeout).Should().BeTrue();
                        if (serverCert == null)
                        {
                            repl.ServerCertificate.Should().BeNull();
                        }
                        else
                        {
                            serverCert.Thumbprint.Should().Be(repl.ServerCertificate?.Thumbprint);
                        }

                        repl.Stop();
                    }

                    waitStopped.Wait(_timeout).Should().BeTrue();
                    if (serverCert == null)
                    {
                        repl.ServerCertificate.Should().BeNull();
                    }
                    else
                    {
                        serverCert.Thumbprint.Should().Be(repl.ServerCertificate?.Thumbprint);
                    }
                }
        }
Ejemplo n.º 9
0
        private void Restart(ReplicatorStatusMessage obj)
        {
            try
            {
                _replicator.RemoveChangeListener(_token);
                _replicator.Stop();
                _replicator.Dispose();
                _replicator = null;

                Connect();
            }
            catch (Exception e)
            {
#if DEBUG
#endif
            }
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            // This only needs to be done once for whatever platform the executable is running
            // (UWP, iOS, Android, or desktop)
            //Couchbase.Lite.Support.NetDesktop.Activate(); => DEPRECATED

            GettingStarted();
            //CreateNewDatabase();
            //CreateDocument();
            //UpdateDocument();
            //UseTypedAccessors();
            //DoBatchOperation();
            //UseBlob();
            //SelectMeta();

            //LoadPrebuilt();
            //CreateIndex();
            //SelectWhere();
            //UseCollectionContains();
            //SelectLike();
            //SelectWildcardLike();
            //SelectWildcardCharacterLike();
            //SelectRegex();
            //SelectJoin();
            //GroupBy();
            //OrderBy();

            //CreateFullTextIndex();
            //FullTextSearch();
            //StartReplication();
            //SetupReplicatorListener();

            _Replicator.Stop();

            while (_Replicator.Status.Activity != ReplicatorActivityLevel.Stopped)
            {
                // Database cannot close until replicators are stopped
                Console.WriteLine($"Waiting for replicator to stop (currently {_Replicator.Status.Activity})...");
                Thread.Sleep(200);
            }

            _Database.Close();

            Console.ReadLine();
        }
Ejemplo n.º 11
0
        private static void DatabaseReplica()
        {
            var db = _Database;

            using (var database2 = new Database("backup")) {
                // EE feature: This code will not compile on the community edition
                // # tag::database-replica[]
                var targetDatabase = new DatabaseEndpoint(database2);
                var config         = new ReplicatorConfiguration(db, targetDatabase)
                {
                    ReplicatorType = ReplicatorType.Push
                };

                var replicator = new Replicator(config);
                replicator.Start();
                // # end::database-replica[]

                _Replicator?.Stop();
                _Replicator = replicator;
            }
        }
Ejemplo n.º 12
0
    void FixedUpdate()
    {
        // NOTE: This quitting process is a first draft and has not been tested yet!
        // Please make sure you test your own process before using in production.
        if (quitting)
        {
            if (replicator != null && replicator.Status.Activity != ReplicatorActivityLevel.Stopped)
            {
                try {
                    replicator.Stop();
                } catch (Exception) {}
            }
            else
            {
                if (replicator != null)
                {
                    replicator.Dispose();
                }

                try {
                    database.GetDocument("meta");
                    database.Close();
                    database.Dispose();
                } catch (ObjectDisposedException) {
                    allDisposed = true;
                    Application.Quit();
                }
            }
        }
        else if (!syncing)
        {
            if (doneSyncing)
            {
                statusLabel.text += $"\n- Done syncing: {replicator.Status.Activity}";
                doneSyncing       = false;
            }
            // Other updates
        }
    }
Ejemplo n.º 13
0
        public async Task TestReplicatorStopWhenClosed()
        {
            var config = CreateConfig(true, true, true);

            using (var repl = new Replicator(config)) {
                repl.Start();
                while (repl.Status.Activity != ReplicatorActivityLevel.Idle)
                {
                    WriteLine($"Replication status still {repl.Status.Activity}, waiting for idle...");
                    await Task.Delay(500);
                }

                this.Invoking(x => ReopenDB())
                .ShouldThrow <InvalidOperationException>(
                    "because the database cannot be closed while replication is running");

                repl.Stop();
                while (repl.Status.Activity != ReplicatorActivityLevel.Stopped)
                {
                    WriteLine($"Replication status still {repl.Status.Activity}, waiting for stopped...");
                    await Task.Delay(500);
                }
            }
        }
Ejemplo n.º 14
0
        private void RunTwoStepContinuous(ReplicatorType type, string uid)
        {
            var listener = new MessageEndpointListener(new MessageEndpointListenerConfiguration(_otherDB, ProtocolType.ByteStream));
            var server   = new MockServerConnection(listener, ProtocolType.ByteStream);
            var config   = new ReplicatorConfiguration(Db,
                                                       new MessageEndpoint(uid, server, ProtocolType.ByteStream, new MockConnectionFactory(null)))
            {
                ReplicatorType = type,
                Continuous     = true
            };
            var replicator = new Replicator(config);

            replicator.Start();

            Database firstSource  = null;
            Database secondSource = null;
            Database firstTarget  = null;
            Database secondTarget = null;

            if (type == ReplicatorType.Push)
            {
                firstSource  = Db;
                secondSource = Db;
                firstTarget  = _otherDB;
                secondTarget = _otherDB;
            }
            else if (type == ReplicatorType.Pull)
            {
                firstSource  = _otherDB;
                secondSource = _otherDB;
                firstTarget  = Db;
                secondTarget = Db;
            }
            else
            {
                firstSource  = Db;
                secondSource = _otherDB;
                firstTarget  = _otherDB;
                secondTarget = Db;
            }

            using (var mdoc = new MutableDocument("livesindb")) {
                mdoc.SetString("name", "db");
                mdoc.SetInt("version", 1);
                firstSource.Save(mdoc);
            }

            var count = 0;

            while (replicator.Status.Progress.Completed == 0 ||
                   replicator.Status.Activity != ReplicatorActivityLevel.Idle)
            {
                Thread.Sleep(500);
                count++;
                count.Should().BeLessThan(10, "because otherwise the replicator did not advance");
            }

            var previousCompleted = replicator.Status.Progress.Completed;

            firstTarget.Count.Should().Be(1);

            using (var savedDoc = secondSource.GetDocument("livesindb"))
                using (var mdoc = savedDoc.ToMutable()) {
                    mdoc.SetInt("version", 2);
                    secondSource.Save(mdoc);
                }

            count = 0;
            while (replicator.Status.Progress.Completed == previousCompleted ||
                   replicator.Status.Activity != ReplicatorActivityLevel.Idle)
            {
                Thread.Sleep(500);
                count++;
                count.Should().BeLessThan(10, "because otherwise the replicator did not advance");
            }

            using (var savedDoc = secondTarget.GetDocument("livesindb")) {
                savedDoc.GetInt("version").Should().Be(2);
            }

            replicator.Stop();
            while (replicator.Status.Activity != ReplicatorActivityLevel.Stopped)
            {
                Thread.Sleep(100);
            }

            replicator.Dispose();
        }
Ejemplo n.º 15
0
        static int Main(string[] args)
        {
            try
            {
                if (args.Length != 3)
                {
                    Console.WriteLine("Usage : SyncMonitor [userName] [password] [Url sync Gateway]");
                    return(1);
                }
                Couchbase.Lite.Support.NetDesktop.Activate();

                Server serverInfo = new Server();
                serverInfo.Login     = args[0];
                serverInfo.Password  = args[1];
                serverInfo.UrlServer = args[2];

                IDataBaseGetter dataBaseGetter = new DataBaseGetter();

                if (dataBaseGetter == null)
                {
                    Console.WriteLine("Error when to create the local database");
                    return(2);
                }


                IReplicatorGetter replicatorGetter = new ReplicatorGetter(dataBaseGetter, serverInfo);
                Replicator        replicator       = replicatorGetter.Get();

                IDataBaseLoader dataBaseLoader = new DataBaseLoader(dataBaseGetter);
                while (!Console.KeyAvailable)
                {
                    if (Console.ReadKey(true).Key == ConsoleKey.I)
                    {
                        Console.WriteLine(dataBaseLoader.Resume());
                    }

                    if (Console.ReadKey(true).Key == ConsoleKey.A)
                    {
                        int           i          = 1;
                        List <string> acquereurs = dataBaseLoader.Acquereurs();
                        foreach (string nom in acquereurs)
                        {
                            Console.WriteLine($"{i++} {nom}");
                        }
                    }

                    if (Console.ReadKey(true).Key == ConsoleKey.R)
                    {
                        Console.WriteLine("Stopping the replicator");
                        replicator.Stop();
                        Console.WriteLine("Waiting 2 seconds ...");
                        Task.Delay(2000).Wait();
                        Console.WriteLine("starting the replicator");
                        replicator.Start();
                    }
                    if (Console.ReadKey(true).Key == ConsoleKey.Escape)
                    {
                        break;
                    }

                    Task.Delay(500).Wait();
                }

                return(0);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                return(3);
            }
            return(0);
        }
Ejemplo n.º 16
0
        private void RunTwoStepContinuous(ReplicatorType type, string uid)
        {
            using (var OtherDb1 = OpenDB(OtherDb.Name))
                using (var Db1 = OpenDB(Db.Name)) {
                    var listener = new MessageEndpointListener(new MessageEndpointListenerConfiguration(OtherDb1, ProtocolType.ByteStream));
                    var server   = new MockServerConnection(listener, ProtocolType.ByteStream);
                    var config   = new ReplicatorConfiguration(Db1,
                                                               new MessageEndpoint(uid, server, ProtocolType.ByteStream, new MockConnectionFactory(null)))
                    {
                        ReplicatorType = type,
                        Continuous     = true
                    };

                    using (var replicator = new Replicator(config)) {
                        Database firstSource  = null;
                        Database secondSource = null;
                        Database firstTarget  = null;
                        Database secondTarget = null;
                        if (type == ReplicatorType.Push)
                        {
                            firstSource  = Db1;
                            secondSource = Db1;
                            firstTarget  = OtherDb1;
                            secondTarget = OtherDb1;
                        }
                        else if (type == ReplicatorType.Pull)
                        {
                            firstSource  = OtherDb1;
                            secondSource = OtherDb1;
                            firstTarget  = Db1;
                            secondTarget = Db1;
                        }
                        else
                        {
                            firstSource  = Db1;
                            secondSource = OtherDb1;
                            firstTarget  = OtherDb1;
                            secondTarget = Db1;
                        }

                        replicator.Start();

                        using (var mdoc = new MutableDocument("livesindb")) {
                            mdoc.SetString("name", "db");
                            mdoc.SetInt("version", 1);
                            firstSource.Save(mdoc);
                        }

                        var count = 0;
                        if (type != ReplicatorType.Push)
                        {
                            while (true)
                            {
                                count++;
                                Thread.Sleep(1000);
                                if (replicator.Status.Progress.Completed > 0 &&
                                    replicator.Status.Activity == ReplicatorActivityLevel.Idle)
                                {
                                    break;
                                }
                            }

                            count.Should().BeLessThan(10, "because otherwise the replicator did not advance");
                        }
                        else //when both doc updates happens on local side with push only, replicator.Status.Progress value wipe out too fast, so skip while loop
                        {
                            Thread.Sleep(1000);
                        }

                        var previousCompleted = replicator.Status.Progress.Completed;
                        firstTarget.Count.Should().Be(1);

                        using (var savedDoc = secondSource.GetDocument("livesindb"))
                            using (var mdoc = savedDoc.ToMutable()) {
                                mdoc.SetInt("version", 2);
                                secondSource.Save(mdoc);
                            }

                        count = 0;
                        if (type != ReplicatorType.Push)
                        {
                            while (true)
                            {
                                count++;
                                Thread.Sleep(1000);
                                if (replicator.Status.Progress.Completed > previousCompleted &&
                                    replicator.Status.Activity == ReplicatorActivityLevel.Idle)
                                {
                                    break;
                                }
                            }

                            count.Should().BeLessThan(10, "because otherwise the replicator did not advance");
                        }
                        else //when both doc updates happens on local side with push only, replicator.Status.Progress value wipe out too fast, so skip while loop
                        {
                            Thread.Sleep(1000);
                        }

                        using (var savedDoc = secondTarget.GetDocument("livesindb")) {
                            savedDoc.GetInt("version").Should().Be(2);
                        }

                        replicator.Stop();
                        Thread.Sleep(100);
                        while (true)
                        {
                            if (replicator.Status.Activity == ReplicatorActivityLevel.Stopped)
                            {
                                break;
                            }
                        }
                    }
                }
        }