How to synchronize data in realtime with Asp.Net Core and Angular
Tags: dotnet, angular, webdev
Published: 2019-12-10 17:02:19

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

{% github morrisjdev/SapphireDB no-readme %}

# 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](https://sapphire-db.com/). Here are the most important the features the project now has:

- :wrench: Dead simple configuration
- :stars: Blazing fast development
- :satellite: Modern technologies
- :computer: Self hosted
- :floppy_disk: Easy CRUD operations
- :key: Authentication/Authorization included
- :heavy_check_mark: Database support
- :electric_plug: Actions
- :globe_with_meridians: NLB support

In this short article I want to explain you how to quickly create your own application with realtime data synchronization using [SapphireDb](https://sapphire-db.com/) 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](https://docs.microsoft.com/de-de/ef/core/)

The context should look something like this:

```csharp
// 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:

```csharp
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:

```ts
@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.

```ts
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:

```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](https://rxjs-dev.firebaseapp.com/)

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:

````csharp
[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:

```ts
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](https://sapphire-db.com/)

{% github morrisjdev/SapphireDB %}