public List <Path> GetExternalPaths(Action <List <Path> > pathsUpdated)
        {
            List <Path> paths = new List <Path>();

            try
            {
                _pathsQuery = QueryBuilder
                              .Select(SelectResult.All())
                              .From(DataSource.Database(DatabaseManager.Database))
                              .Where((Expression.Property("type").EqualTo(Expression.String("path"))
                                      .And(Expression.Property("createdBy").NotEqualTo(Expression.String(AppInstance.AppId)))));

                if (pathsUpdated != null)
                {
                    _pathsQueryToken = _pathsQuery.AddChangeListener((object sender, QueryChangedEventArgs e) =>
                    {
                        if (e?.Results != null && e.Error == null)
                        {
                            paths = e.Results.AllResults()?.ToObjects <Path>(databaseName) as List <Path>;

                            if (paths != null)
                            {
                                pathsUpdated.Invoke(paths);
                            }
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"CanvasRepository GetExternalPaths Exception: {ex.Message}");
            }

            return(paths);
        }
Exemple #2
0
 public int Remove(ListenerToken id)
 {
     lock (_locker) {
         _events.Remove(id.EventHandler as CouchbaseEventHandler <TEventType>);
         return(_events.Count);
     }
 }
Exemple #3
0
        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 List <Hero> GetHeroes(Action <List <Hero> > heroesUpdated)
        {
            var heroes = new List <Hero>();

            try
            {
                _heroesQuery = QueryBuilder
                               .Select(SelectResult.All())
                               .From(DataSource.Database(DatabaseManager.Database))
                               .Where((Expression.Property("type").EqualTo(Expression.String("hero"))));

                if (heroesUpdated != null)
                {
                    _heroesQueryToken = _heroesQuery.AddChangeListener((object sender, QueryChangedEventArgs e) =>
                    {
                        if (e?.Results != null && e.Error == null)
                        {
                            heroes = e.Results.AllResults()?.ToObjects <Hero>() as List <Hero>;

                            if (heroes != null)
                            {
                                heroesUpdated.Invoke(heroes);
                            }
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"HeroRepository GetHeroesAsync Exception: {ex.Message}");
            }

            return(heroes);
        }
Exemple #5
0
        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
            }
        }
        /// <summary>
        /// Gets the current user bookings from the database
        /// </summary>
        /// <returns>An <c>await</c>able <see cref="Task"/> that will complete when the
        /// first set of results are ready</returns>
        public Task FetchBookings()
        {
            var tcs = new TaskCompletionSource <bool>();

            _bookingQuery = Query
                            .Select(FlightsResult)
                            .From(DataSource.Database(UserSession.Database))
                            .Where(UsernameProperty.EqualTo(UserSession.Username));

            var retVal = tcs.Task;

            _cancelToken = _bookingQuery.AddChangeListener(null, (sender, args) =>
            {
                foreach (var row in args.Rows)
                {
                    var bookings  = row.GetArray("flights");
                    var eventArgs = new BookingsUpdateEventArgs(EnumerateBookings(bookings));
                    BookingsChanged?.Invoke(this, eventArgs);
                }

                var oldTcs = Interlocked.Exchange(ref tcs, null);
                oldTcs?.SetResult(true);
            });

            return(retVal);
        }
Exemple #7
0
        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}");
            }
        }
Exemple #8
0
 /// <summary>
 /// Removes a previously added change listener via its <see cref="ListenerToken"/> and/or
 /// Removes a previously added documents ended listener via its <see cref="ListenerToken"/>
 /// </summary>
 /// <param name="token">The token received from <see cref="AddChangeListener(TaskScheduler, EventHandler{ReplicatorStatusChangedEventArgs})"/>
 /// and/or The token received from <see cref="AddDocumentReplicationListener(TaskScheduler, EventHandler{DocumentReplicationEventArgs})"/></param>
 public void RemoveChangeListener(ListenerToken token)
 {
     _statusChanged.Remove(token);
     if (_documentEndedUpdate.Remove(token) == 0)
     {
         Config.Options.ProgressLevel = ReplicatorProgressLevel.Overall;
     }
 }
Exemple #9
0
 /// <summary>
 /// Removes a previously added change listener via its <see cref="ListenerToken"/> and/or
 /// Removes a previously added documents ended listener via its <see cref="ListenerToken"/>
 /// </summary>
 /// <param name="token">The token received from <see cref="AddChangeListener(TaskScheduler, EventHandler{ReplicatorStatusChangedEventArgs})"/>
 /// and/or The token received from <see cref="AddDocumentReplicationListener(TaskScheduler, EventHandler{DocumentReplicationEventArgs})"/></param>
 public void RemoveChangeListener(ListenerToken token)
 {
     _statusChanged.Remove(token);
     if (_documentEndedUpdate.Remove(token) == 0)
     {
         SetProgressLevel(C4ReplicatorProgressLevel.Overall);
     }
 }
        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);
        }
        public int Remove(ListenerToken token)
        {
            if (!(token.EventHandler is CouchbaseEventHandler <TFilterType, TEventType> handler))
            {
                return(-1);
            }

            var collection = _eventMap.GetOrAdd(handler.Filter, new HashSet <CouchbaseEventHandler <TEventType> >());

            lock (_locker) {
                collection.Remove(handler);
                return(collection.Count);
            }
        }
