Quickstart in Couchbase with C# and ASP.NET

  • Learn to build a REST API with Couchbase’s C# SDK 3.4 and ASP.NET
  • See how you can fetch data from Couchbase using SQL++ queries
  • Explore CRUD operations in action with Couchbase

In questo tutorial imparerai come connetterti a un cluster di Couchbase Capella per creare, leggere, aggiornare e cancellare documenti e come scrivere semplici query SQL++ parametrizzate.

Prerequisiti

Per eseguire questo progetto preconfigurato, avrete bisogno di:

  • Couchbase Capella cluster with Travel-sample La carretta è carica.
    • Per eseguire questo tutorial utilizzando un cluster di Couchbase gestito autonomamente, si prega di consultare la documentazione relativa al comando appendice.
  • .NET SDK v6+ installed.
    • Ensure that the .Net version is compatibile con il SDK di Couchbase.
  • Code Editor installed (Visual Studio Professional, Visual Studio Code, or JetBrains Rider)
  • Loading Travel Sample Bucket

Configurazione di Couchbase Capella

Quando si esegue Couchbase utilizzando Capella, Per poter utilizzare questo servizio, è necessario soddisfare i seguenti requisiti preliminari.

  • L'applicazione richiede che il bucket dei campioni di viaggio sia caricato nel cluster della Capella UI.
  • Creare il credenziali del database per accedere al bucket travel-sample (Read e Write) utilizzato nell'applicazione.
  • Consenti l'accesso al cluster dal IP su cui è in esecuzione l'applicazione.

Configurazione dell'applicazione

We will walk through the different steps required to get the application running.

Cloning Repo

git clone https://github.com/couchbase-examples/aspnet-quickstart.git

Installare le dipendenze

cd src/Org.Quickstart.API
dotnet restore
Dependency Injection Nuget package

The Couchbase SDK for .NET includes a nuget package called Couchbase.Extensions.DependencyInjection which is designed for environments like ASP.NET that takes in a configuration to connect to Couchbase and automatically registers interfaces that you can use in your code to perform full CRUD (create, read, update, delete) operations and queries against the database.

Configurazione della database di configurazione

Per saperne di più su come connettersi al cluster Capella, si prega di seguire le istruzioni riportate nella pagina dedicata. istruzioni.

In particolare, è necessario fare quanto segue:

All configuration for communication with the database is stored in the appsettings.Development.json file. This includes the connection string, username, password, bucket name and scope name. The default username is assumed to be Administrator and the default password is assumed to be P@$$w0rd12. If these are different in your environment you will need to change them before running the application.

  "Couchbase": {
    "BucketName": "travel-sample",
    "ScopeName": "inventory",
    "ConnectionString": "couchbases://yourassignedhostname.cloud.couchbase.com",
    "Username": "Administrator",
    "Password": "P@ssw0rd12",
    "IgnoreRemoteCertificateNameMismatch": true,
    "HttpIgnoreRemoteCertificateMismatch": true,
    "KvIgnoreRemoteCertificateNameMismatch": true
  }

Nota: La stringa di connessione prevede couchbases:// o couchbase:// parte.

Running The Application

Directly on Machine

In questo momento abbiamo installato le dipendenze, caricato i dati del travel-sample e configurato l'applicazione con le credenziali. L'applicazione è ora pronta e potete lanciarla.

cd src/Org.Quickstart.API
dotnet run

Usare Docker

  • Creare l'immagine Docker
cd aspnet-quickstart
docker build -t couchbase-aspnet-quickstart . 
  • Run the docker image
cd aspnet-quickstart
docker run -e DB_CONN_STR=<connection_string> -e DB_USERNAME=<user_with_read_write_permission_to_travel-sample_bucket> -e DB_PASSWORD=<password_for_user> -p 8080:8080 couchbase-aspnet-quickstart

You can access the Application on http://localhost:8080/index.html

Verificare l'applicazione

Una volta avviata l'applicazione, è possibile visualizzare i dettagli dell'applicazione nei log.

Application Startup

