Ejemplo n.º 1
0
        private MutableDocument CreateDocumentWithTag(string id, string tag)
        {
            var doc = new MutableDocument(id);

            doc.SetString("tag", tag);

            doc.SetString("firstName", "Daniel");
            doc.SetString("lastName", "Tiger");

            var address = new MutableDictionary();

            address.SetString("street", "1 Main street");
            address.SetString("city", "Mountain View");
            address.SetString("state", "CA");
            doc.SetDictionary("address", address);

            var phones = new MutableArray();

            phones.AddString("650-123-0001").AddString("650-123-0002");
            doc.SetArray("phones", phones);

            doc.SetDate("updated", DateTimeOffset.UtcNow);

            return(doc);
        }
        private void SetDocument(T entity, MutableDocument mutableDocument)
        {
            var properties = ObjectToDictionaryHelper.ToDictionary(entity);

            foreach (var prop in properties)
            {
                if (prop.Value is int)
                {
                    mutableDocument.SetInt(prop.Key, (int)prop.Value);
                }
                else if (prop.Value is long)
                {
                    mutableDocument.SetLong(prop.Key, (long)prop.Value);
                }
                else if (prop.Value is bool)
                {
                    mutableDocument.SetBoolean(prop.Key, (bool)prop.Value);
                }
                else if (prop.Value is DateTimeOffset)
                {
                    if ((DateTimeOffset)prop.Value != default(DateTimeOffset))
                    {
                        mutableDocument.SetDate(prop.Key, (DateTimeOffset)prop.Value);
                    }
                }
                else if (prop.Value is double)
                {
                    mutableDocument.SetDouble(prop.Key, (double)prop.Value);
                }
                else if (prop.Value is float)
                {
                    mutableDocument.SetFloat(prop.Key, (float)prop.Value);
                }
                else if (prop.Value is string)
                {
                    mutableDocument.SetString(prop.Key, (string)prop.Value);
                }
                else
                {
                    mutableDocument.SetValue(prop.Key, prop.Value);
                }
            }
        }
Ejemplo n.º 3
0
        public void TestGetFragmentFromDate()
        {
            var date = DateTimeOffset.Now;
            var doc  = new MutableDocument("doc1");

            doc.SetDate("date", date);
            SaveDocument(doc, d =>
            {
                var fragment = d["date"];
                fragment.Exists.Should().BeTrue("because this portion of the data exists");
                fragment.String.Should().NotBeNull("because this fragment is convertible to string");
                fragment.Array.Should().BeNull("because this fragment is not of this type");
                fragment.Dictionary.Should().BeNull("because this fragment is not of this type");
                fragment.Int.Should().Be(0, "because that is the default value");
                fragment.Long.Should().Be(0L, "because that is the default value");
                fragment.Double.Should().Be(0.0, "because that is the default value");
                fragment.Float.Should().Be(0.0f, "because that is the default value");
                fragment.Boolean.Should().Be(true, "because that is the non-zero value");
                fragment.Date.Should().Be(date, "because that is the stored value");
                fragment.Value.Should().NotBeNull("because this fragment has a value");
            });
        }
Ejemplo n.º 4
0
        private void UpdateDoc(MutableDocument doc, int rounds, string tag)
        {
            for (var i = 1; i <= rounds; i++)
            {
                doc.SetInt("update", i);
                doc.SetString("tag", tag);

                var address = doc.GetDictionary("address");
                address.Should().NotBeNull();
                var street = $"{i} street.";
                address.SetString("street", street);

                var phones = doc.GetArray("phones");
                phones.Should().NotBeNull();
                phones.Count.Should().Be(2);
                var phone = $"650-000-{i:D4}";
                phones.SetString(0, phone);

                doc.SetDate("updated", DateTimeOffset.UtcNow);

                Db.Save(doc).Dispose();
            }
        }
