Build and Run
Description — Build and run a starter app to validate your install of Couchbase Lite on C#
Abstract — This content provides sample code and instructions that enable you to test your Couchbase Lite for csharp installation.
Starter code
Open Main.cs in Visual Studio and copy the following code in the main
method.
This snippet demonstrates how to run basic CRUD operations, a simple Query and running bi-directional replications with Sync Gateway.
// using System;
// using Couchbase.Lite;
// using Couchbase.Lite.Query;
// using Couchbase.Lite.Sync;
// Get the database (and create it if it doesn't exist)
var database = new Database("mydb");
// Create a new document (i.e. a record) in the database
string id = null;
using (var mutableDoc = new MutableDocument())
{
mutableDoc.SetFloat("version", 2.0f)
.SetString("type", "SDK");
// Save it to the database
database.Save(mutableDoc);
id = mutableDoc.Id;
}
// Update a document
using (var doc = database.GetDocument(id))
using (var mutableDoc = doc.ToMutable())
{
mutableDoc.SetString("language", "C#");
database.Save(mutableDoc);
using (var docAgain = database.GetDocument(id))
{
Console.WriteLine($"Document ID :: {docAgain.Id}");
Console.WriteLine($"Learning {docAgain.GetString("language")}");
}
}
// Create a query to fetch documents of type SDK
// i.e. SELECT * FROM database WHERE type = "SDK"
using (var query = QueryBuilder.Select(SelectResult.All())
.From(DataSource.Database(database))
.Where(Expression.Property("type").EqualTo(Expression.String("SDK"))))
{
// Run the query
var result = query.Execute();
Console.WriteLine($"Number of rows :: {result.AllResults().Count}");
}
// Create replicator to push and pull changes to and from the cloud
var targetEndpoint = new URLEndpoint(new Uri("ws://localhost:4984/getting-started-db"));
var replConfig = new ReplicatorConfiguration(database, targetEndpoint);
// Add authentication
replConfig.Authenticator = new BasicAuthenticator("john", "pass");
// Create replicator (make sure to add an instance or static variable
// named _Replicator)
var _Replicator = new Replicator(replConfig);
_Replicator.AddChangeListener((sender, args) =>
{
if (args.Status.Error != null)
{
Console.WriteLine($"Error :: {args.Status.Error}");
}
});
_Replicator.Start();
// Later, stop and dispose the replicator *before* closing/disposing the
}
Build and run. You should see the document ID and property printed to the console. The document was successfully persisted to the database.
See also — Install Sync Gateway