//SERVER & DOCUMENTS
        /// <exception cref="System.IO.IOException"></exception>
        // [Test]
        public void TestAPIManager()
        {
            Manager manager = this.manager;

            Assert.IsTrue(manager != null);

            foreach (string dbName in manager.AllDatabaseNames)
            {
                Database db = manager.GetDatabase(dbName);
                Log.I(Tag, "Database '" + dbName + "':" + db.DocumentCount + " documents");
            }

            var options = new ManagerOptions();

            options.ReadOnly          = true;
            options.CallbackScheduler = new SingleTaskThreadpoolScheduler();

            var roManager = new Manager(new DirectoryInfo(manager.Directory), options);

            Assert.IsTrue(roManager != null);

            var nonExistantDatabase = roManager.GetDatabase("foo");

            Assert.IsNull(nonExistantDatabase);

            var dbNames = manager.AllDatabaseNames;

            Assert.IsFalse(dbNames.Contains <String>("foo"));
            Assert.IsTrue(dbNames.Contains(DefaultTestDb));
        }
        public void TestUpgradeOldDatabaseFiles()
        {
            var testDirName = "test-directory-" + Runtime.CurrentTimeMillis();
            var rootDirPath = RootDirectory.FullName;
            var testDirPath = Path.Combine(rootDirPath, testDirName);
            var testDirInfo = Directory.CreateDirectory(testDirPath);

            var dbStream   = GetAsset("withattachments.cblite");
            var destStream = File.OpenWrite(Path.Combine(testDirPath, "withattachments" + Manager.DatabaseSuffixv1));

            dbStream.CopyTo(destStream);
            dbStream.Dispose();
            destStream.Dispose();

            var attStream = GetAsset("attachment.blob");

            Directory.CreateDirectory(Path.Combine(testDirPath, "withattachments/attachments"));
            destStream = File.OpenWrite(Path.Combine(testDirPath, "withattachments/attachments/356a192b7913b04c54574d18c28d46e6395428ab.blob"));
            attStream.CopyTo(destStream);
            destStream.Dispose();
            attStream.Dispose();

            StopCBLite();
            manager = new Manager(testDirInfo, Manager.DefaultOptions);
            var db      = manager.GetDatabase("withattachments", true);
            int version = DatabaseUpgraderFactory.SchemaVersion(Path.Combine(db.DbDirectory, "db.sqlite3"));

            Assert.IsTrue(version >= 101, "Upgrade failed");
            Assert.IsFalse(Directory.Exists(Path.Combine(testDirPath, "withattachments/attachments")), "Failed to remove old attachments dir");
            Assert.IsTrue(Directory.Exists(db.AttachmentStorePath), "Failed to create new attachments dir");
        }
        public void Test09LoadDB()
        {
            RunTest("Test09LoadDB", (parameters) =>
            {
                var numDocs = Convert.ToInt32(parameters[NUMDOCS_KEY]);
                var docSize = Convert.ToInt32(parameters[DOCSIZE_KEY]);

                var docs = new Document[numDocs];
                database.RunInTransaction(() =>
                {
                    var props = CreateTestProperties(docSize);
                    for (var i = 0; i < docs.Length; i++)
                    {
                        var doc = database.CreateDocument();
                        doc.PutProperties(props);
                        docs[i] = doc;
                    }

                    return(true);
                });

                var stopwatch = Stopwatch.StartNew();

                database.Close();
                manager.Close();

                var path = new DirectoryInfo(GetServerPath() + "/tests");
                manager  = new Manager(path, Manager.DefaultOptions);
                database = manager.GetDatabase(DefaultTestDb);

                stopwatch.Stop();

                return(stopwatch.ElapsedMilliseconds);
            });
        }