Ejemplo n.º 5
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();

            // create database
            var config = new DatabaseConfiguration();

            config.ConflictResolver = new ExampleConflictResolver();
            var database = new Database("my-database", config);

            // create document
            var newTask = new MutableDocument();

            newTask.SetString("type", "task");
            newTask.SetString("owner", "todo");
            newTask.SetDate("createdAt", DateTimeOffset.UtcNow);
            newTask = database.Save(newTask).ToMutable();

            // mutate document
            newTask.SetString("name", "Apples");
            newTask = database.Save(newTask).ToMutable();

            // typed accessors
            newTask.SetDate("createdAt", DateTimeOffset.UtcNow);
            var date = newTask.GetDate("createdAt");

            // database transaction
            database.InBatch(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    using (var doc = new MutableDocument()) {
                        doc.SetString("type", "user");
                        doc.SetString("name", $"user {i}");
                        using (var saved = database.Save(doc)) {
                            Console.WriteLine($"saved user document {saved.GetString("name")}");
                        }
                    }
                }
            });

            // blob
            var bytes = File.ReadAllBytes("avatar.jpg");
            var blob  = new Blob("image/jpg", bytes);

            newTask.SetBlob("avatar", blob);
            newTask = database.Save(newTask).ToMutable();
            var taskBlob = newTask.GetBlob("avatar");
            var data     = taskBlob.Content;

            newTask.Dispose();

            // query
            var query = QueryBuilder.Select(SelectResult.Expression(Meta.ID))
                        .From(DataSource.Database(database))
                        .Where(Expression.Property("type").EqualTo(Expression.String("user"))
                               .And(Expression.Property("admin").EqualTo(Expression.Boolean(false))));

            var rows = query.Execute();

            foreach (var row in rows)
            {
                Console.WriteLine($"doc ID :: ${row.GetString(0)}");
            }


            // live query
            query.AddChangeListener((sender, e) => {
                Console.WriteLine($"Number of rows :: {e.Results.Count()}");
            });

            using (var newDoc = new MutableDocument()) {
                newDoc.SetString("type", "user");
                newDoc.SetBoolean("admin", false);
                database.Save(newDoc);
            }

            // fts example
            // insert documents
            var tasks = new[] { "buy groceries", "play chess", "book travels", "buy museum tickets" };

            foreach (string task in tasks)
            {
                using (var doc = new MutableDocument()) {
                    doc.SetString("type", "task").SetString("name", task); // Chaining is possible
                    database.Save(doc);
                }
            }

            // create Index
            var index = IndexBuilder.FullTextIndex(FullTextIndexItem.Property("name"));

            database.CreateIndex("byName", index);

            using (var ftsQuery = QueryBuilder.Select(SelectResult.Expression(Meta.ID).As("id"))
                                  .From(DataSource.Database(database))
                                  .Where(FullTextExpression.Index("byName").Match("'buy'"))) {
                var ftsRows = ftsQuery.Execute();
                foreach (var row in ftsRows)
                {
                    var doc = database.GetDocument(row.GetString("id")); // Use alias instead of index
                    Console.WriteLine(
                        $"document properties {JsonConvert.SerializeObject(doc.ToDictionary(), Formatting.Indented)}");
                }
            }

            // create conflict

            /*
             * 1. Create a document twice with the same ID (the document will have two conflicting revisions).
             * 2. Upon saving the second revision, the ExampleConflictResolver's resolve method is called.
             * The `theirs` ReadOnlyDocument in the conflict resolver represents the current rev and `mine` is what's being saved.
             * 3. Read the document after the second save operation and verify its property is as expected.
             * The conflict resolver will have deleted the obsolete revision.
             */
            using (var theirs = new MutableDocument("buzz"))
                using (var mine = new MutableDocument("buzz")) {
                    theirs.SetString("status", "theirs");
                    mine.SetString("status", "mine");
                    database.Save(theirs);
                    database.Save(mine);
                }

            var conflictResolverResult = database.GetDocument("buzz");

            Console.WriteLine($"conflictResolverResult doc.status ::: {conflictResolverResult.GetString("status")}");

            // replication (Note: Linux / Mac requires .NET Core 2.0+ due to
            // https://github.com/dotnet/corefx/issues/8768)

            /*
             * Tested with SG 1.5 https://www.couchbase.com/downloads
             * Config file:
             * {
             *        "databases": {
             *          "db": {
             *            "server":"walrus:",
             *            "users": {
             *              "GUEST": {"disabled": false, "admin_channels": ["*"]}
             *            },
             *            "unsupported": {
             *              "replicator_2":true
             *            }
             *          }
             *        }
             *      }
             */
            var url         = new Uri("ws://localhost:4984/db");
            var replConfig  = new ReplicatorConfiguration(database, new URLEndpoint(url));
            var replication = new Replicator(replConfig);

            replication.Start();

            // replication change listener
            replication.AddChangeListener((sender, e) => {
                if (e.Status.Activity == ReplicatorActivityLevel.Stopped)
                {
                    Console.WriteLine("Replication has completed.");
                }
            });

            Console.ReadLine();

            // This is important to do because otherwise the native connection
            // won't be released until the next garbage collection
            query.Dispose();
            database.Dispose();
        }