L'applicazione verrà eseguita sul port 8080 della macchina locale (http://localhost:8080/index.html). You will find the Swagger documentation of the API if you go to the URL in your browser. Swagger documentation is used in this demo to showcase the different API end points and how they can be invoked. More details on the Swagger documentation can be found in the appendice.

Swagger Documentation

Modello dei dati

Per questo tutorial utilizzeremo tre collezioni:, aeroporto, aerolinea e itinerario che contengono rispettivamente aeroporti campione, compagnie aeree e rotte aeree. La raccolta di rotte collega gli aeroporti e le compagnie aeree come mostrato nella figura sottostante. Usiamo queste connessioni nel quickstart per generare aeroporti direttamente collegati e compagnie aeree che collegano un aeroporto di destinazione. Nota che questi sono solo esempi per evidenziare come è possibile utilizzare le query SQL++ per aggregare le collezioni.

img

Proviamo a rivedere il codice

Per iniziare questo tutorial, clonate il repo e apriamolo nell'IDE di vostra scelta. Ora potete imparare come creare, leggere, aggiornare e cancellare documenti in Couchbase Server.

Layout del codice

├── src
│   ├── Org.Quickstart.API
│   │   ├── Controllers
│   │   │   ├── AirlineController.cs
│   │   │   ├── AirportController.cs
│   │   │   └── RouteController.cs
│   │   ├── Models
│   │   │   ├── Airline.cs
│   │   │   ├── Airport.cs
│   │   │   └── Route.cs
│   │   ├── Properties
│   │   │   └── launchSettings.json
│   │   ├── Services
│   │   │   └── InventoryScopeService.cs
│   │   ├── Couchbase.TravelSample.csproj
│   │   ├── Program.cs
│   │   └── appsettings.Development.json
│   └── Org.Quickstart.IntegrationTests
│       ├── ControllerTests
│       │   ├── AirlineTests.cs
│       │   ├── AirportTests.cs
│       │   └── RouteTests.cs  
│       └── Org.Quickstart.IntegrationTests.csproj
├── Org.Quickstart.sln
└── Dockerfile

Org.Quickstart.API.Program:

In order to use the Couchbase.Extensions.DependencyInjection framework, we must first register the service. The Couchbase Services requires the database configuration information, which can be provided by reading the database configuration from the appsettings.Development.json file.

// Register the configuration for Couchbase and Dependency Injection Framework
 builder.Services.Configure<CouchbaseConfig>(config);
 builder.Services.AddCouchbase(config);

The services are added to the DI container. CORS policy is defined to allow specific origins. HttpClient, Controllers, Endpoints API Explorer, and Swagger are also added here. The Swagger setup includes a detailed description of the API.

builder.Services.AddCors(options =>
{
    // ...
});

builder.Services.AddHttpClient();
builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    // ...
});

The InventoryScopeService is registered as a singleton service in the DI container.

builder.Services.AddSingleton<IInventoryScopeService, InventoryScopeService>();

ASP.NET has an interface called IHostApplicationLifetime that you can add to your Configure method to help with registration of lifetime events. The Couchbase SDK provides the ICouchbaseLifetimeService interface for handling closing the database connections when the application closes. It’s best practice to register for the ASP.NET ApplicationStop lifetime event and call the ICouchbaseLifetimeService Close method so that the database connection and resources are closed and removed gracefully. The program logs the Swagger UI address when the application starts.

var lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();

lifetime.ApplicationStarted.Register(() =>
{
    // ...
});

app.Lifetime.ApplicationStopped.Register(() =>
{
    var cls = app.Services.GetRequiredService<ICouchbaseLifetimeService>();
    cls.Close();
});

The program sets up the middleware pipeline for the application. This includes Swagger, CORS, HTTPS redirection, routing, authorization, and endpoint mapping.

app.UseSwagger();
app.UseSwaggerUI(c => {
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Couchbase Quickstart API v1"); 
    c.RoutePrefix = string.Empty;
});

if (app.Environment.EnvironmentName == "Testing")
{
    app.UseCors("_devAllowSpecificOrigins");
}

app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

The Couchbase .NET SDK will handle all communications to the database cluster, so you shouldn’t need to worry about creating a pool of connections.