Beispiel #4
0
        public void TestSharedMapBlocks()
        {
            var path = new DirectoryInfo(Path.Combine(RootDirectory.FullName, "API_SharedMapBlocks"));
            var mgr  = new Manager(path, Manager.DefaultOptions);
            var db   = mgr.GetDatabase("db");

            db.Open();
            db.SetFilter("phil", (r, p) => true);
            db.SetValidation("val", (p1, p2) => true);

            var view = db.GetView("view");
            var ok   = view.SetMapReduce((p1, p2) => { return; }, (a, b, c) => { return(null); }, "1");

            Assert.IsNotNull(ok, "Couldn't set map/reduce");

            var map        = view.Map;
            var reduce     = view.Reduce;
            var filter     = db.GetFilter("phil");
            var validation = db.GetValidation("val");
            var result     = mgr.RunAsync((database) =>
            {
                Assert.IsNotNull(database);
                var serverView = database.GetExistingView("view");
                Assert.IsNotNull(serverView);
                Assert.AreEqual(database.GetFilter("phil"), filter);
                Assert.AreEqual(database.GetValidation("val"), validation);
                Assert.AreEqual(serverView.Map, map);
                Assert.AreEqual(serverView.Reduce, reduce);
            }, db);

            result.Wait(TimeSpan.FromSeconds(5));
            // blocks until async task has run
            db.Close();
            mgr.Close();
        }
Beispiel #5
0
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        protected internal virtual Database EnsureEmptyDatabase(string dbName)
        {
            Database db = manager.GetExistingDatabase(dbName);

            if (db != null)
            {
                db.Delete();
            }
            db = manager.GetDatabase(dbName);
            return(db);
        }
        protected internal virtual Database EnsureEmptyDatabase(string dbName)
        {
            Database db = manager.GetExistingDatabase(dbName);

            if (db != null)
            {
                bool status = db.Delete();
                NUnit.Framework.Assert.IsTrue(status);
            }
            db = manager.GetDatabase(dbName);
            return(db);
        }
	void Start() {
		Log.SetLogger(new UnityLogger());

		var path = Application.persistentDataPath;
		Log.D (TAG, "Database path: " + path);

		_manager = new Manager (new DirectoryInfo (Application.persistentDataPath), new ManagerOptions { CallbackScheduler = UnityMainThreadScheduler.TaskScheduler } );
		_db = _manager.GetDatabase ("unity_test");

		CreateGameObjectsView ();
		CreateCounterView ();
		StartReplication ();

		Log.D (TAG, "Finished Init");
	}
        public void TestChangeUUID()
        {
            var mgr = new Manager(new DirectoryInfo(Path.Combine(GetRootDirectory().FullName, "ChangeUUID")), Manager.DefaultOptions);
            var db  = mgr.GetDatabase("db");

            db.Open();

            var pub  = db.PublicUUID();
            var priv = db.PrivateUUID();

            Assert.IsTrue(pub.Length > 10);
            Assert.IsTrue(priv.Length > 10);
            Assert.IsTrue(db.ReplaceUUIDs(), "replaceUUIDs failed");
            Assert.IsFalse(pub.Equals(db.PublicUUID()));
            Assert.IsFalse(priv.Equals(db.PrivateUUID()));
            mgr.Close();
        }
	void Start() {
#if UNITY_STANDALONE_WIN && !UNITY_EDITOR
		SQLitePCL.SQLite3Provider.SetDllDirectory (Path.Combine(Application.dataPath, "Plugins"));
#elif UNITY_EDITOR
		Log.SetLogger(new UnityLogger());
#endif
		var path = Application.persistentDataPath;
		Log.D (TAG, "Database path: " + path);

		_manager = new Manager (new DirectoryInfo (Application.persistentDataPath), new ManagerOptions { CallbackScheduler = UnityMainThreadScheduler.TaskScheduler } );
		_db = _manager.GetDatabase ("unity_test");

		CreateGameObjectsView ();
		CreateCounterView ();
		StartReplication ();

		Log.D (TAG, "Finished Init");
	}
