
Introduction
In our previous article,
In this article we will see in detail about using ASP.NET Core 1.0 with Angular2 to Insert and Select Student Details to SQL Server Database using WEB API.
In this article we will see in detail how to,
- Create our ASP.NET Core 1.0 RC2 Web Application.
- Create Model to add Student details.
- Create WEB API Controller using Entity framework to Select and Insert data to database.
- How to add TypeScript JSON Configuration File
- How to add grunt package using NPM configuration file
- How to configure Grunt File.
- Adding Dependencies to install Angular2 and all other files
- How to create our Angular2 App, boot using Type Script file.
- Using HTTP Get/Post to Insert and select data from Angular2 to WEB API to insert in DB.
- Creating HTML File
- How to Run the Grunt file using Visual Studio Task Runner Explorer
- How to Run and view our Sample.
Reference website :
Prerequisites
Create a Database
We will be using our SQL Server database for our WEB API. First we create a database named StudentsDB and a table as StudentMaster. Here is the SQL script to create Database table and sample record insert query in our table. Run the below query in your local SQL server to create Database and Table to be used in our project.
- USE MASTER
- GO
- -- 1) Check for the Database Exists .If the database is exist then drop and create new DB
- IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'StudentsDB' )
- DROP DATABASE StudentsDB
- GO
- CREATE DATABASE StudentsDB
- GO
- USE StudentsDB
- GO
- -- 1) //////////// StudentMasters
- IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'StudentMasters' )
- DROP TABLE StudentMasters
- GO
- CREATE TABLE [dbo].[StudentMasters](
- [StdID] INT IDENTITY PRIMARY KEY,
- [StdName] [varchar](100) NOT NULL,
- [Email] [varchar](100) NOT NULL,
- [Phone] [varchar](20) NOT NULL,
- [Address] [varchar](200) NOT NULL
- )
- -- insert sample data to Student Master table
- INSERT INTO [StudentMasters] ([StdName],[Email],[Phone],[Address])
- VALUES ('Shanu','[email protected]','01030550007','Madurai,India')
- INSERT INTO [StudentMasters] ([StdName],[Email],[Phone],[Address])
- VALUES ('Afraz','[email protected]','01030550006','Madurai,India')
- INSERT INTO [StudentMasters] ([StdName],[Email],[Phone],[Address])
- VALUES ('Afreen','[email protected]','01030550005','Madurai,India')
- select * from [StudentMasters]
After installing both Visual Studio 2015 and ASP.NET Core 1.0 RC2. Click Start, then Programs and select Visual Studio 2015 - Click Visual Studio 2015. Click New, then Project, select Web and select ASP.NET Core Web Application. Enter your Project Name and click OK.

Next select Web Application. If you are not hosting in Cloud then you can uncheck the Host in the Cloud at the bottom right corner. Click OK.

Now we have,

Database Connection String
Now we need to change the local connection string from ASP.Net 5 project with our SQL Server connection.
Note: In ASP.NET Core 1.0 we need to use “appsettings.json” file instead of web.config.We can find the “appsettings.json” file from our ASP.NET Core 1.0 solution.

To change the default connection string with our SQL connection open the “appsettings.json” file .Yes this is JSON file and this file looks like below Image by default.

Now the default connectionstring will be something like this,
- "ConnectionStrings": {
- "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-Core1.0Angular2CRUDInsert-599f2ca4-119a-4fd5-a2a4-e58fb4b2e5be;Trusted_Connection=True;MultipleActiveResultSets=true"
- },
- "ConnectionStrings": {
- "DefaultConnection": "Server=SQLSERVERNAME;Database=StudentsDB;user id=SQLID;password=SQLPWD;Trusted_Connection=True;MultipleActiveResultSets=true;"
- },
We can create a model by adding a new class file in our Model Folder.

Right click the Models folder and click new Item. Select Class and enter your class name as “StudentMasters.cs”

Now in this class we first create property variable, add student. We will be using this in our WEB API controller.
- using System.ComponentModel.DataAnnotations;
- namespace WebApplicationTestSample.Models
- {
- public class StudentMasters
- {
- [Key]
- public int StdID { get; set; }
- [Required]
- [Display(Name = "Name")]
- public string StdName { get; set; }
- [Required]
- [Display(Name = "Email")]
- public string Email { get; set; }
- [Required]
- [Display(Name = "Phone")]
- public string Phone { get; set; }
- public string Address { get; set; }
- }
- }
We can create a controller by adding a new Empty API Controller in our Controller Folder.

