private ReplicatorConfiguration CreateFailureP2PConfiguration(ProtocolType protocolType, MockConnectionLifecycleLocation location, bool recoverable) { var errorLocation = TestErrorLogic.FailWhen(location); if (recoverable) { errorLocation.WithRecoverableException(); } else { errorLocation.WithPermanentException(); } var listener = new MessageEndpointListener(new MessageEndpointListenerConfiguration(_otherDB, protocolType)); var server = new MockServerConnection(listener, protocolType) { ErrorLogic = errorLocation }; var config = new ReplicatorConfiguration(Db, new MessageEndpoint("p2ptest1", server, protocolType, new MockConnectionFactory(errorLocation))) { ReplicatorType = ReplicatorType.Push, Continuous = false }; return(config); }
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); } }
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 static void InitCouchBase() { NetDesktop.Activate(); // Get the database (and create it if it doesn't exist) _database = new Database("db"); // Create replicator to push and pull changes to and from the cloud var targetEndpoint = new URLEndpoint(new Uri("ws://localhost:4984/db")); var replConfig = new ReplicatorConfiguration(_database, targetEndpoint); // Add authentication replConfig.Authenticator = new BasicAuthenticator("sync_gateway", "password"); replConfig.ReplicatorType = ReplicatorType.PushAndPull; replConfig.Continuous = true; // Create replicator (make sure to add an instance or static variable // named _Replicator) _Replicator = new Replicator(replConfig); _Replicator.AddChangeListener((sender, args) => { Instance.DataChanged.Invoke(sender, args); _log.Debug($"status={args.Status.Activity}"); _log.Debug($"progress={args.Status.Progress.Completed}/{args.Status.Progress.Total}"); _log.Debug($"error={args.Status.Error}"); if (args.Status.Error != null) { _log.Error($"Error :: {args.Status.Error}"); } }); _Replicator.Start(); }
private Replicator StartReplication(string username, string password, Database db) { if (String.IsNullOrWhiteSpace(username) || String.IsNullOrWhiteSpace(password)) { throw new InvalidOperationException("User credentials not provided"); } var dbUrl = new Uri(SyncUrl, DbName); Debug.WriteLine( $"PushPull Replicator:Will connect to {SyncUrl}"); var config = new ReplicatorConfiguration(db, new URLEndpoint(dbUrl)) { ReplicatorType = ReplicatorType.PushAndPull, Continuous = true, Authenticator = new BasicAuthenticator(username, password), Channels = new[] { $"channel.{username}" } }; var repl = new Replicator(config); repl.AddChangeListener((sender, args) => { var s = args.Status; Debug.WriteLine( $"PushPull Replicator: {s.Progress.Completed}/{s.Progress.Total}, error {s.Error?.Message ?? "<none>"}, activity = {s.Activity}"); }); repl.Start(); return(repl); }
public void TestRemoveChangeListener() { var statuses = new List <ReplicatorActivityLevel>(); var listener = new MessageEndpointListener(new MessageEndpointListenerConfiguration(_otherDB, ProtocolType.ByteStream)); var awaiter = new ListenerAwaiter(listener); var serverConnection = new MockServerConnection(listener, ProtocolType.ByteStream); var config = new ReplicatorConfiguration(Db, new MessageEndpoint("p2ptest1", serverConnection, ProtocolType.ByteStream, new MockConnectionFactory(null))) { Continuous = true }; var token = listener.AddChangeListener((sender, args) => { statuses.Add(args.Status.Activity); }); var connection = listener.Connections; listener.RemoveChangeListener(token); RunReplication(config, 0, 0); awaiter.WaitHandle.WaitOne(TimeSpan.FromSeconds(10)).Should().BeTrue(); awaiter.Validate(); statuses.Count.Should().Be(0); }
public MainWindow() { InitializeComponent(); log4net.Config.XmlConfigurator.Configure(); Couchbase.Lite.Support.NetDesktop.Activate(); var config = new DatabaseConfiguration() { Directory = AppDomain.CurrentDomain.BaseDirectory }; Database = new Database(DbName, config); var configSync = new ReplicatorConfiguration(Database, new URLEndpoint(SyncGatewayUrl)) { ReplicatorType = ReplicatorType.PushAndPull, Continuous = true }; configSync.Authenticator = new BasicAuthenticator("emonthly", "password"); _replication = new Replicator(configSync); _replication.AddChangeListener((sender, args) => { Console.WriteLine(args.Status.Activity); }); _replication.Start(); }
private void Connect() { try { if (_serverInfo == null) { _serverInfo = _serverDal.Get(); } if (_serverInfo == null) { return; } Uri target = new Uri($"ws://{_serverInfo.UrlServer}"); IEndpoint endpoint = new URLEndpoint(target); ReplicatorConfiguration replicationConfig = new ReplicatorConfiguration(_dataBaseGetter.Get(), endpoint) { Continuous = true, ReplicatorType = ReplicatorType.PushAndPull, Authenticator = new BasicAuthenticator(_serverInfo.Login, _serverInfo.Password) }; _replicator = new Replicator(replicationConfig); if (CrossConnectivity.IsSupported && CrossConnectivity.Current.IsConnected) { _replicator.Start(); } _token = _replicator.AddChangeListener(_replicator_StatusChanged); } catch (Exception e) { #if DEBUG #endif } }
public void CreateReplicator(string PeerEndpointString) { if (_repl != null) { return; } Uri host = new Uri(PeerEndpointString); var dbUrl = new Uri(host, _db.Name); var replicatorConfig = new ReplicatorConfiguration(_db, new URLEndpoint(dbUrl)); // <1> replicatorConfig.ReplicatorType = ReplicatorType.PushAndPull; replicatorConfig.Continuous = true; if (CoreApp.ListenerTLSMode > 0) { // Explicitly allows self signed certificates. By default, only // CA signed cert is allowed switch (CoreApp.ListenerCertValidationMode) // <2> { case LISTENER_CERT_VALIDATION_MODE.SKIP_VALIDATION: // Use acceptOnlySelfSignedServerCertificate set to true to only accept self signed certs. // There is no cert validation replicatorConfig.AcceptOnlySelfSignedServerCertificate = true; break; case LISTENER_CERT_VALIDATION_MODE.ENABLE_VALIDATION_WITH_CERT_PINNING: // Use acceptOnlySelfSignedServerCertificate set to false to only accept CA signed certs // Self signed certs will fail validation replicatorConfig.AcceptOnlySelfSignedServerCertificate = false; // Enable cert pinning to only allow certs that match pinned cert try { var pinnedCert = LoadSelfSignedCertForListenerFromBundle(); replicatorConfig.PinnedServerCertificate = pinnedCert; } catch (Exception ex) { Debug.WriteLine($"Failed to load server cert to pin. Will proceed without pinning. {ex}"); } break; case LISTENER_CERT_VALIDATION_MODE.ENABLE_VALIDATION: // Use acceptOnlySelfSignedServerCertificate set to false to only accept CA signed certs // Self signed certs will fail validation. There is no cert pinning replicatorConfig.AcceptOnlySelfSignedServerCertificate = false; break; } } if (CoreApp.RequiresUserAuth) { var user = CoreApp.CurrentUser; replicatorConfig.Authenticator = new BasicAuthenticator(user.Username, user.Password); // <3> } _repl = new Replicator(replicatorConfig); // <4> _listenerToken = _repl.AddChangeListener(ReplicationStatusUpdate); }
public void StartReplication() { try { var targetUrlEndpoint = new URLEndpoint(new Uri(_remoteSyncUrl, _databaseName)); var configuration = new ReplicatorConfiguration(Database, targetUrlEndpoint) { ReplicatorType = ReplicatorType.PushAndPull, Continuous = true }; _replicator = new Replicator(configuration); _replicatorListenerToken = _replicator.AddChangeListener(OnReplicatorUpdate); _replicator.Start(); } catch (Exception ex) { // We don't want replication errors to prevent us from // using the app, but we do want to know about them. Console.WriteLine($"Replication Exception - {ex.Message}"); } }
public void TestChannelPull() { _otherDB.Count.Should().Be(0); Db.InBatch(() => { for (int i = 0; i < 5; i++) { using (var doc = new MutableDocument($"doc-{i}")) { doc["foo"].Value = "bar"; Db.Save(doc); } } for (int i = 0; i < 10; i++) { using (var doc = new MutableDocument($"doc-{i+5}")) { doc["channels"].Value = "my_channel"; Db.Save(doc); } } }); var config = CreateConfig(true, false, false, new URLEndpoint(new Uri("ws://localhost/db"))); RunReplication(config, 0, 0); config = new ReplicatorConfiguration(_otherDB, new URLEndpoint(new Uri("ws://localhost/db"))); ModifyConfig(config, false, true, false); config.Channels = new[] { "my_channel" }; RunReplication(config, 0, 0); _otherDB.Count.Should().Be(10, "because 10 documents should be in the given channel"); }
private void Connect() { Uri target = new Uri($"{_serverInfo.UrlServer}"); ReplicatorConfiguration replicationConfig = new ReplicatorConfiguration(_dataBaseGetter.Get(), target); replicationConfig.Continuous = true; replicationConfig.ReplicatorType = ReplicatorType.PushAndPull; replicationConfig.Authenticator = new BasicAuthenticator(_serverInfo.Login, _serverInfo.Password); _replicator = new Replicator(replicationConfig); _replicator.Start(); _token = _replicator.AddChangeListener(_replicator_StatusChanged); }
private static void TestReplicatorConflictResolver() { // tag::replication-conflict-resolver[] var target = new URLEndpoint(new Uri("ws://localhost:4984/mydatabase")); var replConfig = new ReplicatorConfiguration(database, target); replConfig.ConflictResolver = new LocalWinConflictResolver(); var replicator = new Replicator(replConfig); replicator.Start(); // end::replication-conflict-resolver[] }
public void TestP2PPassiveCloseAll() { var listener = new MessageEndpointListener(new MessageEndpointListenerConfiguration(_otherDB, ProtocolType.MessageStream)); var serverConnection1 = new MockServerConnection(listener, ProtocolType.MessageStream); var serverConnection2 = new MockServerConnection(listener, ProtocolType.MessageStream); var errorLogic = new ReconnectErrorLogic(); var config = new ReplicatorConfiguration(Db, new MessageEndpoint("p2ptest1", serverConnection1, ProtocolType.MessageStream, new MockConnectionFactory(errorLogic))) { Continuous = true }; var config2 = new ReplicatorConfiguration(Db, new MessageEndpoint("p2ptest2", serverConnection2, ProtocolType.MessageStream, new MockConnectionFactory(errorLogic))) { Continuous = true }; var replicator = new Replicator(config); replicator.Start(); var replicator2 = new Replicator(config2); replicator2.Start(); var count = 0; while (count++ < 10 && replicator.Status.Activity != ReplicatorActivityLevel.Idle && replicator2.Status.Activity != ReplicatorActivityLevel.Idle) { Thread.Sleep(500); count.Should().BeLessThan(10, "because otherwise the replicator(s) never went idle"); } errorLogic.ErrorActive = true; listener.CloseAll(); count = 0; while (count++ < 10 && replicator.Status.Activity != ReplicatorActivityLevel.Stopped && replicator2.Status.Activity != ReplicatorActivityLevel.Stopped) { Thread.Sleep(500); count.Should().BeLessThan(10, "because otherwise the replicator(s) never stopped"); } replicator.Status.Error.Should() .NotBeNull("because closing the passive side creates an error on the active one"); replicator2.Status.Error.Should() .NotBeNull("because closing the passive side creates an error on the active one"); replicator.Dispose(); replicator2.Dispose(); }
public void StartDBConnection() { Couchbase.Lite.Support.UWP.Activate(); // Get the database (and create it if it doesn't exist) this.database = new Database("einkaufsliste"); // Create replicator to push and pull changes to and from the cloud var targetEndpoint = new URLEndpoint(new Uri("ws://37.252.185.24:4984/db")); var replConfig = new ReplicatorConfiguration(this.database, targetEndpoint) { ReplicatorType = ReplicatorType.PushAndPull }; replConfig.Channels = new List <String>(); replConfig.Channels.Add("liste"); replConfig.Continuous = true; // Add authentication replConfig.Authenticator = new BasicAuthenticator("UserEin", "Einkaufsliste"); // Create replicator var replicator = new Replicator(replConfig); replicator.AddChangeListener((sender, args) => { if (args.Status.Error != null) { System.Diagnostics.Debug.WriteLine($"Error :: {args.Status.Error}"); } System.Diagnostics.Debug.WriteLine("Test sync"); using (var query = QueryBuilder.Select(SelectResult.All()) .From(DataSource.Database(this.database))) { // Run the query var result = query.Execute(); var res = result.ToArray(); foreach (var i in res) { System.Diagnostics.Debug.WriteLine("Output " + Newtonsoft.Json.JsonConvert.SerializeObject(i)); System.Diagnostics.Debug.WriteLine("Output " + i.GetDictionary(0).GetString("name")); } result = query.Execute(); System.Diagnostics.Debug.WriteLine("Number " + result.Count()); } }); replicator.Start(); }
public void syncorder(Database syncdb) { var url = new Uri("ws://104.214.56.109:4984/order"); var target = new URLEndpoint(url); var config = new ReplicatorConfiguration(syncdb, target) { ReplicatorType = ReplicatorType.Push }; var replicator = new Replicator(config); replicator.Start(); }
private static void PinCertificate() { // Note: No certificate is included here, so this code is for show only var url = new Uri("wss://localhost:4984/db"); var target = new URLEndpoint(url); var db = _Database; // # tag::certificate-pinning[] var certificate = new X509Certificate2("cert.cer"); var config = new ReplicatorConfiguration(db, target) { PinnedServerCertificate = certificate }; // # end::certificate-pinning[] }
private static void ResetReplicatorCheckpoint() { var database = _Database; var url = new Uri("ws://localhost:4984/db"); var target = new URLEndpoint(url); var config = new ReplicatorConfiguration(database, target); using (var replicator = new Replicator(config)) { // # tag::replication-reset-checkpoint[] // replicator is a Replicator instance replicator.ResetCheckpoint(); replicator.Start(); // # end::replication-reset-checkpoint[] } }
private static void ReplicationCustomHeaders() { var url = new Uri("ws://localhost:4984/mydatabase"); var target = new URLEndpoint(url); // tag::replication-custom-header[] var config = new ReplicatorConfiguration(database, target) { Headers = new Dictionary <string, string> { ["CustomHeaderName"] = "Value" } }; // end::replication-custom-header[] }
private static void EnableSessionAuth() { var database = _Database; // tag::session-authentication[] var url = new Uri("ws://localhost:4984/mydatabase"); var target = new URLEndpoint(url); var config = new ReplicatorConfiguration(database, target); config.Authenticator = new SessionAuthenticator("904ac010862f37c8dd99015a33ab5a3565fd8447"); var replicator = new Replicator(config); replicator.Start(); // end::session-authentication[] }
private static void EnableBasicAuth() { var database = _Database; // tag::basic-authentication[] var url = new Uri("ws://localhost:4984/mydatabase"); var target = new URLEndpoint(url); var config = new ReplicatorConfiguration(database, target); config.Authenticator = new BasicAuthenticator("john", "pass"); var replicator = new Replicator(config); replicator.Start(); // end::basic-authentication[] }
public void TestPasswordAuthenticator() { var auth = new ListenerPasswordAuthenticator((sender, username, password) => { return(username == "daniel" && new NetworkCredential(string.Empty, password).Password == "123"); }); _listener = CreateListener(false, true, auth); // Replicator - No authenticator var targetEndpoint = _listener.LocalEndpoint(); var config = new ReplicatorConfiguration(Db, targetEndpoint); RunReplication(config, (int)CouchbaseLiteError.HTTPAuthRequired, CouchbaseLiteErrorType.CouchbaseLite); var pw = "123"; var wrongPw = "456"; SecureString pwSecureString = null; SecureString wrongPwSecureString = null; unsafe { fixed(char *pw_ = pw) fixed(char *wrongPw_ = wrongPw) { pwSecureString = new SecureString(pw_, pw.Length); wrongPwSecureString = new SecureString(wrongPw_, wrongPw.Length); } } // Replicator - Wrong Credentials config = new ReplicatorConfiguration(Db, targetEndpoint) { Authenticator = new BasicAuthenticator("daniel", wrongPwSecureString) }; RunReplication(config, (int)CouchbaseLiteError.HTTPAuthRequired, CouchbaseLiteErrorType.CouchbaseLite); // Replicator - Success config = new ReplicatorConfiguration(Db, targetEndpoint) { Authenticator = new BasicAuthenticator("daniel", pwSecureString) }; RunReplication(config, 0, 0); _listener.Stop(); pwSecureString.Dispose(); wrongPwSecureString.Dispose(); }
public void TestReachability() { try { var status = NetworkReachabilityStatus.Unknown; var e = new NetworkReachabilityChangeEventArgs(status); NetworkReachabilityStatus s = NetworkReachabilityStatus.Unknown; var _reachability = new Reachability(); _reachability.StatusChanged += (sender, args) => s = args.Status; _reachability.Start(); e.Status.Should().Be(s); var method = ReachabilityType.GetMethod("InvokeNetworkChangeEvent", BindingFlags.NonPublic | BindingFlags.Instance); var res = method.Invoke(_reachability, new object[1] { s }); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); method = ReachabilityType.GetMethod("IsInterfaceValid", BindingFlags.NonPublic | BindingFlags.Static); foreach (var n in nics) { res = method.Invoke(null, new object[1] { n }); } var asender = new object(); method = ReachabilityType.GetMethod("OnNetworkChange", BindingFlags.NonPublic | BindingFlags.Instance); res = method.Invoke(_reachability, new object[2] { asender, e }); var ReplicatorType = typeof(Replicator); var targetEndpoint = new URLEndpoint(new Uri("ws://192.168.0.11:4984/app")); var config = new ReplicatorConfiguration(Db, targetEndpoint); using (Replicator replicator = new Replicator(config)) { method = ReplicatorType.GetMethod("ReachabilityChanged", BindingFlags.NonPublic | BindingFlags.Instance); res = method.Invoke(replicator, new object[2] { asender, e }); } } catch { } }
private ReplicatorConfiguration ModifyConfig(ReplicatorConfiguration config, bool push, bool pull, bool continuous) { var type = (ReplicatorType)0; if (push) { type |= ReplicatorType.Push; } if (pull) { type |= ReplicatorType.Pull; } config.ReplicatorType = type; config.Continuous = continuous; return(config); }
public Replicator StartReplicator(Database db) { try { Uri target = new Uri("blip://192.168.1.10:4984/travel-sample"); ReplicatorConfiguration replicationConfig = new ReplicatorConfiguration(db, target); replicationConfig.Continuous = true; replicationConfig.ReplicatorType = ReplicatorType.PushAndPull; replicationConfig.Authenticator = new BasicAuthenticator("Gateway", "production"); var replication = new Replicator(replicationConfig); replication.Start(); return(replication); } catch (Exception e) { throw new Exception($"Connection starting replication in StartReplicator, {e.Message}", e); } }
/// <summary> /// Starts a replication for the session /// </summary> /// <param name="username">The username to use for the replication</param> /// <param name="password">The password to use for replication auth (optional)</param> public static void StartReplication(string username, string password = null) { var config = new ReplicatorConfiguration(Database, new URLEndpoint(SyncGatewayUrl)) { ReplicatorType = ReplicatorType.PushAndPull, Continuous = true }; if (username != null && password != null) { config.Authenticator = new BasicAuthenticator(username, password); } _replication = new Replicator(config); _replication.AddChangeListener((sender, args) => { Console.WriteLine(args.Status.Activity); }); _replication.Start(); }
public async Task TestReplicatorStopsWhenEndpointInvalid() { // If this IP address happens to exist, then change it. It needs to be an address that does not // exist on the LAN var targetEndpoint = new URLEndpoint(new Uri("ws://192.168.0.11:4984/app")); var config = new ReplicatorConfiguration(Db, targetEndpoint); using (var repl = new Replicator(config)) { repl.Start(); var count = 0; while (count++ <= 35 && repl.Status.Activity != ReplicatorActivityLevel.Stopped) { WriteLine($"Replication status still {repl.Status.Activity}, waiting for stopped..."); await Task.Delay(500); } count.Should().BeLessThan(35, "because otherwise the replicator never stopped"); } }
public void TestP2PPassiveClose() { var listener = new MessageEndpointListener(new MessageEndpointListenerConfiguration(_otherDB, ProtocolType.MessageStream)); var awaiter = new ListenerAwaiter(listener); var serverConnection = new MockServerConnection(listener, ProtocolType.MessageStream); var errorLogic = new ReconnectErrorLogic(); var config = new ReplicatorConfiguration(Db, new MessageEndpoint("p2ptest1", serverConnection, ProtocolType.MessageStream, new MockConnectionFactory(errorLogic))) { Continuous = true }; var replicator = new Replicator(config); replicator.Start(); var count = 0; while (count++ < 10 && replicator.Status.Activity != ReplicatorActivityLevel.Idle) { Thread.Sleep(500); count.Should().BeLessThan(10, "because otherwise the replicator never went idle"); } errorLogic.ErrorActive = true; listener.Close(serverConnection); count = 0; while (count++ < 10 && replicator.Status.Activity != ReplicatorActivityLevel.Stopped) { Thread.Sleep(500); count.Should().BeLessThan(10, "because otherwise the replicator never stopped"); } awaiter.WaitHandle.WaitOne(TimeSpan.FromSeconds(10)).Should().BeTrue(); awaiter.Validate(); replicator.Status.Error.Should() .NotBeNull("because closing the passive side creates an error on the active one"); }
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; } }
private static void PinCertificate() { // Note: No certificate is included here, so this code is for show only var url = new Uri("wss://localhost:4984/db"); var target = new URLEndpoint(url); var db = _Database; // tag::certificate-pinning[] // Note: `GetCertificate` is a fake method. This would be the platform-specific method // to find and load the certificate as an instance of `X509Certificate2`. // For .NET Core / .NET Framework this can be loaded from the filesystem path. // For UWP, from the assets directory. // For iOS, from the main bundle. // For Android, from the assets directory. var certificate = GetCertificate("cert.cer"); var config = new ReplicatorConfiguration(db, target) { PinnedServerCertificate = certificate }; // end::certificate-pinning[] }