Beispiel #10
0
		//SERVER & DOCUMENTS
		/// <exception cref="System.Exception"></exception>
		public virtual void TestAPIManager()
		{
			Manager manager = this.manager;
			NUnit.Framework.Assert.IsTrue(manager != null);
			foreach (string dbName in manager.GetAllDatabaseNames())
			{
				Database db = manager.GetDatabase(dbName);
				Log.I(Tag, "Database '" + dbName + "':" + db.GetDocumentCount() + " documents");
			}
			ManagerOptions options = new ManagerOptions();
			options.SetReadOnly(true);
			Manager roManager = new Manager(new FilePath(manager.GetDirectory()), options);
			NUnit.Framework.Assert.IsTrue(roManager != null);
			Database db_1 = roManager.GetDatabase("foo");
			NUnit.Framework.Assert.IsNull(db_1);
			IList<string> dbNames = manager.GetAllDatabaseNames();
			NUnit.Framework.Assert.IsFalse(dbNames.Contains("foo"));
			NUnit.Framework.Assert.IsTrue(dbNames.Contains(DefaultTestDb));
		}
Beispiel #11
0
        protected internal virtual Database EnsureEmptyDatabase(string dbName)
        {
            Database db = manager.GetExistingDatabase(dbName);

            if (db != null)
            {
                var status = false;;

                try {
                    db.Delete();
                    status = true;
                } catch (Exception e) {
                    Log.E(Tag, "Cannot delete database " + e.Message);
                }

                NUnit.Framework.Assert.IsTrue(status);
            }
            db = manager.GetDatabase(dbName);
            return(db);
        }
        protected Database EnsureEmptyDatabase(string dbName)
        {
            var db = manager.GetExistingDatabase(dbName);

            if (db != null)
            {
                var status = false;;

                try {
                    db.Delete();
                    db.Close();
                    status = true;
                } catch (Exception e) {
                    Log.E(TAG, "Cannot delete database " + e.Message);
                }

                Assert.IsTrue(status);
            }
            db = manager.GetDatabase(dbName);
            return(db);
        }
Beispiel #13
0
        public void TestChangeUUID()
        {
            var path = new DirectoryInfo(Path.Combine(RootDirectory.FullName, "ChangeUUID"));
            var mgr = new Manager(path, Manager.DefaultOptions);
            var db = mgr.GetDatabase("db");

            db.Open();

            var pub = db.PublicUUID();
            var priv = db.PrivateUUID();
            Assert.IsTrue(pub.Length > 10);
            Assert.IsTrue(priv.Length > 10);
            Assert.IsTrue(db.ReplaceUUIDs(), "replaceUUIDs failed");
            Assert.IsFalse(pub.Equals(db.PublicUUID()));
            Assert.IsFalse(priv.Equals(db.PrivateUUID()));
            mgr.Close();
        }
        public void TestUpgradeOldDatabaseFiles()
        {
            var testDirName = "test-directory-" + Runtime.CurrentTimeMillis();
            var rootDirPath = RootDirectory.FullName;
            var testDirPath = Path.Combine(rootDirPath, testDirName);
            var testDirInfo = Directory.CreateDirectory(testDirPath);

            var dbStream = GetAsset("withattachments.cblite");
            var destStream = File.OpenWrite(Path.Combine(testDirPath, "withattachments" + Manager.DatabaseSuffixv1));
            dbStream.CopyTo(destStream);
            dbStream.Dispose();
            destStream.Dispose();

            var attStream = GetAsset("attachment.blob");
            Directory.CreateDirectory(Path.Combine(testDirPath, "withattachments/attachments"));
            destStream = File.OpenWrite(Path.Combine(testDirPath, "withattachments/attachments/356a192b7913b04c54574d18c28d46e6395428ab.blob"));
            attStream.CopyTo(destStream);
            destStream.Dispose();
            attStream.Dispose();

            StopCBLite();
            manager = new Manager(testDirInfo, Manager.DefaultOptions);
            var db = manager.GetDatabase("withattachments", true);
            int version = DatabaseUpgraderFactory.SchemaVersion(Path.Combine(db.DbDirectory, "db.sqlite3"));
            Assert.IsTrue(version >= 101, "Upgrade failed");
            Assert.IsFalse(Directory.Exists(Path.Combine(testDirPath, "withattachments/attachments")), "Failed to remove old attachments dir");
            Assert.IsTrue(Directory.Exists(db.AttachmentStorePath), "Failed to create new attachments dir");
        }