Right click the Controller folder and Add Controller. Select API Controller with action, using Entity Framework and click Add,

Select the Model class as StudentMasters.

After selecting the Model Class select the Data Context Class. Here we are selecting the default ApplicationDbContext. Note we have set the default connection string to our SQL Server database Connection. Next give our WEB API controller name as StudentMastersAPI.

We can see that our WEB API Controller has been created now and also the controller will contain default Select (HttpGet) and Insert method as (HttpPost). We will be using this get and post method In our Angular2 to select and insert data to database.

To test it we can run our project and copy the get method api path here we can see our API path for get is api/StudentMastersAPI/
Run the program and paste the above API path to test our output.

Step 4: How to add TypeScript JSON Configuration File
The TypeScript JSON file specifies the root files and the compiler options required to compile the project .To know more about TypeScript JSON Configuration kindly visit this site.
To create the TypeScript JSON file right click on you Project and Click Add new Item.

Select TypeScript JSCON Configuration File and Click ok. The File will be look like below image.

Now copy the below code and replace with your config file.
- "compilerOptions": {
- "emitDecoratorMetadata": true,
- "experimentalDecorators": true,
- "module": "commonjs",
- "moduleResolution": "node",
- "noImplicitAny": false,
- "noEmitOnError": true,
- "removeComments": false,
- "target": "es5",
- "sourceMap": true

Step 5: How to add grunt package using NPM configuration file
Now we need to add a NPM Configuration File for adding a grunt package to run our java scripts. As we have created as a Web Application the NPM Configuration File will be located in our project. By default we can’t view our NPM Configuration File. The NPM Configuration File will be in the name of “package.JSON” . To view that from the Solution Explorer click on “Show All Files”
Now open the “package.JSON” file. Now first we need to change the name to our project Solution name and add our grunt package. We can see the code here below the image.

Here we have changed the name as our Solution name and also added the grunt package.
- {
- "name": "test",
- "version": "0.0.0",
- "private": true,
- "devDependencies": {
- "grunt": "1.0.1",
- "grunt-contrib-copy": "1.0.0",
- "grunt-contrib-uglify": "1.0.1",
- "grunt-contrib-watch": "1.0.0",
- "grunt-ts": "5.5.1",
- "gulp": "3.8.11",
- "gulp-concat": "2.5.2",
- "gulp-cssmin": "0.1.7",
- "gulp-uglify": "1.2.0",
- "rimraf": "2.2.8"
- }
- }
Restoring

Al Installed

Step 6: Configure Grunt File.
Grunt is used to build all our client side resources like JavaScript for our project.
First step is to add a Grunt file to our project. Right click our project and Select Grunt Configuration File and click Add.

After creating the file now we need to edit this file to add load plugins, configure plugins and define tasks
Here in our Grunt file we have first load plugins which we have added in our npm. Using loadNpmTask here we load 'grunt-contrib-copy ,'grunt-contrib-uglify' , 'grunt-contrib-watch',

Next we configure the grunt add the app.js file in our wwwroot folder. All our Script files from Scripts folder result will be added in this app.js file. Next we need to copy all the Script file from 'node_modules/ to our local js Folder.
The watch plugin will be used to check for any changes on JavaScript file and update it app.js with all new changes.
- /*
- This file in the main entry point for defining grunt tasks and using grunt plugins.
- Click here to learn more. http://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409
- */
- module.exports = function (grunt) {
- grunt.loadNpmTasks('grunt-contrib-copy');
- grunt.loadNpmTasks('grunt-contrib-uglify');
- grunt.loadNpmTasks('grunt-contrib-watch');
- grunt.loadNpmTasks('grunt-ts');
- grunt.initConfig({
- ts:
- {
- base:
- {
- src: ['Scripts/app/boot.ts', 'Scripts/app/**/*.ts'],
- outDir: 'wwwroot/app',
- tsconfig: './tsconfig.json'
- }
- },
- uglify:
- {
- my_target:
- {
- files: [{
- expand: true,
- cwd: 'wwwroot/app',
- src: ['**/*.js'],
- dest: 'wwwroot/app'
- }]
- },
- options:
- {
- sourceMap: true
- }
- },
- // Copy all JS files from external libraries and required NPM packages to wwwroot/js
- copy: {
- main: {
- files:
- [{
- expand: true,
- flatten: true,
- src: ['Scripts/js/**/*.js', 'node_modules/es6-shim/es6-shim.min.js', 'node_modules/systemjs/dist/system-polyfills.js', 'node_modules/angular2/bundles/angular2-polyfills.js', 'node_modules/systemjs/dist/system.src.js', 'node_modules/rxjs/bundles/Rx.js', 'node_modules/angular2/bundles/angular2.dev.js'],
- dest: 'wwwroot/js/',
- filter: 'isFile'
- }]
- }
- },
- // Watch specified files and define what to do upon file changes
- watch: {
- scripts: {
- files: ['Scripts/**/*.js'],
- tasks: ['ts', 'uglify', 'copy']
- }
- }
- });
- // Define the default task so it will launch all other tasks
- grunt.registerTask('default', ['ts', 'uglify', 'copy', 'watch']);
- };
We are using NPM to install our Angular2 in our web application. Open our Package.JSON file and the below dependencies.
- "dependencies": {
- "@angular/http": "2.0.0-rc.1",
- "angular2": "^2.0.0-beta.8",
- "angular2-jwt": "0.1.16",
- "angular2-meteor": "0.5.5",
- "cors": "2.7.1",
- "systemjs": "0.19.22",
- "es6-promise": "^3.0.2",
- "es6-shim": "^0.33.3",
- "reflect-metadata": "0.1.2",
- "rxjs": "5.0.0-beta.2",
- "tsd": "^0.6.5",
- "zone.js": "0.5.15"
- },

Save the file and wait for a few second to complete all dependencies installed.

Step 8 How to create our Angular2 App, boot using Type Script file.
Now it’s time to create our Angular2 application. First create a Folder named Scripts. Right click our project and click add new Folder and name the folder name as “Scripts”. Now we will create our TypeScript files inside this Scripts folder.
To work with Angular2 we need to create 2 important TypeScript files.
- Component File where we write our Angular coding.
- Boot file: To run our component app .
Creating App TypeScript file
Right Click on Scripts folder and click on add new Item. Select TypeScript File and name the file as App.ts and click Add.

In App.ts file we have three parts first is the,
- import part
- Next is component part
- Next we have the class for writing our business logics.
Here we can see a simple basic one way binding example to display the welcome message in side h1 tag.Here.











Ramit BaksiPosted Jul 12, 2017, 12:07 PM
Hi Syed, I'm using VS2017 and getting this error "GET http://localhost:17215/api/StudentMastersAPI net::ERR_CONNECTION_RESET" while running the API. Checked in google, but not getting any solution. Could you please suggest anything?
kalikrishna maddulaPosted May 12, 2017, 1:14 AM
Hi, I'm facing errors When i try to configure your downloaded project "The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\DotNet\Microsoft.DotNet.Props" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.". Could you please provide your comments on this.
Rathrola Prem KumarPosted Apr 30, 2017, 5:57 AM
My Troubleshoot, When i add tsconfig, i face some build error, so then i have a new folder named with scripts and added one empty .ts file, hence my problem resolved
kzelda linkPosted Mar 12, 2017, 6:28 AM
Thank you very much
Rajashekhar GPosted Dec 29, 2016, 8:58 AM
Nice article and very helpful
Ravi KandelPosted Aug 14, 2016, 3:06 AM
Nice
Syed ShanuPosted Jul 19, 2016, 8:20 PM
Thank You
Saurabh SarkarPosted Jul 19, 2016, 2:22 PM
Nice..
Anu VPosted Jul 19, 2016, 6:07 AM
Nice
Anupam SinghPosted Jul 19, 2016, 5:13 AM
Nice share.
Shobana JPosted Jul 19, 2016, 2:51 AM
Nice one
Vignesh ManiPosted Jul 18, 2016, 6:28 PM
Good one.
Mohammed IbrahimPosted Jul 18, 2016, 9:54 AM
Nice article can u suggest me some tutorials for Angular js and web API
kalu singh raoPosted Jul 18, 2016, 4:55 AM
Nice...