Exemple #12
0
        public int Remove(ListenerToken token, out TFilterType filter)
        {
            filter = default(TFilterType);
            if (!(token.EventHandler is CouchbaseEventHandler <TFilterType, TEventType> handler))
            {
                return(-1);
            }

            var collection = _eventMap.GetOrAdd(handler.Filter, new HashSet <CouchbaseEventHandler <TEventType> >())
                             ?? new HashSet <CouchbaseEventHandler <TEventType> >(); // Suppress R# inspection

            lock (_locker) {
                collection.Remove(handler);
                filter = handler.Filter;
                return(collection.Count);
            }
        }
Exemple #13
0
        public void StartReplication(string sessionId,
                                     string[] channels,
                                     ReplicatorType replicationType = ReplicatorType.PushAndPull,
                                     bool continuous = true)
        {
            var targetUrlEndpoint = new URLEndpoint(new Uri(_remoteSyncUrl, _databaseName));

            var configuration = new ReplicatorConfiguration(Database, targetUrlEndpoint)
            {
                ReplicatorType = replicationType,
                Continuous     = continuous,
                Authenticator  = new SessionAuthenticator(sessionId),
                Channels       = channels
            };

            _replicator = new Replicator(configuration);

            _replicatorListenerToken = _replicator.AddChangeListener(OnReplicatorUpdate);

            _replicator.Start();
        }
Exemple #14
0
        public List <Item> GetItems(Action <List <Item> > userProfileUpdated)
        {
            List <Item> items = new List <Item>();

            try
            {
                var database = DatabaseManager.Database;

                if (database != null)
                {
                    _userQuery = QueryBuilder
                                 .Select(SelectResult.All())
                                 .From(DataSource.Database(database))
                                 .Where((Expression.Property("type").EqualTo(Expression.String("item"))));
                    //.And(Expression.String("tenant_2").In(Expression.Property("channels"))));

                    if (userProfileUpdated != null)
                    {
                        _userQueryToken = _userQuery.AddChangeListener((object sender, QueryChangedEventArgs e) =>
                        {
                            if (e?.Results != null && e.Error == null)
                            {
                                items = e.Results.AllResults()?.ToObjects <Item>("test") as List <Item>;

                                if (items != null)
                                {
                                    userProfileUpdated.Invoke(items);
                                }
                            }
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"TestRepository Exception: {ex.Message}");
            }

            return(items);
        }
Exemple #15
0
        public List <Message> GetMessages(Action <List <Message> > messagesUpdated)
        {
            List <Message> messages = new List <Message>();

            try
            {
                var database = DatabaseManager.Database;

                if (database != null)
                {
                    _messagesQuery = QueryBuilder
                                     .Select(SelectResult.All())
                                     .From(DataSource.Database(database))
                                     .Where((Expression.Property("type").EqualTo(Expression.String("message")))
                                            .And((Expression.Property("channel").EqualTo(Expression.String(AppInstance.Channel)))));

                    if (messagesUpdated != null)
                    {
                        _messagesQueryToken = _messagesQuery.AddChangeListener((object sender, QueryChangedEventArgs e) =>
                        {
                            if (e?.Results != null && e.Error == null)
                            {
                                messages = e.Results.AllResults()?.ToObjects <Message>("chatbase") as List <Message>;

                                if (messages != null)
                                {
                                    messagesUpdated.Invoke(messages);
                                }
                            }
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"ChatRepository Exception: {ex.Message}");
            }

            return(messages);
        }
Exemple #16
0
 public ListenerAwaiter(MessageEndpointListener listener)
 {
     _token    = listener.AddChangeListener(CheckForStopped);
     _listener = listener;
 }
Exemple #17
0
 /// <summary>
 /// Removes a previously added change listener via its <see cref="ListenerToken"/>
 /// </summary>
 /// <param name="token">The token received from <see cref="AddChangeListener(TaskScheduler, EventHandler{ReplicatorStatusChangedEventArgs})"/></param>
 public void RemoveChangeListener(ListenerToken token)
 {
     _statusChanged.Remove(token);
 }