This InventoryScopeService class is a service that provides a convenient way to fetch a specific scope from a specific bucket, handling all the necessary validation and error checking.

Entità aeroportuale

For this tutorial, we will focus on the airport entity. The other entities are similar.

Stabiliremo un'API REST per gestire i documenti aeroportuali.

Per le operazioni CRUD utilizzeremo il Operazioni chiave-valore che sono integrate nel Couchbase SDK per creare, leggere, aggiornare e cancellare un documento. Ogni documento avrà bisogno di un ID (simile a una chiave primaria in altre database) per essere salvato nel database. Questo ID viene passato nell'URL. Per gli altri endpoint, utilizzeremo SQL++ per richiedere documenti.

Struttura dei documenti dell'aeroporto

Our airport document will have an airportname, city, country, faa code, icao code, timezone info and the geographic coordinates. For this demo, we will store all airport information in one document in the aeroporto raccolta nel Travel-sample bucket.

{
  "airportname": "Sample Airport",
  "city": "Sample City",
  "country": "United Kingdom",
  "faa": "SAA",
  "icao": "SAAA",
  "tz": "Europe/Paris",
  "geo": {
    "lat": 48.864716,
    "lon": 2.349014,
    "alt": 92
  }
}

Aeroporto POST

Apri AirportController.cs file and navigate to the Post metodo.

It takes an id and a richiesta as parameters, where id is the unique identifier for the airport and richiesta contains the data for the new airport. The method extracts the aeroporto object from the richiesta and attempts to insert it into the collection using the InsertAsync method of the Couchbase SDK. If the insertion is successful, it returns a Created result. However, if a document with the same id already exists in the collection, the method catches a DocumentExistsException and returns a Conflict result. For any other exceptions, it logs the error message and returns an InternalServerError result.

public async Task<IActionResult> Post(string id, AirportCreateRequestCommand request)
{
    try
    {
        var collection = await _inventoryScope.CollectionAsync(CollectionName);
        var airport = request.GetAirport();
        await collection.InsertAsync(id, airport);
        return Created($"/api/v1/airport/{id}", airport);
    }
    catch (DocumentExistsException)
    {
        return Conflict($"A document with the ID '{id}' already exists.");
    }
    catch (Exception ex)
    {
        _logger.LogError(ex.Message);
        return StatusCode(StatusCodes.Status500InternalServerError, $"Error: {ex.Message} {ex.StackTrace} {Request.GetDisplayUrl()}");
    }
}

GET Airport

Apri AirportController.cs file and navigate to the GetById metodo.

This method retrieves an airport document from a collection using its id. It uses the GetAsync method of the Couchbase SDK to fetch the document. If the document exists, it returns the document; otherwise, it returns a NotFound result. Any other exceptions are caught, logged, and an InternalServerError result is returned.

public async Task<IActionResult> GetById(string id)
{
    try
    {
        var collection = await _inventoryScope.CollectionAsync(CollectionName);
        var result = await collection.GetAsync(id);
        var resultAirport = result.ContentAs<Airport>();
        if (resultAirport != null)
        {
            return Ok(resultAirport);
        }
    }
    catch (DocumentNotFoundException)
    {
        return NotFound();
    }
    catch (Exception ex)
    {
        _logger.LogError(ex.Message);
        return StatusCode(StatusCodes.Status500InternalServerError, $"Error: {ex.Message} {ex.StackTrace} {Request.GetDisplayUrl()}");
    }
    return NotFound();
}

Aeroporto di PUT

Apri AirportController.cs file and navigate to the Update metodo.

This method is used to update an existing airport document in the collection. It uses the GetAsync e ReplaceAsync methods from the Couchbase SDK. If the document with the specified id exists, it replaces the document with the new data from the richiesta. If the document does not exist, it returns a NotFound result. Any other exceptions are caught, logged, and an InternalServerError result is returned.

