You are here:   Blog
Register   |  Login

 

Mar 11

Written by: Michael Washington
3/11/2017 11:03 PM  RssIcon

image

You can create database driven .Net Core applications using JavaScriptServices, and PrimeNg.

Live Example

You can see the application running live on Microsoft Azure at: http://helloworlddata.azurewebsites.net

YouTube Video

image

You can see the YouTube video that covers all the content of this Blog here: https://www.youtube.com/watch?v=i6ke21P-fgA

Prerequisites

If you do not already have them, install the following prerequisites:

 

Create JavaScriptServices project

image

Create a folder on your Microsoft Windows computer (this tutorial was created using Windows 10).

Note: Do not have any special characters in the folder name. For example, and exclamation mark (!) will break the JavaScript code.

image

You can type CMD and press Enter to switch to the command line (and still be in that directory).

image

If you have not already installed JavaScriptServices, install them by entering (and pressing Enter):

dotnet new --install Microsoft.AspNetCore.SpaTemplates::*

image

The screen will display indicating the templates now available.

image

Create the ASP.NET Core JavaScriptServices application by entering (and pressing Enter):

dotnet new angular

 

image

The application will be created.

Double-click on the *.csproj file to open it in Visual Studio 2017.

image

It will start restoring .Net dependencies and the node_modules (you can view the ../node_modules directory to see the items populated).

(Note: This can take 3-10 minutes or more)

image

Visual Studio will indicate when everything is complete.

image

Press Ctrl+F5 to Start Without Debugging.

image

The application will Build.

image

The application will show.

Close the web browser for now.

Add PrimeNG

image

We will now install the free open source PrimeNG Angular 2 components.

This will demonstrate how to integrate most Angular 2+ libraries with JavaScriptServices.

image

Open the package.json file and add:

    "font-awesome": "^4.7.0",
    "primeng": "^2.0.0"

Save the file.

image

Open the webpack.config.vendor.js file and add:

 

    'font-awesome/css/font-awesome.css',
    'primeng/primeng',
    'primeng/resources/themes/omega/theme.css',
    'primeng/resources/primeng.min.css', 

image

Also, in rules/test, add:

    |gif

Save the file.

image

At this time, PrimeNg does not support pre-rendering so in ..\Views\Home\Index.cshtml, change:

<app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>


to:

<app>Loading...</app>

 

Save the file.

image

We altered the webpack.config.vendor.js file (to add PrimeNg and Font Awesome) but it is not updated by the normal build process. We have to run its configuration manually whenever we alter it.
In a command prompt, at the project root, run:

webpack --config webpack.config.vendor.js

(Note: If you don’t already have the webpack tool installed (for example you get an error when you run the code above), you’ll need to run: npm install -g webpack first)

image

Create a folder called prime in the components folder and add the following code to ..\ClientApp\app\components\prime\prime.component.html:

 

<h1>Counter</h1>
<p>This is a simple example of an Angular 2 component.</p>
<p>Current count: <strong>{{ currentCount }}</strong></p>
<p-growl [value]="msgs"></p-growl>
<button pButton 
        type="button" 
        (click)="incrementCounter()" 
        label="Increment" 
        icon="fa-check"
        class="ui-button-info">
</button>

 

image

Create the file and add the following code to ..\ClientApp\app\components\prime\prime.component.ts:

 

import { Component } from '@angular/core';
import {
    ButtonModule,
    GrowlModule,
    Message
} from 'primeng/primeng';
@Component({
    selector: 'counter',
    templateUrl: './prime.component.html'
})
export class PrimeComponent {
    public currentCount = 0;
    public msgs: Message[] = [];
    public incrementCounter() {
        this.currentCount++;
        this.msgs.push(
            {
                severity: 'info',
                summary: 'Info Message',
                detail: this.currentCount.toString()
            });
    }
}

 

image

Alter the file at: ..\ClientApp\app\app.module.ts to add:

 

import { FormsModule } from '@angular/forms';
import { PrimeComponent } from './components/prime/prime.component';
import { ButtonModule, GrowlModule } from 'primeng/primeng';
@NgModule({
    declarations: [ 
        ...
        PrimeComponent
    ],
    imports: [
        RouterModule.forRoot([
            ...
            { path: 'prime', component: PrimeComponent },
            ...
        ]),
        FormsModule,
        ButtonModule,
        GrowlModule
    ]
})
...

 

image

Add the following code to ..\ClientApp\app\components\navmenu\navmenu.component.html:

 

    <li [routerLinkActive]="['link-active']">
        <a [routerLink]="['/prime']">
            <span class='glyphicon glyphicon-th-list'></span> Prime
        </a>
    </li>

 

image

Press Ctrl+F5 to Start Without Debugging.

image

When you click on the Prime link in the menu you will see a page that is using PrimeNg components.

Add A Database

image

Right-click on the project node, select Add then New Scaffolded Item…

image

Select Full Dependencies then click Add.