Beispiel #15
0
        /// <summary>
        /// Opens the named <see cref="EntityDatabase"/>, creating one if it doesn't exist.
        /// </summary>
        /// <param name="manager">The database manager.</param>
        /// <param name="name">The database name.</param>
        /// <returns>The <see cref="EntityDatabase"/>.</returns>
        public static EntityDatabase GetEntityDatabase(this Manager manager, string name)
        {
            Covenant.Requires <ArgumentNullException>(!string.IsNullOrEmpty(name));

            return(EntityDatabase.From(manager.GetDatabase(name)));
        }
Beispiel #16
0
		/// <summary>
		/// Make sure that a database's map/reduce functions are shared with the shadow database instance
		/// running in the background server.
		/// </summary>
		/// <remarks>
		/// Make sure that a database's map/reduce functions are shared with the shadow database instance
		/// running in the background server.
		/// </remarks>
		/// <exception cref="System.Exception"></exception>
		public virtual void TestSharedMapBlocks()
		{
			Manager mgr = new Manager(new FilePath(GetRootDirectory(), "API_SharedMapBlocks")
				, Manager.DefaultOptions);
			Database db = mgr.GetDatabase("db");
			db.Open();
			db.SetFilter("phil", new _ReplicationFilter_931());
			db.SetValidation("val", new _Validator_938());
			View view = db.GetView("view");
			bool ok = view.SetMapReduce(new _Mapper_945(), new _Reducer_950(), "1");
			NUnit.Framework.Assert.IsNotNull("Couldn't set map/reduce", ok);
			Mapper map = view.GetMap();
			Reducer reduce = view.GetReduce();
			ReplicationFilter filter = db.GetFilter("phil");
			Validator validation = db.GetValidation("val");
			Future result = mgr.RunAsync("db", new _AsyncTask_965(filter, validation, map, reduce
				));
			result.Get();
			// blocks until async task has run
			db.Close();
			mgr.Close();
		}
