public bool Upsert(BingoBall bingoBall)
        {
            var success = true;

            try
            {
                string targetBall = null;

                using (var query = QueryBuilder.Select(SelectResult.Expression(Meta.ID))
                                   .From(DataSource.Database(_database))
                                   .Where(Expression.Property("Name").EqualTo(Expression.String(bingoBall.Name))))
                {
                    var resultArray = query.Execute().ToArray();
                    if (resultArray.Length > 0)
                    {
                        targetBall = resultArray[0].GetValue(0)?.ToString();
                    }
                }

                if (targetBall == null)
                {
                    using var mutableDoc = new MutableDocument();

                    mutableDoc.SetString("Name", bingoBall.Name)
                    .SetBoolean("IsPlayed", false)
                    .SetBoolean("IsMatched", false)
                    .SetArray("PlayedBy", new MutableArrayObject())
                    .SetArray("MatchedBy", new MutableArrayObject());

                    _database.Save(mutableDoc);
                }
                else
                {
                    MutableDocument doc = _database.GetDocument(targetBall)?.ToMutable();
                    doc.SetBoolean("IsPlayed", bingoBall.IsPlayed);
                    doc.SetBoolean("IsMatched", bingoBall.IsMatched);
                    doc.SetArray("PlayedBy", new MutableArrayObject(bingoBall.PlayedBy));
                    doc.SetArray("MatchedBy", new MutableArrayObject(bingoBall.MatchedBy));

                    _database.Save(doc);
                }
            }
            catch (Exception e)
            {
                success = false;
            }
            return(success);
        }
        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);
                }
            }
        }
예제 #3
0
        private static void DoBatchOperation()
        {
            var db = _Database;

            // # tag::batch[]
            db.InBatch(() =>
            {
                for (var i = 0; i < 10; i++)
                {
                    using (var doc = new MutableDocument()) {
                        doc.SetString("type", "user");
                        doc.SetString("name", $"user {i}");
                        doc.SetBoolean("admin", false);
                        db.Save(doc);
                        Console.WriteLine($"Saved user document {doc.GetString("name")}");
                    }
                }
            });
            // # end::batch[]
        }
예제 #4
0
        public void TestGetFragmentFromBoolean()
        {
            var doc = new MutableDocument("doc1");

            doc.SetBoolean("boolean", true);
            SaveDocument(doc, d =>
            {
                var fragment = d["boolean"];
                fragment.Exists.Should().BeTrue("because this portion of the data exists");
                fragment.String.Should().BeNull("because this fragment is not of this type");
                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(1, "because that is the converted value");
                fragment.Long.Should().Be(1L, "because that is the converted value");
                fragment.Double.Should().Be(1.0, "because that is the converted value");
                fragment.Float.Should().Be(1.0f, "because that is the converted value");
                fragment.Boolean.Should().Be(true, "because that is the stored value");
                fragment.Date.Should().Be(DateTimeOffset.MinValue, "because that is the default value");
                fragment.Value.Should().NotBeNull("because this fragment has a value");
            });
        }
예제 #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();
        }