image

The Scaffolding will run.

image

Close the ScaffoldingReadMe.txt file that opens.

image

Right-click on the project node and select Edit HelloWorldData.csproj.

image

Add:

<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" />

Save and close the file.

image

From the menu in Visual Studio, select Tools then Connect to Database…

image

  • Ensure that Microsoft SQL Server Database File (SqlClient) is selected for Data source (use the Change button if not)
  • Enter HelloData.mdf for the database name and indicate that it is in a folder called Data that is under your project root (the file does not exist, it will be created by Visual Studio)
  • Click OK

image

Click Yes to create the database.

image

In the Server Explorer window in Visual Studio (you can get to it from the Visual Studio menu using View then Server Explorer), the database will show.

Expand it, right-click on the Tables node and select Add New Table.

image

Enter the following script and click the Update button:

 

CREATE TABLE [dbo].[WeatherForecast] (
    [Id]            INT           IDENTITY (1, 1) NOT NULL,
    [DateFormatted] NVARCHAR (50) NOT NULL,
    [TemperatureC]  INT           NOT NULL,
    [TemperatureF] INT NOT NULL, 
    [Summary] NVARCHAR(50) NOT NULL, 
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

 

image

Click Update Database.

image

The Data Tools Operations window will indicate when the update is complete.

image

In the Server Explorer window, right-click on the database and select Refresh.

image

The WeatherForecast table will show.

Right-click on the table and select Show Table Data.

image

Enter sample data into the grid.

image

Always Close the database connection when done working with it to prevent locking.

image

In the Solution Explorer, right-click on the project node and select Manage NuGet Packages.

image

Search for and install: Microsoft.EntityFrameworkCore.Tools.

image

Open the NuGet Package Manager Console.

image

Enter:

Scaffold-DbContext "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\TEMP\HelloWorldData\Data\HelloData.mdf;Integrated Security=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

and press Enter.

(update the connection string above to point to the location of the .mdf file in the project)

image

The scaffolded files will appear in the Models directory.

Note: If you get DBContext cannot be found errors (red squiggly lines in the Visual Studio text editor, simply close Visual Studio and re-open it.

image

Rename the DataContext file and the class to HelloDataContext.

image

Next, we follow the directions at this link: ASP.NET Core - Existing Database.

We remove the OnConfiguring method.

We add the following constructor to the class:

 

    public HelloDataContext(DbContextOptions<HelloDataContext> options) : 
        base(options) { }

 

image

We add the following using statements to Startup.cs:

 

using HelloWorldData.Models;
using Microsoft.EntityFrameworkCore;

 

image

We add the following code to the ConfigureServices section:

 

    services.AddDbContext<HelloDataContext>(
        options => options.UseSqlServer(
            Configuration.GetConnectionString("HelloWorldDataDatabase")));

 

image

 

Add the following setting to the appsettings.json file:

 

  "ConnectionStrings": {

"HelloWorldDataDatabase": "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=

C:\\TEMP\\HelloWorldData\\Data\\HelloData.mdf;Integrated Security=True;"

  },

 

(Note: The HelloWorldDataDatabase value needs to be on a single line – see the source code for the exact seting)

 

image

Right-click on the Controllers folder and select Add then New Scaffolded Item…

image

Select API, then API Controller with actions, using Entity Framework, then click Add.

image

Select the options above and click Add.

image

An API controller that will retrieve data from the database will be created.

image

We will now point the Angular page to the new API controller.

Open the ..\ClientApp\app\components\fetchdata\fetchdata.component.ts  file and alter the .get address to:

'/api/WeatherForecasts'

 

image

When we run the application, and click on the Fetch data link, the data will now be retrieved from the database.

 

Links

Building Single Page Applications on ASP.NET Core with JavaScriptServices

Visual Studio 2017

Node.js

EntityFramework Reverse POCO Generator

ASP.NET Core - New Database

ASP.NET Core - Existing Database

Publishing and Running ASP.NET Core Applications with IIS

Download

The project is available at http://lightswitchhelpwebsite.com/Downloads.aspx

You must have Visual Studio 2017 (or higher) installed to run the code.

You will need to alter the appsettings.json file to point to the exact location of the .mdf file on your computer depending on where you unzip the project to.

2 comment(s) so far...


Gravatar

Re: Hello World Angular 2+ Data Sample Using JavaScriptServices .Net Core and PrimeNg

Start learn new one technology is hard. Thank to you I passed to join VS2017 SPA WebAPI Core and Angular 2 and libraries with JavaScriptServices.

By Oleg on   3/19/2017 2:25 PM
Gravatar

Re: Hello World Angular 2+ Data Sample Using JavaScriptServices .Net Core and PrimeNg

@Oleg - Thank you for the feedback.

By Michael Washington on   3/19/2017 2:25 PM
Microsoft Visual Studio is a registered trademark of Microsoft Corporation / LightSwitch is a registered trademark of Microsoft Corporation