Beispiel #17
0
 public override IDisposable OpenDB()
 {
     var manager = new Manager(new DirectoryInfo(this.Path), ManagerOptions.Default);
     manager.StorageType = "ForestDB";
     return this.db = manager.GetDatabase("cbdb");
 }
        private static Replication SetupReplication(Manager manager, bool continuous, bool createTarget,
            Uri remoteUri, bool isPull, string user, string password)
        {
            if (remoteUri == null) {
                return null;
            }

            var databaseName = remoteUri.Segments.Last();
            var authenticator = default(IAuthenticator);
            if (user != null && password != null) {
                Logger.I("Listener", "Setting session credentials for user '{0}'", user);
                authenticator = AuthenticatorFactory.CreateBasicAuthenticator(user, password);
            }

            if (isPull) {
                Logger.I("Listener", "Pulling from <{0}> --> {1}", remoteUri, databaseName);
            } else {
                Logger.I("Listener", "Pushing {0} --> <{1}>", databaseName, remoteUri);
            }

            var db = manager.GetExistingDatabase(databaseName);
            if (isPull && db == null) {
                db = manager.GetDatabase(databaseName);
            }

            if (db == null) {
                Logger.E("Listener", "Couldn't open database {0}", databaseName);
                return null;
            }

            var repl = isPull ? db.CreatePullReplication(remoteUri) : db.CreatePushReplication(remoteUri);
            repl.Continuous = continuous;
            repl.CreateTarget = createTarget;
            repl.Authenticator = authenticator;
            repl.Changed += (sender, e) => 
            {
                Logger.I("Listener", "*** Replicator status changed ({0} {1}/{2}) ***", e.Status, e.CompletedChangesCount,
                    e.ChangesCount);
                if(e.LastError != null) {
                    Logger.W("Listener", "*** Replicator reported error ***", e);
                } else if(e.Status == ReplicationStatus.Stopped) {
                    Logger.I("Listener", "*** Replicator finished ***");
                }
            };

            repl.Start();
            return repl;
        }
        public CouchbaseLiteFacade()
        {
            _manager = Manager.SharedInstance;

            _database = _manager.GetDatabase(DB_NAME + DateTime.Now.GetHashCode());
        }
        private void InitializeDatabase()
        {
            {
                Debug.WriteLine("Initializeing CouchbaseLite");
                try
                {
                    Log.SetDefaultLoggerWithLevel(SourceLevels.Verbose);

                    _dbPath = new DirectoryInfo(Environment.CurrentDirectory);
                    Log.I(TAG, "Creating manager in " + _dbPath);
                    Debug.WriteLine("Creating manager in " + _dbPath);

                    _manager = new Manager(_dbPath, ManagerOptions.Default);
                    Debug.WriteLine("Creating database " + DB_NAME);
                    Log.I(TAG, "Creating database " + DB_NAME);

                    _database = _manager.GetDatabase(DB_NAME);

                }
                catch (Exception ex)
                {
                    var msg = "Could not load database in path " + _dbPath.ToString();
                    MessageBox.Show(msg);
                }
            }
        }
 public SimpleModel(Manager manager, string dbName)
 {
     _db = manager.GetDatabase(dbName);
 }
Beispiel #22
0
		/// <exception cref="System.Exception"></exception>
		public virtual void TestChangeUUID()
		{
			Manager mgr = new Manager(new FilePath(GetRootDirectory(), "ChangeUUID"), Manager
				.DefaultOptions);
			Database db = mgr.GetDatabase("db");
			db.Open();
			string pub = db.PublicUUID();
			string priv = db.PrivateUUID();
			NUnit.Framework.Assert.IsTrue(pub.Length > 10);
			NUnit.Framework.Assert.IsTrue(priv.Length > 10);
			NUnit.Framework.Assert.IsTrue("replaceUUIDs failed", db.ReplaceUUIDs());
			NUnit.Framework.Assert.IsFalse(pub.Equals(db.PublicUUID()));
			NUnit.Framework.Assert.IsFalse(priv.Equals(db.PrivateUUID()));
			mgr.Close();
		}
Beispiel #23
0
        //SERVER & DOCUMENTS
        /// <exception cref="System.IO.IOException"></exception>
       // [Test]
        public void TestAPIManager()
        {
            Manager manager = this.manager;
            Assert.IsTrue(manager != null);

            foreach (string dbName in manager.AllDatabaseNames)
            {
                Database db = manager.GetDatabase(dbName);
                Log.I(Tag, "Database '" + dbName + "':" + db.DocumentCount + " documents");
            }

            var options = new ManagerOptions();
            options.ReadOnly = true;
            options.CallbackScheduler = new SingleTaskThreadpoolScheduler();

            var roManager = new Manager(new DirectoryInfo(manager.Directory), options);
            Assert.IsTrue(roManager != null);

            var nonExistantDatabase = roManager.GetDatabase("foo");
            Assert.IsNull(nonExistantDatabase);

            var dbNames = manager.AllDatabaseNames;
            Assert.IsFalse(dbNames.Contains<String>("foo"));
            Assert.IsTrue(dbNames.Contains(DefaultTestDb));
        }