public async Task<IActionResult> Update(string id, AirportCreateRequestCommand request)
{
    try
    {
        var collection = await _inventoryScope.CollectionAsync(CollectionName);
        if (await collection.GetAsync(id) is { } result)
        {
            result.ContentAs<Airport>();
            await collection.ReplaceAsync(id, request.GetAirport());
            return Ok(request);
        }
        else
        {
            return NotFound();
        }
    }
    catch (DocumentNotFoundException)
    {
        return NotFound();
    }
    catch (Exception ex)
    {
        _logger.LogError(ex.Message);
        return StatusCode(StatusCodes.Status500InternalServerError, $"Error: {ex.Message} {ex.StackTrace} {Request.GetDisplayUrl()}");
    }
    return NotFound();
}

DELETE Airport

Apri AirportController.cs file and navigate to the Delete metodo.

This method used to delete an existing airport document from a Couchbase collection. It uses the GetAsync e RemoveAsync methods from the Couchbase SDK. If the document with the specified id exists, it removes the document from the collection. If the document does not exist, it returns a NotFound result. Any other exceptions are caught, logged, and an InternalServerError result is returned.

public async Task<IActionResult> Delete(string id)
{
    try
    {
        var collection = await _inventoryScope.CollectionAsync(CollectionName);
        var result = await collection.GetAsync(id);
        var resultAirport = result.ContentAs<Airport>();
        if (resultAirport != null)
        {
            await collection.RemoveAsync(id);
            return Ok(id);
        }
        else
        {
            return NotFound();
        }
    }
    catch (DocumentNotFoundException)
    {
        return NotFound();
    }
    catch (Exception ex)
    {
        _logger.LogError(ex.Message);
        return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
    }
    return NotFound();
}

Lista aeroporti

Questo endpoint recupera l'elenco degli aeroporti presenti nel database. L'API offre la possibilità di specificare la dimensione della pagina dei risultati e il paese da cui estrarre i documenti relativi agli aeroporti.

SQL++ is a powerful query language based on SQL, but designed for structured and flexible JSON documents. We will use a SQL+ query to search for airports with Limit, Offset, and Country option.

Apri AirportController.cs file and navigate to the Delete method. This endpoint is different from the others we have seen before because it makes the SQL++ query rather than a key-value operation. This usually means more overhead because the query engine is involved. For this query, we are using the predefined indices in the Travel-sample bucket. Possiamo creare un altro indice specifico per questa query per renderla più efficiente.

We need to get the values from the query string for country, limit, and Offset that we will use in our query. These are pulled from the queryParameters.Parameter metodo.

Questo endpoint ha due query a seconda del valore del parametro Paese. Se viene specificato un nome di paese, recuperiamo i documenti relativi all’aeroporto per quel paese specifico. Se non viene specificato, recuperiamo l’elenco degli aeroporti di tutti i paesi. Le query sono leggermente diverse per questi due scenari.

Costruiamo la nostra query SQL++ utilizzando il parametri specificato da $ simbolo per entrambi questi scenari. La differenza tra le due query è la presenza del paese Il parametro nella query. Normalmente, per le query con la funzione di paginaazione, si consiglia di ordinare i risultati per mantenere l'ordine dei risultati in più query.

Successivamente passiamo oltre richiesta to the QueryAsync metodo. Salviamo i risultati in una lista, items.

This endpoint calls the QueryAsync metodo definito nel Ambito di applicazione tramite il SDK di Couchbase.

           
           var queryParameters = new Couchbase.Query.QueryOptions();
		   queryParameters.Parameter("limit", limit ?? 10);
		   queryParameters.Parameter("offset", offset ?? 0);

		   string query;
		   if (!string.IsNullOrEmpty(country))
		   {
			   query = $@"SELECT airport.airportname,
                          airport.city,
                          airport.country,
                          airport.faa,
                          airport.geo,
                          airport.icao,
                          airport.tz
                        FROM airport AS airport
                        WHERE lower(airport.country) = $country
                        ORDER BY airport.airportname
                        LIMIT $limit
                        OFFSET $offset";
                    
			   queryParameters.Parameter("country", country.ToLower());
		   }
		   else
		   {
			   query = $@"SELECT airport.airportname,
                              airport.city,
                              airport.country,
                              airport.faa,
                              airport.geo,
                              airport.icao,
                              airport.tz
                            FROM airport AS airport
                            ORDER BY airport.airportname
                            LIMIT $limit
                            OFFSET $offset";
		   }

		   var results = await _inventoryScope.QueryAsync<Airport>(query, queryParameters);
		   var items = await results.Rows.ToListAsync();

		   return items.Count == 0 ? NotFound() : Ok(items);

