Esempio n. 1
0
        private Database TestEncryptedBlobsInternal(string password)
        {
            var seekrit = OpenSeekrit(password);
            var body    = Encoding.UTF8.GetBytes("This is a blob!");
            var blob    = new Blob("text/plain", body);

            using (var doc = new MutableDocument("att")) {
                doc.SetBlob("blob", blob);
                seekrit.Save(doc);

                blob = doc.GetBlob("blob");
                blob.Digest.Should().NotBeNull();

                var fileName = blob.Digest.Substring(5).Replace("/", "_");
                var path     = $"{seekrit.Path}Attachments{Path.DirectorySeparatorChar}{fileName}.blob";
                var raw      = File.ReadAllBytes(path);
                if (password != null)
                {
                    raw.Should().NotBeEquivalentTo(body, "because otherwise the attachment was not encrypted");
                }
                else
                {
                    raw.Should().BeEquivalentTo(body, "because otherwise the attachment was encrypted");
                }
            }

            using (var savedDoc = seekrit.GetDocument("att")) {
                blob = savedDoc.GetBlob("blob");
                blob.Digest.Should().NotBeNull();
                var content = Encoding.UTF8.GetString(blob.Content);
                content.Should().Be("This is a blob!");
            }

            return(seekrit);
        }
Esempio n. 2
0
        public bool SaveUserProfile(UserProfile userProfile)
        {
            try
            {
                if (userProfile != null)
                {
                    var mutableDocument = new MutableDocument(userProfile.Id);
                    mutableDocument.SetString("Name", userProfile.Name);
                    mutableDocument.SetString("Email", userProfile.Email);
                    mutableDocument.SetString("Address", userProfile.Address);

                    if (userProfile.ImageData != null)
                    {
                        mutableDocument.SetBlob("ImageData", new Blob("image/jpeg", userProfile.ImageData));
                    }

                    Database.Save(mutableDocument);

                    return(true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"UserProfileRepository Exception: {ex.Message}");
            }

            return(false);
        }
        private Document StoreBlob(Database db, MutableDocument doc, byte[] content)
        {
            var blob = new Blob("text/plain", content);

            doc.SetBlob("data", blob);
            return(Db.Save(doc));
        }
        public void TestCopy()
        {
            for (int i = 0; i < 10; i++)
            {
                var docID = $"doc{i}";
                using (var doc = new MutableDocument(docID)) {
                    doc.SetString("name", docID);

                    var data = Encoding.UTF8.GetBytes(docID);
                    var blob = new Blob("text/plain", data);
                    doc.SetBlob("data", blob);

                    Db.Save(doc);
                }
            }

            var dbName = "nudb";
            var config = Db.Config;
            var dir    = config.Directory;

            Database.Delete(dbName, dir);
            Database.Copy(Db.Path, dbName, config);

            Database.Exists(dbName, dir).Should().BeTrue();
            using (var nudb = new Database(dbName, config)) {
                nudb.Count.Should().Be(10, "because it is a copy of another database with 10 items");
                var DOCID   = Meta.ID;
                var S_DOCID = SelectResult.Expression(DOCID);
                using (var q = QueryBuilder.Select(S_DOCID).From(DataSource.Database(nudb))) {
                    var rs = q.Execute();
                    foreach (var r in rs)
                    {
                        var docID = r.GetString(0);
                        docID.Should().NotBeNull();

                        var doc = nudb.GetDocument(docID);
                        doc.Should().NotBeNull();
                        doc.GetString("name").Should().Be(docID);

                        var blob = doc.GetBlob("data");
                        blob.Should().NotBeNull();

                        var data = Encoding.UTF8.GetString(blob.Content);
                        data.Should().Be(docID);
                    }
                }
            }

            Database.Delete(dbName, dir);
        }
Esempio n. 5
0
        private static void UseBlob()
        {
            var db = _Database;

            using (var newTask = new MutableDocument()) {
                // # tag::blob[]
                // Note: Reading the data is implementation dependent, as with prebuilt databases
                var image = File.ReadAllBytes("avatar.jpg");
                var blob  = new Blob("image/jpeg", image);
                newTask.SetBlob("avatar", blob);
                db.Save(newTask);
                // # end::blob[]

                var taskBlob = newTask.GetBlob("avatar");
                using (var bitmap = SKBitmap.Decode(taskBlob.ContentStream)) {
                    Console.WriteLine($"Bitmap dimensions: {bitmap.Width} x {bitmap.Height} ({bitmap.BytesPerPixel} bytes per pixel)");
                }
            }
        }
Esempio n. 6
0
        public void TestDocumentBlobToJSON()
        {
            var blob = ArrayTestBlob();

            using (var md = new MutableDocument("doc1")) {
                md.SetBlob("blob", blob);
                Db.Save(md);
            }

            using (var d = Db.GetDocument("doc1")) {
                var b            = d.GetBlob("blob");
                var json         = b.ToJSON();
                var blobFromJson = JsonConvert.DeserializeObject <Dictionary <string, object> >(json);
                blobFromJson.ContainsKey(Blob.ContentTypeKey).Should().BeTrue();
                blobFromJson.ContainsKey(Blob.DigestKey).Should().BeTrue();
                blobFromJson.ContainsKey(Blob.LengthKey).Should().BeTrue();
                blobFromJson.ContainsKey(Constants.ObjectTypeProperty).Should().BeTrue();
            }
        }
Esempio n. 7
0
        public void TestGetContent6MBFile()
        {
            byte[] bytes = null;
            using (var stream = typeof(BlobTest).GetTypeInfo().Assembly.GetManifestResourceStream("iTunesMusicLibrary.json"))
                using (var sr = new BinaryReader(stream)) {
                    bytes = sr.ReadBytes((int)stream.Length);
                }

            var blob = new Blob("application/json", bytes);

            using (var mDoc = new MutableDocument("doc1")) {
                mDoc.SetBlob("blob", blob);
                using (var doc = Db.Save(mDoc)) {
                    var savedBlob = doc.GetBlob("blob");
                    savedBlob.Should().NotBeNull();
                    savedBlob.ContentType.Should().Be("application/json");
                    savedBlob.Content.Should().Equal(bytes);
                }
            }
        }
Esempio n. 8
0
        public void TestGetContent()
        {
            byte[] bytes = null;
            using (var stream = typeof(BlobTest).GetTypeInfo().Assembly.GetManifestResourceStream("attachment.png"))
                using (var sr = new BinaryReader(stream)) {
                    bytes = sr.ReadBytes((int)stream.Length);
                }

            var blob = new Blob("image/png", bytes);

            using (var mDoc = new MutableDocument("doc1")) {
                mDoc.SetBlob("blob", blob);
                Db.Save(mDoc);
                using (var doc = Db.GetDocument(mDoc.Id)) {
                    var savedBlob = doc.GetBlob("blob");
                    savedBlob.Should().NotBeNull();
                    savedBlob.ContentType.Should().Be("image/png");
                    savedBlob.Content.Should().Equal(bytes);
                }
            }
        }
        public void TestQueryWithBlobProperty()
        {
            var texts = new[]
            {
                "Knox on fox in socks in box.  Socks on Knox and Knox in box.",
                "Clocks on fix tick. Clocks on Knox tock. Six sick bricks tick.  Six sick chicks tock."
            };

            foreach (var text in texts)
            {
                using (var doc = new MutableDocument()) {
                    doc.SetBlob("text", new Blob("text/plain", Encoding.UTF8.GetBytes(text)));
                    SaveDocument(doc);
                }
            }

            var textModel = new TextModel();

            textModel.RegisterModel();

            var input      = TextModel.CreateInput("text");
            var prediction = Function.Prediction(textModel.Name, input).Property("wc");

            using (var q = QueryBuilder
                           .Select(SelectResult.Property("text"), SelectResult.Expression(prediction).As("wc"))
                           .From(DataSource.Database(Db))
                           .Where(prediction.GreaterThan(Expression.Int(15)))) {
                foreach (var row in q.Execute())
                {
                    WriteLine(row.GetInt("wc").ToString());
                }
            }

            textModel.ContentType.Should().Be("text/plain");
            Database.Prediction.UnregisterModel(textModel.Name);
        }
Esempio n. 10
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();
        }