Beispiel #24
0
        public void TestSharedMapBlocks()
        {
            var path = new DirectoryInfo(Path.Combine(RootDirectory.FullName, "API_SharedMapBlocks"));
            var mgr = new Manager(path, Manager.DefaultOptions);
            var db = mgr.GetDatabase("db");

            db.Open();
            db.SetFilter("phil", (r, p) => true);
            db.SetValidation("val", (p1, p2) => true);

            var view = db.GetView("view");
            var ok = view.SetMapReduce((p1, p2)=>{ return; }, (a, b, c) => { return null; }, "1");

            Assert.IsNotNull(ok, "Couldn't set map/reduce");

            var map = view.Map;
            var reduce = view.Reduce;
            var filter = db.GetFilter("phil");
            var validation = db.GetValidation("val");
            var result = mgr.RunAsync("db", (database)=>
                {
                    Assert.IsNotNull(database);
                    var serverView = database.GetExistingView("view");
                    Assert.IsNotNull(serverView);
                    Assert.AreEqual(database.GetFilter("phil"), filter);
                    Assert.AreEqual(database.GetValidation("val"), validation);
                    Assert.AreEqual(serverView.Map, map);
                    Assert.AreEqual(serverView.Reduce, reduce);
                    return true;
                });
            result.Wait(TimeSpan.FromSeconds(5));
            // blocks until async task has run
            db.Close();
            mgr.Close();
        }
        public void Test09LoadDB()
        {
            RunTest("Test09LoadDB", (parameters) =>
            {
                var numDocs = Convert.ToInt32(parameters[NUMDOCS_KEY]);
                var docSize = Convert.ToInt32(parameters[DOCSIZE_KEY]);

                var docs = new Document[numDocs];
                database.RunInTransaction(() =>
                {
                    var props = CreateTestProperties(docSize);
                    for (var i = 0; i < docs.Length; i++)
                    {
                        var doc = database.CreateDocument();
                        doc.PutProperties(props);
                        docs[i] = doc;
                    }

                    return true;
                });

                var stopwatch = Stopwatch.StartNew();

                database.Close();
                manager.Close();

                var path = new DirectoryInfo(GetServerPath() + "/tests");
                manager = new Manager(path, Manager.DefaultOptions);
                database = manager.GetDatabase(DefaultTestDb);

                stopwatch.Stop();

                return stopwatch.ElapsedMilliseconds;
            });
        }