Connessioni dirette

This endpoint fetches the airports that can be reached directly from the specified source airport code. This also uses a SQL++ query to fetch the results similar to the List Airport endpoint.

Consideriamo la query utilizzata qui:

SELECT distinct (route.destinationairport)
DALLA STAZIONE AEROPORTUALE COME STAZIONE AEROPORTUALE
Inserire la rotta come percorso su route.sourceairport = airport.faa
WHERE $airport.faa = aeroporto e route.stops = 0
Ordine per percorso. Aeroporto di destinazione
LIMIT $limite
OFFSET $offset

Raccogliamo le connessioni dirette unendo la raccolta dell'aeroporto alla raccolta del percorso e filtrando in base all'aeroporto di origine specificato dall'utente e alle rotte senza fermate.

Running The Tests

We have defined integration tests using the xunit nuget package for all the API end points. The integration tests use the same database configuration as the application. For the integration tests, we perform the operation using the API and confirm the results by checking the documents in the database. For example, to check the creation of the document by the API, we would call the API to create the document and then read the same document from the database and compare them. After the tests, the documents are cleaned up by calling the DELETE endpoint

To run the standard integration tests, use the following commands:

cd ../Org.Quickstart.IntegrationTests/
dotnet restore 
dotnet build
dotnet test

Appendice

Ampliare l'API aggiungendo un'entità nuova

Se desiderate aggiungere un'altra entità alle API, i passaggi da seguire sono i seguenti:

  • Creare la nuova entità (collezione) nel bucket Couchbase. È possibile creare la collezione utilizzando il comando SDK o tramite il Interfaccia del server Couchbase.
  • Define the routes inside a new file in the Controllers folder similar to the existing ones like AirportController.cs.
  • Aggiungere i test per le nuove rotte in un nuovo file nel ControllerTests una cartella simile a AirportTests.cs.

Gestione automatica di un cluster di Couchbase

Se stai eseguendo questo quickstart con un cluster di Couchbase gestito autonomamente, è necessario caricare caricare i dati del bucket dei dati di viaggio nel cluster e generare le credenziali per il bucket.

È necessario aggiornare la stringa di connessione e le credenziali nel file appsettings.Development.json file nella cartella di origine.

NOTA: Couchbase must be installed and running prior to running the the ASP.NET app.

Documentazione Swagger

La documentazione di Swagger fornisce una panoramica chiara dell'API, includendo endpoint, metodi HTTP, parametri delle richieste e oggetti di risposta.

Fare clic su un singolo endpoint per ampliarlo e visualizzare le informazioni dettagliate. Ciò include la descrizione dell’endpoint, i possibili codici di stato delle risposte e i parametri della richiesta che esso accetta.

Testare l'API

È possibile provare un'API cliccando sul pulsante “Prova” accanto agli endpoint.

  • Parametri: Se un endpoint richiede parametri, l'interfaccia utente Swagger fornisce dei campi di input da compilare. Questi possono includere parametri di percorso, stringhe di query, intestazioni o il corpo di una richiesta POST/PUT.

  • Esecuzione: Una volta inseriti tutti i parametri necessari, è possibile cliccare sul pulsante “Esecuzione” per effettuare una chiamata API in tempo reale. L’interfaccia utente Swagger invierà la richiesta all’API e visualizzerà la risposta direttamente nella documentazione. Ciò include il codice della risposta, gli header e il corpo della risposta.

Modelli

Swagger documenta la struttura dei corpi di richiesta e risposta utilizzando modelli. Questi modelli definiscono la struttura dei dati prevista utilizzando lo schema JSON e sono estremamente utili per comprendere quali dati inviare e quali aspettarsi.

Lasciare la proliferazione dei database nel passato

Ogni aggiunta di stack significa un altro conto da gestire. Calcola in 2 minuti quanto puoi risparmiare.