DEV Community

Morris Janatzek
Morris Janatzek

Posted on • Originally published at morrisj.net

How to synchronize data in realtime with Asp.Net Core and Angular

To easily create a realtime application I'm using SapphireDb. Check out the documentation to learn more: https://sapphire-db.com/

GitHub logo SapphireDb / SapphireDb

SapphireDb Server, a self-hosted, easy to use realtime database for Asp.Net Core and EF Core

Intro

Around one year ago I started developing a new project. The project initially consisted of an asp.net core application as a backend server and an angular client application as a UI. One of the key requirements was the data synchronization in realtime.

I already knew and liked firebase and had the wish to be able to use it in the project. Sadly that was not possible because another requirement was that the application should have a asp.net core backend and can be self-hosted.

I made some research and sadly did not find any other solution that would make the development easier with the required tech stack.

I then decided to start developing my own realtime database called SapphireDb. Here are the most important the features the project now has:

  • 🔧 Dead simple configuration
  • 🌠 Blazing fast development
  • 📡 Modern technologies
  • 💻 Self hosted
  • 💾 Easy CRUD operations
  • 🔑 Authentication/Authorization included
  • ✔️ Database support
  • 🔌 Actions
  • 🌐 NLB support

In this short article I want to explain you how to quickly create your own application with realtime data synchronization using SapphireDb for Asp.Net Core and an Angular application.

Setup

Server

First you have to create a server application using Asp.Net Core. Using the empty project template totally does the job.

Install

The next step is to install the package from nuget:

PM> Install-Package SapphireDb

Create DbContext

Now create a DbContext that contains the objects you want to store in the database.

If you dont know how to work with Entity Framework Core check out this documentation for more details: EF Core Docs

The context should look something like this:

// Important: Use SapphireDbContext instead of DbContext
public class MyDbContext : SapphireDbContext
{
  //Add SapphireDatabaseNotifier for DI
  public MyDbContext(DbContextOptions<MyDbContext> options, SapphireDatabaseNotifier notifier) : base(options, notifier)
  {

  }

  public DbSet<User> Users { get; set; }

  public DbSet<Test> Tests { get; set; }
}

Register services and update pipeline

The last step is to modify your service registrations and add SapphireDb to your request pipeline. Modify your Startup.cs file like this:

public class Startup
{
  public void ConfigureServices(IServiceCollection services)
  {
    //Register services
    services.AddSapphireDb(new SapphireDbOptions())
      .AddContext<MyDbContext>(cfg => cfg.UseSomeDatabase());
  }

  public void Configure(IApplicationBuilder app)
  {
    //Add Middleware
    app.UseSapphireDb();
  }
}

Try launching the application

The server application should now work.

Client

You now can create your client application. You first have to create a Angular App or use an existing.

Install

First install the project using:

npm install -S ng-sapphiredb

Import SapphireDbModule

Then you have to import the SapphireDbModule in you app.module.ts to make the services available in the whole application:

@NgModule({
  imports: [
    SapphireDbModule
  ],
  providers: [
    // This part is optional and only required if you want to override some of the settings
    {
      provide: SAPPHIRE_DB_OPTIONS,
      useValue: {
        serverBaseUrl: environment.serverBaseUrl,
        apiSecret: 'pw1234',
        apiKey: 'webapp',
        connectionType: 'websocket'
      }
    }
  ],
})
export class AppModule {}

Start application

The cient application should now work. Start it and navigate to the url in your browser.

Query data

You are now able to query data. You can use this code in your angular client to get the data from your database. Changes on server side are not required.

export class DemoComponent implements OnInit {
  values$: Observable<Entry[]>;

  constructor(private db: SapphireDb) { }

  ngOnInit() {
    this.values$ = this.db.collection<Entry>('nameofdbset').values();
  }
}

To display the content of your collection as json use this in your html:

{{ values$ | async | json }}

This project uses RxJs. If you don't know what an observable is and how to work with it check out this url: RxJs Documentation

When you display the content of the array in the component you can already see the entries and if you change something it should update immediatly.

Update data

To update data you have to make the class of the model you want to update updatable. The class should look like this:

[Updatable]
public class DemoEntry
{
  [Key]
  public int Id { get; set; }

  public string Content { get; set; }
}

You can then update the content using this code on client side:

export class DemoComponent implements OnInit {
  collection: DefaultCollection<Entry>;
  constructor(private db: SapphireDb) { }

  ngOnInit() {
    this.collection = this.db.collection<Entry>('entries', 'demo');
  }

  updateValue(value: Entry) {
    this.collection.update({
      ...value,
      content: v
    });
  }
}

Finish

You are now familiar to the main features of SapphireDb. If you want to learn more check out the documentation and the project on Github.

Documentation

GitHub logo SapphireDb / SapphireDb

SapphireDb Server, a self-hosted, easy to use realtime database for Asp.Net Core and EF Core

SapphireDb - Server for Asp.Net Core Build Status

SapphireDb logo

SapphireDb is a self-hosted, easy to use realtime database for Asp.Net Core and EF Core.

It creates a generic API you can easily use with different clients to effortlessly create applications with realtime data synchronization SapphireDb should serve as a self hosted alternative to firebase realtime database and firestore on top of .Net.

Check out the documentation for more details: Documentation

Features

  • 🔧 Dead simple configuration
  • 📡 Broad technology support
  • 💻 Self hosted
  • 📱 Offline support
  • 💾 Easy to use CRUD operations
  • Model validation
  • ✔️ Database support
  • 📂 Supports joins/includes
  • Complex server evaluated queries
  • 🔌 Actions
  • 🔑 Authorization included
  • ✉️ Messaging
  • 🌐 Scalable

Learn more

Installation

Install package

To install the package execute the following command in your package manager console

PM> Install-Package SapphireDb

You can also install the extension using Nuget package manager. The project can be found here: https://www.nuget.org/packages/SapphireDb/

Configure

Top comments (0)