Beispiel #26
0
        public static void Main(string[] args)
        {
            var timeoutStr = "90000";
            var options = new OptionSet() {
                { "push", "push replication", v => _isPush = v == "push" },
                { "pull", "pull replication", v => _isPull = v == "pull" },
                { "f|file=",  "CBLite file path", v =>
                    _path = v },
                { "u|url=",  "URL to replicate with", v => _url = v },
                { "t|timeout=", "Set the timeout for HTTP requests in milliseconds (default is 90000)", v => timeoutStr = v },
                { "h|help",  "show this message and exit", v => _showHelp = v != null },

            };

            List<string> extra;
            try {
                extra = options.Parse(args);
                if (extra.Count == 1)
                {
                    // Should be just a file path. Will validate below.
                    _path = extra[0];
                }
            } catch (OptionException e) {
                Console.Write("cbreplicate: ");
                OutputUsingColor(
                    color: ConsoleColor.Red,
                    format: e.Message
                );
                Console.WriteLine();
                Console.WriteLine("Try `cbreplicate --help' for more information.");
                Environment.ExitCode = (int)Exit.InvalidOptions;
                return;
            }

            if (_showHelp || args.Length == 0) {
                var writer = new StringWriter(new StringBuilder("usage: cb-replicate [options] [file path]" + Environment.NewLine + Environment.NewLine));
                options.WriteOptionDescriptions(writer);

                _helpText = writer.ToString();

                writer.Close();

                ShowHelp();
                return;
            }

            int timeout;
            if(Int32.TryParse(timeoutStr, out timeout)) {
                Manager.DefaultOptions.RequestTimeout = TimeSpan.FromMilliseconds(timeout);
            }

            if (String.IsNullOrWhiteSpace(_path)) {
                OutputUsingColor(
                    color: ConsoleColor.Red,
                    format: "The path to the database was empty text or all whitespace.{0}",
                    args: Environment.NewLine
                );
                ShowHelp();
                Environment.ExitCode = (int)Exit.PathIsNullOrEmpty;
                return;
            }

            FileInfo file;
            if (!File.Exists(_path)) {
                // See if they gave us a relative path.
                _path = Path.Combine(Environment.CurrentDirectory, _path);
                if (!File.Exists(_path) && _isPush) {
                    OutputUsingColor(
                        color: ConsoleColor.Red,
                        format: "The path {0} is not valid. A valid CBLite database is required for push replication",
                        args: _path
                    );
                    Environment.ExitCode = (int)Exit.PathDoesNotExist;
                    return;
                }
            }

            file = new FileInfo(_path);

            var man = new Manager(file.Directory, Manager.DefaultOptions);

            try
            {
                _db = _isPull ? man.GetDatabase(file.Name.Split('.')[0]) : man.GetExistingDatabase(file.Name.Split('.')[0]);
            }
            catch (Exception ex)
            {
                OutputUsingColor(
                    color: ConsoleColor.Red,
                    format: "Error opening the database: {0}{1}",
                    args: new[] { ex.Message, Environment.NewLine }
                );
                Environment.ExitCode = (int)Exit.CannotOpenDatabase;
                return;
            }

            if (_db == null)
            {
                OutputUsingColor(
                    color: ConsoleColor.Red,
                    format: "No CBLite db found at '{0}'. Push replication requires and existing CBLite database.",
                    args: _path
                );
                Environment.ExitCode = (int)Exit.PathDoesNotExist;
                return;
            }

            if (_isPush)
            {
                try
                {
                    Push();
                }
                catch (Exception ex)
                {
                    OutputUsingColor(
                        color: ConsoleColor.Red,
                        format: "Unhandled exception during push replication: {0}",
                        args: ex.Message
                    );
                    Environment.ExitCode = (int)Exit.UnhandledException;
                    return;
                }
            }
            else if (_isPull)
            {
                try
                {
                    Pull();
                }
                catch (Exception ex)
                {
                    OutputUsingColor(
                        color: ConsoleColor.Red,
                        format: "Unhandled exception during pull replication: {0}",
                        args: ex.Message
                    );
                    Environment.ExitCode = (int)Exit.UnhandledException;
                    return;
                }
            }

            bool doneWaiting;

            Console.CancelKeyPress += (sender, e) => {
                if (e.Cancel) {
                    _done = _mre.Set();
                }
            };

            do {
                doneWaiting = _mre.WaitOne(100);
            } while(!_done || !doneWaiting);
        }
Beispiel #27
0
    void Start()
    {
        DontDestroyOnLoad(this);
        if (FindObjectsOfType(GetType()).Length > 1)
        {
            Destroy(gameObject);
            return;
        }
        manager = Manager.SharedInstance;
        db = manager.GetDatabase(Constants.DB_NAME);
        db.Changed += (sender, e) => {
            var changes = e.Changes.ToList();
            foreach (DocumentChange change in changes) {
                print("Document " + change.DocumentId + " changed");
            }
        };

        // initialize views
        // account username-password
        View viewAccount = db.GetView(Constants.DB_TYPE_ACCOUNT);
        viewAccount.SetMap ((doc, emit) => {
            if(doc[Constants.DB_KEYWORD_TYPE].ToString () == Constants.DB_TYPE_ACCOUNT)
                emit(doc[Constants.DB_KEYWORD_USERNAME], doc[Constants.DB_KEYWORD_PASSWORD]);
        }, "1");

        // initialize database, use Unity inspector to change value in GameManager
        if (GameManager.Instance.initializeDatabase) {
            InitializeDatabase();
        }
    }