Advertisements

Building Applications with ASP.NET Core MVC 6 & Entity Framework Core using ASP.NET Core 1.0


Introduction

In this article, we will explain how to build the Applications with an ASP.NET Core MVC 6 & Entity Framework Core, using ASP.NET Core 1.0.

Before reading this article, you must read the articles given below for ASP.NET Core knowledge.

Model Class

We are going to create a registration page, using ASP.NET Core & EntityFrameWork Core. The Model class given below contains the properties of Registration details in our Applications.

using System;

namespace RegistrationForm.Models
{
    public class Registration
    {
        public Guid Id { get; set; }

        public string Name { get; set; }
        
        public string Location { get; set; }
        
        public string Mobile { get; set; }
        
        public string Email { get; set; }
        
        public string Address { get; set; }
    }
}

Dependency Required

The dependency given below is required to build ASP.NET Core MVC & EntityFrameWork Core Applications.

{
  "dependencies": {
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.AspNetCore.Mvc.TagHelpers": "1.1.1",
    "Microsoft.AspNetCore.Mvc.ViewFeatures": "1.1.1",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.AspNetCore.StaticFiles": "1.1.0",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.EntityFrameworkCore.Design":"1.1.0",
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    }  },

Tools Required

Add the Entity Framework Core tools in our Application.

"tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.0.0-preview2-final",
      "imports": [
        "portable-net45+win8+dnxcore50",
        "portable-net45+win8"
      ]
    }
  },

Configuring ASP.NET MVC in ASP.NET Core 1.0

We are going to add “UseMvc” Middleware and “AddMvc()” Configure Services in Startup.cs Class. The code given below clearly mentions that manually we need to add our controller name and an action name in “MapRoute”. We can change this controller name and action name, which is based on our requirement in the Applications.

app.UseMvc(config =>
           {
               config.MapRoute(
                   name: "Default",
                   template: "{controller}/{action}/{id?}",
                   defaults: new { controller = "Home", action = "Home" }
                   );
           });

LocalDB Configuration in ASP.NET Core 1.0

In the previous versions, everything is handled by Web.Config but in ASP.NET Core, the connection string is written in appsettings.json file. By default, it will show as a LocalDB path and as per our requirement, we can change the connection string path.

The appsetting JSON file contains the LocalDB connection string details in our Application and we have given the database name as “RegDB”. If you want to know more about JSON file configuration in ASP.NET Core, please check our previous article ADDING A CONFIGURATION SOURCE FILE IN ASP.NET CORE 1.0.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=RegDB;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

DbContext in ASP.NET Core 1.0

The code given below contains an information about EntityFrameWork Core DbContext. We can add the LocalDB connection string details with the help of “UseSqlServer” Method.

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

namespace RegistrationForm.Models
{
    public class RegContext : DbContext
    {
        private IConfigurationRoot _config;

        public RegContext(IConfigurationRoot config, DbContextOptions options) : base(options)
        {
            _config = config;
        }
        public DbSet<Registration> Registrations { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer(_config["ConnectionStrings:DefaultConnection"]);
        }
    }
}

Seed Data in EntityFrameWork Core

We are going to implement Code First Migrations in an Entity Framework Core to seed the database with the test data and manually we are entering the seed data information in the “RegContextSeedData” class. The code given below contains the default values of Registration Details Table in our Application.

using System;
using System.Linq;
using System.Threading.Tasks;

namespace RegistrationForm.Models
{
    public class RegContextSeedData
    {
        private RegContext _context;

        public RegContextSeedData(RegContext context)
        {
            _context = context;
        }

        public async Task SeedData()
        {
            if(!_context.Registrations.Any())
            {
                var newReg = new Registration()
                {
                    Id = Guid.NewGuid(),
                    Name = "RajeeshMenoth",
                    Location = "Thuyyam",
                    Mobile = "123456789",
                    Email = "rajeeshmenoth@gmail.com",
                    Address = "Menoth Parambil House, Edappal Post, Thuyyam"
                };
                _context.Registrations.Add(newReg);
                await _context.SaveChangesAsync();
            }
        }
    }
}

Repository 

The code given below contains the common repository for our Application.

using System.Collections.Generic;
using System.Linq;

namespace RegistrationForm.Models
{
    public class RegRepository : IRegRepository
    {
        private RegContext _context;

        public RegRepository(RegContext context)
        {
            _context = context;
        }

        public IEnumerable<Registration> GetAllRegistrations()
        {
            return _context.Registrations.ToList();
        }
    }
}

Server Side Validation

In the View Model, we implemented the default validations in the Registration page in our Applications.

using System.ComponentModel.DataAnnotations;

namespace RegistrationForm.ViewModels
{
    public class RegistrationViewModel
    {
        [Required]
        public string Name { get; set; }

        [Required]
        public string Location { get; set; }

        [Required]
        [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid Phone number")]
        public string Mobile { get; set; }

        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [Required]
        [StringLength(5000, MinimumLength =10)]
        public string Address { get; set; }
        
    }
}

Controllers

In our Applications, we created two Controllers, where one is Home and another is Registration.

Home Controller

Home Controller returns all the registered user information list in home page with the help of common repository.

using Microsoft.AspNetCore.Mvc;
using RegistrationForm.Models;

namespace RegistrationForm.Controllers.WebApp
{
    public class HomeController : Controller
    {
        private IRegRepository _repository;

        public HomeController(IRegRepository repository)
        {
            _repository = repository;
        }

        public IActionResult Home()
        {
            var data = _repository.GetAllRegistrations();
            return View(data);
        }

    }
}

Registration Controller

The registration controller contains the registration information in our Application.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RegistrationForm.Models;
using RegistrationForm.ViewModels;
using System;

namespace RegistrationForm.Controllers.WebApp
{
    public class RegistrationController : Controller
    {
        private RegContext _context;
        private ILogger<Registration> _logger;

        public RegistrationController(RegContext context, ILogger<Registration> logger)
        {
            _context = context;
            _logger = logger;
        }
        public IActionResult Registration()
        {
            return View();
        }
        public IActionResult Home()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Registration(RegistrationViewModel model)
        {
            ViewBag.SuccessMessage = null;

            if (model.Email.Contains("menoth.com"))
            {
                ModelState.AddModelError("Email", "We don't support menoth Address !!");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    Registration regData = new Registration()
                    {
                        Id = Guid.NewGuid(),
                        Name = model.Name,
                        Email = model.Email,
                        Location = model.Location,
                        Mobile = model.Mobile,
                        Address = model.Address
                    };

                    _context.Registrations.Add(regData);
                    _context.SaveChanges();

                    ModelState.Clear();
                    ViewBag.SuccessMessage = "Registered Successfully !!";
                }
                catch (Exception ex)
                {
                    _logger.LogError($" Registration Failure : {ex.Message} ");
                }
            }

            return View();
        }
    }
}

Startup.cs

The class given blow contains the complete middleware details in our Applications.

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using RegistrationForm.Models;
using Microsoft.Extensions.Configuration;

namespace RegistrationForm
{
    public class Startup
    {
        private IConfigurationRoot _config;

        public Startup(IHostingEnvironment env)
        {
            var ConfigBuilder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json");
            _config = ConfigBuilder.Build();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(_config);
            services.AddDbContext<RegContext>();
            services.AddScoped<IRegRepository, RegRepository>();
            services.AddTransient<RegContextSeedData>();
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
            ILoggerFactory loggerFactory, RegContextSeedData seeder)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseStaticFiles();

            app.UseMvc(config =>
           {
               config.MapRoute(
                   name: "Default",
                   template: "{controller}/{action}/{id?}",
                   defaults: new { controller = "Home", action = "Home" }
                   );
           });

            seeder.SeedData().Wait();

        }
    }
}

project.json

project.json contains the complete picture of dependency in our Applications.

{
  "dependencies": {
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.AspNetCore.Mvc.TagHelpers": "1.1.1",
    "Microsoft.AspNetCore.Mvc.ViewFeatures": "1.1.1",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.AspNetCore.StaticFiles": "1.1.0",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.EntityFrameworkCore.Design":"1.1.0",
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    }  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.0.0-preview2-final",
      "imports": [
        "portable-net45+win8+dnxcore50",
        "portable-net45+win8"
      ]
    }
  },

  
  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

bower.json

The simple way in which we can say Bower is optimized for the front-end in our Applications and it provides the client side dependencies. For example, Bower manages the components and it contains HTML, CSS, JavaScript, fonts or even the image files.

{
	"name": "asp.net",
	"private": true,
  "dependencies": {
    "jquery": "~3.1.1",
    "jquery-validation": "~1.16.0",
    "jquery-validation-unobtrusive": "~3.2.6",
    "bootstrap": "~3.2.6"
    
  }
}

Code First Migration

First, we need to find the project location in CLI (Command Line Interface ) and afterwards, run the commands given below step by step.

  • “dotnet ef migrations add IntialDB” ( new EntityFrameWork migration ).
  • “dotnet ef database update” ( update the EntityFrameWork Core database in ASP.NET Core ).

To know more about it, please refer my previous article by Click here.

Project Structure

The structure given below will be created after the ef migration in ASP.NET Core.

Project Structure

Project Structure

New Tag Helpers

We used latest ASP.NET Core Tag Helpers in Registration page to access controller and actions, validation etc.

<div asp-validation-summary="All" class="text-danger"></div>

<label asp-for="Name"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>

<a asp-controller="Home" asp-action="Home" class="btn btn-info">Cancel</a>

Inject Tag Helpers

In the way given below, we can inject the Tag Helpers in our Application. Now, create the default “_ViewImports.cshtml” file in View Folder and add the code given below in that file.

@addTagHelper "*,Microsoft.AspNetCore.Mvc.TagHelpers"

Client Side Validations

The Client Side validation is done through with the help of Bootstrap & jQuery etc. All these Client Side dependencies are accessed from bower.json file.

RegistrationForm Validation

RegistrationForm Validation

Output

Output

Reference

See Also

You can download other ASP.NET Core 1.0 source codes from MSDN Code, using the links, mentioned below.

Conclusion

We learnt how to build the Applications with ASP.NET Core MVC 6 & an Entity Framework Core, using ASP.NET Core 1.0. I hope, you liked this article. Please share your valuable suggestions and feedback.

Advertisements

Code First Migration : ASP.NET Core MVC 6 With EntityFrameWork Core


Introduction

In this article, we are going to explain Code First Migration in ASP.NET Core MVC 6 with EntityFrameWork Core, using Command Line Interface ( CLI ).

Before reading this article, you must read the articles given below for ASP.NET Core knowledge.

Model Class

We are going to create a sample Code First Migration project in ASP.NET Core 1.0. Model class given below contains the properties of the user details in our Applications.

using System;

namespace CodeFirstMigration.Models
{
    public class UserDetails
    {
        public Guid Id { get; set; }

        public string Name { get; set; }

        public string EmailId { get; set; }

        public string Company { get; set; }
    }
}

LocalDB Configuration in ASP.NET Core 1.0

In the previous versions, everything is handled by Web.Config but in ASP.NET Core, the connection string is written in appsettings.json file. By default, it will show as a LocalDB path and as per our requirement, we can change the connection string path.

In the way given below, we can create connection string in ASP.NET Core 1.0.

Appsetting in Asp.Net Core

Appsetting in Asp.Net Core

The appsetting JSON file contains the LocalDB connection string details in our Application and we have given the database name as “UserDb”. If you want to know more about JSON file configuration in ASP.NET Core, please check our previous article ADDING A CONFIGURATION SOURCE FILE IN ASP.NET CORE 1.0

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=UserDb;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

DbContext in ASP.NET Core 1.0

The code givden below contains the information about EntityFrameWork Core DbContext. We can add the LocalDB connection string details with the help of “UseSqlServer” Method.

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

namespace CodeFirstMigration.Models
{
    public class CodeDbContext : DbContext
    {
        private IConfigurationRoot _config;

        public CodeDbContext(IConfigurationRoot config, DbContextOptions options) : base(options)
        {
            _config = config;
        }

        public DbSet<UserDetails> userDetails { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);

            optionsBuilder.UseSqlServer(_config["ConnectionStrings:DefaultConnection"]);
        }
    }
}

Seed Data in EntityFrameWork Core

We are going to implement Code First Migrations in Entity Framework Core to seed the database with test data and manually we are entering the seed data information in the “CodeDbSeedData” class. The code given below contains the default values of User Details Table in our Application.

using System;
using System.Linq;
using System.Threading.Tasks;

namespace CodeFirstMigration.Models
{
    public class CodeDbSeedData
    {
        private CodeDbContext _context;

        public CodeDbSeedData(CodeDbContext context)
        {
            _context = context;
        }

        public async Task SeedData()
        {
            if (!_context.userDetails.Any())
            {
                var user = new UserDetails()
                {
                    Id = Guid.NewGuid(),
                    Name = "RajeeshMenoth",
                    EmailId = "rajeeshmenoth@gmail.com",
                    Company = "HappiestMinds Technologies Pvt Ltd"
                };

                _context.userDetails.Add(user);
                await _context.SaveChangesAsync();
            }
        }
    }
}

project.json

project.json contain the complete picture of dependency in our Applications.

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.AspNetCore.Mvc.Core": "1.1.1",
    "Microsoft.EntityFrameworkCore": "1.1.0",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.1.0",
    "Microsoft.AspNetCore.Mvc": "1.1.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.1.0",
    "Microsoft.Extensions.Configuration.Json": "1.1.0",
    "Microsoft.EntityFrameworkCore.Design": "1.0.0-preview2-final"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.0.0-preview2-final",
      "imports": [
        "portable-net45+win8+dnxcore50",
        "portable-net45+win8"
      ]
    }
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

Startup.cs

The class given blow contains the complete middleware details in our Applications.

using CodeFirstMigration.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;

namespace CodeFirstMigration
{
    public class Startup
    {
        private IConfigurationRoot _config;

        public Startup(IHostingEnvironment env)
        {
            var ConfigBuilder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
                        .AddJsonFile("appsettings.json");
            _config = ConfigBuilder.Build();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(_config);
            services.AddDbContext<CodeDbContext>();
            services.AddTransient<CodeDbSeedData>();
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
            CodeDbSeedData seeder)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync(" Welcome to Dotnet Core !!");
            });

            try
            {
                seeder.SeedData().Wait();
            }
            catch (Exception ex)
            {

                throw ex;
            }
           


        }
    }
}

Code First Migration

The steps given below will explain the step by step Code First Migration in EntityFrameWork Core.

Setting Project Location

The command given below will help to change our current “C Drive” to “F Drive” because currently our Code First Migration project is saved into “F Drive”.

Drive Changing

Drive Changing

Dotnet Help Command

The command given below will display for more information about dotnet ef command.

“dotnet ef –help”

Dotnet EF Commands

Dotnet EF Commands

Starting With New Migration

We are going to start with new EntityFrameWork migration, using the command given below.

“dotnet ef migrations add IntialDB”

EF New Migration

EF New Migration

Update the database

The command given below will update the EntityFrameWork Core database in ASP.NET Core Application.

EF Update the Database

EF Update the Database

Project Structure After Migration

The structure given below will be created after the ef migration in .NET Core.

Migration Structure

Migration Structure

Local Db Created

The Dotnet EntityFrameWork CLI ( Command Line Interface ) creates the Local DB as “UserDB”. Go to “View” and select “SQL Server Object Explorer” in Visual Studio. Now, expand “SQL Server -> (localdb) -> Databases -> UserDB”.

LocalDb Created

LocalDb Created

Output

Output

Output

Download Source Code : Code First Migration

Conclusion

We learned about Code First Migration in ASP.NET Core MVC 6 with EntityFrameWork Core, using Command Line Interface ( CLI ) and I hope you liked this article. Please share your valuable suggestions and feedback.

Reference

See Also

You can download other ASP.NET Core 1.0 source codes from MSDN Code, using the links, mentioned below.

Adding A Configuration Source File In ASP.NET Core 1.0


Introduction

In this article, I will explain how to add a configuration source in ASP.NET Core 1.0. This is the simplest way to access the JSON file information in ASP.NET Core 1.0.

Before reading this article, you must read the articles given below for ASP.NET Core knowledge.

Package required

We need to add the following JSON package in package.json file. This package will help to access the information in ASP.NET Core 1.0.

"Microsoft.Extensions.Configuration.Json": "1.0.0"

Creating a json file

We are creating a configuration JSON file in our application.

Right click -> Add -> New Item.. -> Click “Code” inside the Installed Category -> Select json file.

Configuration Source

Configuration Source

appsettings.json

We have added one sample message inside the JSON file.

{
  "Message": { "WelcomeMessage": "Configure Source In ASP.NET Core 1.0 !!" },
  "Microsoft": {
    "Platform": [ "My", "New", "Article !! " ]
  }
}

JSON configuration

In the following code, we used “AddJsonFile(“json file name”)” extension method. We can access the JSON file in our application through this extension “AddJsonFile(“appsettings.json”)”.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Linq;

namespace ConfiguringSource
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var ConfigBuilder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
                                                          .AddJsonFile("appsettings.json");
            Configuration = ConfigBuilder.Build();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public IConfiguration Configuration { get; set; }
        public void ConfigureServices(IServiceCollection services)
        {

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                var Message = Configuration["Message:WelcomeMessage"];
                var Details = Configuration.GetSection("Microsoft:Platform").GetChildren().Select(x => x.Value);//array of value
                await context.Response.WriteAsync(string.Join(" ", Details) + Message);
                
            });
        }
    }
}

IConfiguration Interface

IConfiguration Interface represents a set of key/value application configuration properties.

Possible Error !!

We have added all packages and libraries but we are getting the “File Not Found” Exception. This is not a big deal! We can resolve this Internal Server Error in two ways.

Error

Error

Fixing Error 1 :

We need to specify the exact path of “appsettings.json” file. The following code includes “IHostingEnvironment” to find the path of the JSON file or any other file inside the application.

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json");

    Configuration = builder.Build();
}

Fixing Error 2 :

This is a common answer. We can directly put “Directory.GetCurrentDirectory()” to find the path of the file.

public Startup()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");

Configuration = builder.Build();
}

project.json

The final structure of project.json file in our application is given below.

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

Array

The following code will read the array of value in JSON file.

app.Run(async (context) =>
            {
                var Message = Configuration["Message:WelcomeMessage"];
                var Details = Configuration.GetSection("Microsoft:Platform").GetChildren().Select(x => x.Value);//array of value
                await context.Response.WriteAsync(string.Join(" ", Details) + Message);
                
            });

Output

Output

Output

Reference

Conclusion

We learned about adding a configuration source in ASP.NET Core 1.0 and I hope you liked this article. Please share your valuable suggestions and feedback.

How to create Rest API or Web API with ASP.NET Core 1.0


Introduction

There are several articles on Google for creating Rest API or Web API with ASP.NET Core 1.0. In this article, I will explain how to create Rest API or Web API with ASP.NET Core 1.0, starting from scratch.

Before reading this article, you must read the articles given below for ASP.NET Core knowledge.

Start from Scratch

We choose “Empty” template in “ASP.NET Core Templates” Category. I think someone may have a doubt like — without selecting a “Web API”, why do we choose “Empty” template in “ASP.NET Core Templates” Category ? Because the “Web API” templates automatically generate a few libraries related to REST API creation. So, we don’t know what is happening in the background. That’s why we choose “Empty” template.

Selecting Empty Template in Asp.Net Core 1.0

Selecting Empty Template in Asp.Net Core 1.0

References Required

We need the following references for accessing Static files, libraries for Routing, and Rest API, accessing MVC design pattern, etc.

    "Microsoft.AspNetCore.StaticFiles": "1.1.0",
    "Microsoft.AspNetCore.Routing": "1.0.1",
    "Microsoft.AspNetCore.Mvc.Core": "1.0.1",
    "Microsoft.AspNetCore.Mvc.ViewFeatures": "1.0.1",
    "Microsoft.AspNetCore.Mvc": "1.0.1"

Project.json

The following JSON file will show the full reference structure of our Web API application.

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.AspNetCore.StaticFiles": "1.1.0",
    "Microsoft.AspNetCore.Routing": "1.0.1",
    "Microsoft.AspNetCore.Mvc.Core": "1.0.1",
    "Microsoft.AspNetCore.Mvc.ViewFeatures": "1.0.1",
    "Microsoft.AspNetCore.Mvc": "1.0.1"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

Project Structure

This is the project structure of our Rest API application.

Project Structure for REST API Application

Project Structure for REST API Application

LibraryDetails.cs

We have created the following class for property details in our Rest API application.

namespace DotNetCoreExtentions
{
    public class LibraryDetails
    {
        public int Id { get; set; }
        public string Author { get; set; }
        public string BookName { get; set; }
        public string Category { get; set; }
        
    }
}

API Controller

We have to create one folder named  “Controllers”. Right click on the “Controllers” folder and go to the following steps to create an API class “Add – > New item.. -> Web API Controller Class”.

We have created an API Class named as “LibraryAPI”.

LibraryAPI.cs

The following code contains the CRUD operation of REST API application.

using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace DotNetCoreExtentions
{
    [Route("api/[controller]")]
    public class LibraryAPI : Controller
    {
        LibraryDetails[] LibraryDetails = new LibraryDetails[]
        {
            new LibraryDetails { Id=1, BookName="Programming C# for Beginners", Author="Mahesh Chand", Category="C#" },
            new LibraryDetails { Id=2, BookName="Setting Up SharePoint 2016 Multi-Server Farm In Azure", Author="Priyaranjan K S", Category="SharePoint" },
            new LibraryDetails { Id=3, BookName="SQL Queries For Beginners", Author="Syed Shanu", Category="Sql" },
            new LibraryDetails { Id=4, BookName="OOPs Principle and Theory", Author="Syed Shanu", Category="Basic Concepts" },
            new LibraryDetails { Id=5, BookName="ASP.NET GridView Control Pocket Guide", Author="Vincent Maverick Durano", Category="Asp.Net" }
        };
        
        // GET: api/values
        [HttpGet]
        public IEnumerable<LibraryDetails> GetAllBooks()
        {
            return LibraryDetails;
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {
            var books = LibraryDetails.FirstOrDefault((p) => p.Id == id);

            var item = books;
            if (item == null)
            {
                return NotFound();
            }
            return new ObjectResult(item);
        }
        
        // POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

[Route(“api/[controller]”)]

The route will assign a single route path for accessing specific API Controller CRUD operations. Instead of “[controller]”, we can mention our controller name as “LibraryAPI” in client side or server side code. If searching for any information from API, we can pass id like this -“api/LibraryAPI/id”.

Accessing Json data into LibraryAPI

At client-side, we are going to access JSON data from Library API with the help of JavaScript.

//api url
        var uri = 'api/LibraryAPI';//[Route("api/[controller]")] instead of [controller] we can mention our API classname.

        $(document).ready(function () {
            // Send an AJAX request
            $.getJSON(uri)
                .done(function (data) {
                    // On success, 'data' contains a list of products.

                    $.each(data, function (key, item) {
                        // Add a list item for the product.

                        $('


<li>', { text: ItemDetails(item) }).appendTo($('#books')).before("
");
                        $("li").addClass("list-group-item list-group-item-info");

                    });
                });
        });

        function ItemDetails(item) {
            return 'BookId : [ ' + item.id + ' ] -- Author Name : [ ' + item.author + ' ] -- Book Name : [ ' + item.bookName + ' ] -- Category : [ ' + item.category + ' ]';
        }

        function find() {
            var id = $('#bookId').val();
            if (id == '') id = 0;

            $.getJSON(uri + '/' + id)
                .done(function (data) {
                    $('#library').text(ItemDetails(data));
                    $("p").addClass("list-group-item list-group-item-info");
                })
                .fail(function (jqXHR, textStatus, err) {
                    $('#library').text('Error: ' + err);

                });
        }

 

Startup.cs

In the following code, we mention the “AddMvc()” in configuration service method. It will help to access the MVC related information at runtime.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace DotNetCoreExtentions
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseFileServer();
            app.UseMvc();
        }
    }
}

Output 1

Output 1

Output 1

Json Output 1

Json Output 1

Json Output 1

Output 2

Output 2

Output 2

Json Output 2

Json Output 2

Json Output 2

References

Conclusion

Thus, we learned how to create Rest API or Web API with ASP.NET Core 1.0 when starting from scratch. I hope you liked this article. Please share your valuable suggestions and feedback.

Create An Aurelia Single Page Applications In ASP.NET Core 1.0


Introduction

In our previous article, we studied How to configure Aurelia Single Page applications in ASP.NET Core 1.0. Now, we are going to create Aurelia single page Applications in ASP.NET Core 1.0.

Aurelia

Aurelia is a JavaScript client framework for mobile, desktop, Web and we can create a single page applications using the Aurelia framework.

Configuring Aurelia in ASP.NET Core 1.0

In our previous article, we mentioned a detailed description about How to configure Aurelia Single Page applications in ASP.NET Core 1.0. Thus, we only noticed the important steps of Aurelia configuration in ASP.NET Core 1.0. Install jspm and Aurelia framework through the command.

  • Download and Install : Node.js
  • Download and Install : Git – Downloads
  • Install jspm [ Command : “npm install -g jspm” ].
  • jspm Initialization [ Command : “jspm init” ]
  • Install Aurelia framework in ASP.NET Core 1.0 [ Command : “jspm install aurelia-framework” ]
  • Install Aurelia bootstrapper in ASP.NET Core 1.0 [ Command : “jspm install aurelia-bootstrapper” ]

Project Structure

Click “show all files icon” in Solution Explorer. You can see the jspm_packages reference and config.js inside the wwwroot.

Aurelia Project Structure In ASP.NET Core 1.0

Aurelia Project Structure In ASP.NET Core 1.0

Aurelia Reference in index.html page

We are going to add Aurelia references in “index.html” page because in ASP.NET Core 1.0, we run index.html file as a start page in default. Don’t worry. We can mention other pages also but we need to do some customization in the code.

Index.html

The code given below contains the reference of “jspm_packages/system.js” & “config.js”. The body tag contains the “aurelia-app” or an entry point of Aurelia app and it automatically detects the app.js file in our root folder (what we mention baseURL on jspm installation) or wwwroot. The “System.import(“Aurelia-Bootstrapper”)” will help to import Aurelia-Bootstrapper references in the body.

Index Page

Index Page

 

config.js

JSON file contains all the details about Aurelia configuration.

System.config({
  baseURL: "/",
  defaultJSExtensions: true,
  transpiler: "babel",
  babelOptions: {
    "optional": [
      "runtime",
      "optimisation.modules.system"
    ]
  },
  paths: {
    "github:*": "jspm_packages/github/*",
    "npm:*": "jspm_packages/npm/*"
  },

  map: {
    "aurelia-bootstrapper": "npm:aurelia-bootstrapper@2.0.1",
    "aurelia-framework": "npm:aurelia-framework@1.0.8",
    "aurelia-pal-browser": "npm:aurelia-pal-browser@1.1.0",
    "babel": "npm:babel-core@5.8.38",
    "babel-runtime": "npm:babel-runtime@5.8.38",
    "core-js": "npm:core-js@1.2.7",
    "github:jspm/nodelibs-assert@0.1.0": {
      "assert": "npm:assert@1.4.1"
    },
    "github:jspm/nodelibs-buffer@0.1.0": {
      "buffer": "npm:buffer@3.6.0"
    },
    "github:jspm/nodelibs-path@0.1.0": {
      "path-browserify": "npm:path-browserify@0.0.0"
    },
    "github:jspm/nodelibs-process@0.1.2": {
      "process": "npm:process@0.11.9"
    },
    "github:jspm/nodelibs-util@0.1.0": {
      "util": "npm:util@0.10.3"
    },
    "github:jspm/nodelibs-vm@0.1.0": {
      "vm-browserify": "npm:vm-browserify@0.0.4"
    },
    "npm:assert@1.4.1": {
      "assert": "github:jspm/nodelibs-assert@0.1.0",
      "buffer": "github:jspm/nodelibs-buffer@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.2",
      "util": "npm:util@0.10.3"
    },
    "npm:aurelia-binding@1.1.1": {
      "aurelia-logging": "npm:aurelia-logging@1.2.0",
      "aurelia-metadata": "npm:aurelia-metadata@1.0.3",
      "aurelia-pal": "npm:aurelia-pal@1.2.0",
      "aurelia-task-queue": "npm:aurelia-task-queue@1.1.0"
    },
    "npm:aurelia-bootstrapper@2.0.1": {
      "aurelia-event-aggregator": "npm:aurelia-event-aggregator@1.0.1",
      "aurelia-framework": "npm:aurelia-framework@1.0.8",
      "aurelia-history": "npm:aurelia-history@1.0.0",
      "aurelia-history-browser": "npm:aurelia-history-browser@1.0.0",
      "aurelia-loader-default": "npm:aurelia-loader-default@1.0.0",
      "aurelia-logging-console": "npm:aurelia-logging-console@1.0.0",
      "aurelia-pal": "npm:aurelia-pal@1.2.0",
      "aurelia-pal-browser": "npm:aurelia-pal-browser@1.1.0",
      "aurelia-polyfills": "npm:aurelia-polyfills@1.1.1",
      "aurelia-router": "npm:aurelia-router@1.1.1",
      "aurelia-templating": "npm:aurelia-templating@1.2.0",
      "aurelia-templating-binding": "npm:aurelia-templating-binding@1.2.0",
      "aurelia-templating-resources": "npm:aurelia-templating-resources@1.2.0",
      "aurelia-templating-router": "npm:aurelia-templating-router@1.0.1"
    },
    "npm:aurelia-dependency-injection@1.3.0": {
      "aurelia-metadata": "npm:aurelia-metadata@1.0.3",
      "aurelia-pal": "npm:aurelia-pal@1.2.0"
    },
    "npm:aurelia-event-aggregator@1.0.1": {
      "aurelia-logging": "npm:aurelia-logging@1.2.0"
    },
    "npm:aurelia-framework@1.0.8": {
      "aurelia-binding": "npm:aurelia-binding@1.1.1",
      "aurelia-dependency-injection": "npm:aurelia-dependency-injection@1.3.0",
      "aurelia-loader": "npm:aurelia-loader@1.0.0",
      "aurelia-logging": "npm:aurelia-logging@1.2.0",
      "aurelia-metadata": "npm:aurelia-metadata@1.0.3",
      "aurelia-pal": "npm:aurelia-pal@1.2.0",
      "aurelia-path": "npm:aurelia-path@1.1.1",
      "aurelia-task-queue": "npm:aurelia-task-queue@1.1.0",
      "aurelia-templating": "npm:aurelia-templating@1.2.0"
    },
    "npm:aurelia-history-browser@1.0.0": {
      "aurelia-history": "npm:aurelia-history@1.0.0",
      "aurelia-pal": "npm:aurelia-pal@1.2.0"
    },
    "npm:aurelia-loader-default@1.0.0": {
      "aurelia-loader": "npm:aurelia-loader@1.0.0",
      "aurelia-metadata": "npm:aurelia-metadata@1.0.3",
      "aurelia-pal": "npm:aurelia-pal@1.2.0"
    },
    "npm:aurelia-loader@1.0.0": {
      "aurelia-metadata": "npm:aurelia-metadata@1.0.3",
      "aurelia-path": "npm:aurelia-path@1.1.1"
    },
    "npm:aurelia-logging-console@1.0.0": {
      "aurelia-logging": "npm:aurelia-logging@1.2.0"
    },
    "npm:aurelia-metadata@1.0.3": {
      "aurelia-pal": "npm:aurelia-pal@1.2.0"
    },
    "npm:aurelia-pal-browser@1.1.0": {
      "aurelia-pal": "npm:aurelia-pal@1.2.0"
    },
    "npm:aurelia-polyfills@1.1.1": {
      "aurelia-pal": "npm:aurelia-pal@1.2.0"
    },
    "npm:aurelia-route-recognizer@1.1.0": {
      "aurelia-path": "npm:aurelia-path@1.1.1"
    },
    "npm:aurelia-router@1.1.1": {
      "aurelia-dependency-injection": "npm:aurelia-dependency-injection@1.3.0",
      "aurelia-event-aggregator": "npm:aurelia-event-aggregator@1.0.1",
      "aurelia-history": "npm:aurelia-history@1.0.0",
      "aurelia-logging": "npm:aurelia-logging@1.2.0",
      "aurelia-path": "npm:aurelia-path@1.1.1",
      "aurelia-route-recognizer": "npm:aurelia-route-recognizer@1.1.0"
    },
    "npm:aurelia-task-queue@1.1.0": {
      "aurelia-pal": "npm:aurelia-pal@1.2.0"
    },
    "npm:aurelia-templating-binding@1.2.0": {
      "aurelia-binding": "npm:aurelia-binding@1.1.1",
      "aurelia-logging": "npm:aurelia-logging@1.2.0",
      "aurelia-templating": "npm:aurelia-templating@1.2.0"
    },
    "npm:aurelia-templating-resources@1.2.0": {
      "aurelia-binding": "npm:aurelia-binding@1.1.1",
      "aurelia-dependency-injection": "npm:aurelia-dependency-injection@1.3.0",
      "aurelia-loader": "npm:aurelia-loader@1.0.0",
      "aurelia-logging": "npm:aurelia-logging@1.2.0",
      "aurelia-metadata": "npm:aurelia-metadata@1.0.3",
      "aurelia-pal": "npm:aurelia-pal@1.2.0",
      "aurelia-path": "npm:aurelia-path@1.1.1",
      "aurelia-task-queue": "npm:aurelia-task-queue@1.1.0",
      "aurelia-templating": "npm:aurelia-templating@1.2.0"
    },
    "npm:aurelia-templating-router@1.0.1": {
      "aurelia-binding": "npm:aurelia-binding@1.1.1",
      "aurelia-dependency-injection": "npm:aurelia-dependency-injection@1.3.0",
      "aurelia-logging": "npm:aurelia-logging@1.2.0",
      "aurelia-metadata": "npm:aurelia-metadata@1.0.3",
      "aurelia-pal": "npm:aurelia-pal@1.2.0",
      "aurelia-path": "npm:aurelia-path@1.1.1",
      "aurelia-router": "npm:aurelia-router@1.1.1",
      "aurelia-templating": "npm:aurelia-templating@1.2.0"
    },
    "npm:aurelia-templating@1.2.0": {
      "aurelia-binding": "npm:aurelia-binding@1.1.1",
      "aurelia-dependency-injection": "npm:aurelia-dependency-injection@1.3.0",
      "aurelia-loader": "npm:aurelia-loader@1.0.0",
      "aurelia-logging": "npm:aurelia-logging@1.2.0",
      "aurelia-metadata": "npm:aurelia-metadata@1.0.3",
      "aurelia-pal": "npm:aurelia-pal@1.2.0",
      "aurelia-path": "npm:aurelia-path@1.1.1",
      "aurelia-task-queue": "npm:aurelia-task-queue@1.1.0"
    },
    "npm:babel-runtime@5.8.38": {
      "process": "github:jspm/nodelibs-process@0.1.2"
    },
    "npm:buffer@3.6.0": {
      "base64-js": "npm:base64-js@0.0.8",
      "child_process": "github:jspm/nodelibs-child_process@0.1.0",
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "ieee754": "npm:ieee754@1.1.8",
      "isarray": "npm:isarray@1.0.0",
      "process": "github:jspm/nodelibs-process@0.1.2"
    },
    "npm:core-js@1.2.7": {
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "path": "github:jspm/nodelibs-path@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.2",
      "systemjs-json": "github:systemjs/plugin-json@0.1.2"
    },
    "npm:inherits@2.0.1": {
      "util": "github:jspm/nodelibs-util@0.1.0"
    },
    "npm:path-browserify@0.0.0": {
      "process": "github:jspm/nodelibs-process@0.1.2"
    },
    "npm:process@0.11.9": {
      "assert": "github:jspm/nodelibs-assert@0.1.0",
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "vm": "github:jspm/nodelibs-vm@0.1.0"
    },
    "npm:util@0.10.3": {
      "inherits": "npm:inherits@2.0.1",
      "process": "github:jspm/nodelibs-process@0.1.2"
    },
    "npm:vm-browserify@0.0.4": {
      "indexof": "npm:indexof@0.0.1"
    }
  }
});

package.json

JSON file contains all the dependencies of Aurelia.

{
  "jspm": {
    "directories": {
      "baseURL": "wwwroot"
    },
    "dependencies": {
      "aurelia-bootstrapper": "npm:aurelia-bootstrapper@^2.0.1",
      "aurelia-framework": "npm:aurelia-framework@^1.0.8",
      "aurelia-pal-browser": "npm:aurelia-pal-browser@^1.1.0"
    },
    "devDependencies": {
      "babel": "npm:babel-core@^5.8.24",
      "babel-runtime": "npm:babel-runtime@^5.8.24",
      "core-js": "npm:core-js@^1.1.4"
    }
  }
}

app.js

We have created one more staticfile or app.js inside the wwwroot or Webroot. The file given below contains the syntax as “export”. It will help to export the entire class details to correspondence app.html as Controller and View name relation in ASP.NET MVC.

export class App
{
    constructor()
    {
        this.Message = "Aurelia in Asp.Net Core 1.0 !!";
    }
}

app.html 

Now, we are going to create one more HTML file inside the wwwroot or Webroot. Here, we will bind the app.js methods,functions etc. inside the curly bracket “${}”.

<template>
<div>${Message}</div>
</template>

Project.json

When we want to call Staticfiles in ASP.NET Core 1.0, we need to add Staticfiles dependency in project.json.

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.AspNetCore.StaticFiles": "1.1.0"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

Configuration in Startup.cs Class

The code given below in UseFileServer() will help to call staticfiles in ASP.NET Core 1.0.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace AureliaHelloWorld
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseFileServer();

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }
}

Possible Error

I think possibly we will get the given error below.

Error in Aurelia Browser

Error in Aurelia Browser

Therefore, we need to install aurelia-pal Browser in our project.

Command

“jspm install npm:aurelia-pal-browser”

Output

Finally, we got it.

Aurelia Output

Aurelia Output

Reference

Conclusion

We learned how to create an Aurelia single page application in ASP.NET Core 1.0 and I hope you liked this article. Please share your valuable suggestions and feedback.

Configuration : Aurelia Single Page Applications In ASP.NET Core 1.0


Introduction

We all are familiar with SPA or Single Page Applications like Angular 2 in development. Aurelia is another famous Single Page Application development technique in the market similar to Angular 2 but syntactically different. Now, we are going to configure Aurelia Single Page Applications in ASP.NET Core 1.0.

Before reading this article, you must read the articles given below for ASP.NET Core knowledge.

Configuring Aurelia SPA in ASP.NET Core 1.0

The following steps need to be followed to configure Aurelia Single Page Applications in ASP.NET Core 1.0.

Install Node.Js

Node.js is very powerful JavaScript-based framework built on Chrome’s V8 JavaScript Engine. Node.js’ package ecosystem and npm are the largest ecosystems of open source libraries in the world.

Download and install Node.js on your machine : Node.js

nodejs-rajeeshmenoth

Nodejs : Download & Install

After completing the installation, we can check the current running version of Node.js in our machine through command prompt.

Command for Version Checking  – “node -v”

nodejs-version-rajeeshmenoth

Command for Nodejs Version

Install Git

Download and install appropriate Git on your machine from Git – Downloads

Install jspm

jspm or JavaScript Package Manager is a package manager for the SystemJS universal module loader and it is built on top of the dynamic ES6 module loader.

jspm installation command – “npm install -g jspm”

jspm-installation

After installing, we can check the current running version of jspm on our machine through command prompt, using the following command.

“jspm -v”

jspm version

jspm version

Setting Project Location

The following command will help to change our current “C Drive” to “F Drive” because currently our Aurelia project is saved into “F Drive”.

Drive Changing to Prjoect Location

Drive Change to Exact Aurelia Project Location in our machine

jspm Initialization

Now, we are going to install jspm in our ASP.NET Core 1.0 application.

“jspm init”

During the jspm initialization, it will ask a few questions. We have to enter three values in the following questions.

1.Enter server baseURL (public folder path) [./]

wwwroot ( I have saved all jspm references into Webroot or wwwroot but you can choose any folder ).

2. Do you wish to use a transpiler?[yes]:

yes ( Transpiler is similar to Compiler. It converts ES2015 to ES5 ).

3. Which ES6 transpiler would you like to use, Babel, TypeScript or Traceur ? [traceur] :

Babel ( You can choose either Babel or TypeScript ).

jspm Initialization

jspm Initialization

Install Aurelia Framework in ASP.NET Core 1.0

The following command will help to install Aurelia framework in ASP.NET Core 1.0.

“jspm install aurelia-framework”

Aurelia Framework Installation

Aurelia Framework Installation

Install Aurelia bootstrapper in ASP.NET Core 1.0

The following command will help to install Aurelia bootstrapper in ASP.NET Core 1.0.

“jspm install aurelia-bootstrapper”

Aurelia Bootstrapper Installation

Aurelia Bootstrapper Installation

Project Structure

Click “show all files icon” in Solution Explorer. Then, you can see the jspm_packages reference and config.js inside the wwwroot.

Aurelia Project Structure In ASP.NET Core 1.0

Aurelia Project Structure In ASP.NET Core 1.0

config.js

The following json file contains all the details about Aurelia configuration.

System.config({
  baseURL: "/",
  defaultJSExtensions: true,
  transpiler: "babel",
  babelOptions: {
    "optional": [
      "runtime",
      "optimisation.modules.system"
    ]
  },
  paths: {
    "github:*": "jspm_packages/github/*",
    "npm:*": "jspm_packages/npm/*"
  },

  map: {
    "aurelia-bootstrapper": "npm:aurelia-bootstrapper@2.0.1",
    "aurelia-framework": "npm:aurelia-framework@1.0.8",
    "aurelia-pal-browser": "npm:aurelia-pal-browser@1.1.0",
    "babel": "npm:babel-core@5.8.38",
    "babel-runtime": "npm:babel-runtime@5.8.38",
    "core-js": "npm:core-js@1.2.7",
    "github:jspm/nodelibs-assert@0.1.0": {
      "assert": "npm:assert@1.4.1"
    },
    "github:jspm/nodelibs-buffer@0.1.0": {
      "buffer": "npm:buffer@3.6.0"
    },
    "github:jspm/nodelibs-path@0.1.0": {
      "path-browserify": "npm:path-browserify@0.0.0"
    },
    "github:jspm/nodelibs-process@0.1.2": {
      "process": "npm:process@0.11.9"
    },
    "github:jspm/nodelibs-util@0.1.0": {
      "util": "npm:util@0.10.3"
    },
    "github:jspm/nodelibs-vm@0.1.0": {
      "vm-browserify": "npm:vm-browserify@0.0.4"
    },
    "npm:assert@1.4.1": {
      "assert": "github:jspm/nodelibs-assert@0.1.0",
      "buffer": "github:jspm/nodelibs-buffer@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.2",
      "util": "npm:util@0.10.3"
    },
    "npm:aurelia-binding@1.1.1": {
      "aurelia-logging": "npm:aurelia-logging@1.2.0",
      "aurelia-metadata": "npm:aurelia-metadata@1.0.3",
      "aurelia-pal": "npm:aurelia-pal@1.2.0",
      "aurelia-task-queue": "npm:aurelia-task-queue@1.1.0"
    },
    "npm:aurelia-bootstrapper@2.0.1": {
      "aurelia-event-aggregator": "npm:aurelia-event-aggregator@1.0.1",
      "aurelia-framework": "npm:aurelia-framework@1.0.8",
      "aurelia-history": "npm:aurelia-history@1.0.0",
      "aurelia-history-browser": "npm:aurelia-history-browser@1.0.0",
      "aurelia-loader-default": "npm:aurelia-loader-default@1.0.0",
      "aurelia-logging-console": "npm:aurelia-logging-console@1.0.0",
      "aurelia-pal": "npm:aurelia-pal@1.2.0",
      "aurelia-pal-browser": "npm:aurelia-pal-browser@1.1.0",
      "aurelia-polyfills": "npm:aurelia-polyfills@1.1.1",
      "aurelia-router": "npm:aurelia-router@1.1.1",
      "aurelia-templating": "npm:aurelia-templating@1.2.0",
      "aurelia-templating-binding": "npm:aurelia-templating-binding@1.2.0",
      "aurelia-templating-resources": "npm:aurelia-templating-resources@1.2.0",
      "aurelia-templating-router": "npm:aurelia-templating-router@1.0.1"
    },
    "npm:aurelia-dependency-injection@1.3.0": {
      "aurelia-metadata": "npm:aurelia-metadata@1.0.3",
      "aurelia-pal": "npm:aurelia-pal@1.2.0"
    },
    "npm:aurelia-event-aggregator@1.0.1": {
      "aurelia-logging": "npm:aurelia-logging@1.2.0"
    },
    "npm:aurelia-framework@1.0.8": {
      "aurelia-binding": "npm:aurelia-binding@1.1.1",
      "aurelia-dependency-injection": "npm:aurelia-dependency-injection@1.3.0",
      "aurelia-loader": "npm:aurelia-loader@1.0.0",
      "aurelia-logging": "npm:aurelia-logging@1.2.0",
      "aurelia-metadata": "npm:aurelia-metadata@1.0.3",
      "aurelia-pal": "npm:aurelia-pal@1.2.0",
      "aurelia-path": "npm:aurelia-path@1.1.1",
      "aurelia-task-queue": "npm:aurelia-task-queue@1.1.0",
      "aurelia-templating": "npm:aurelia-templating@1.2.0"
    },
    "npm:aurelia-history-browser@1.0.0": {
      "aurelia-history": "npm:aurelia-history@1.0.0",
      "aurelia-pal": "npm:aurelia-pal@1.2.0"
    },
    "npm:aurelia-loader-default@1.0.0": {
      "aurelia-loader": "npm:aurelia-loader@1.0.0",
      "aurelia-metadata": "npm:aurelia-metadata@1.0.3",
      "aurelia-pal": "npm:aurelia-pal@1.2.0"
    },
    "npm:aurelia-loader@1.0.0": {
      "aurelia-metadata": "npm:aurelia-metadata@1.0.3",
      "aurelia-path": "npm:aurelia-path@1.1.1"
    },
    "npm:aurelia-logging-console@1.0.0": {
      "aurelia-logging": "npm:aurelia-logging@1.2.0"
    },
    "npm:aurelia-metadata@1.0.3": {
      "aurelia-pal": "npm:aurelia-pal@1.2.0"
    },
    "npm:aurelia-pal-browser@1.1.0": {
      "aurelia-pal": "npm:aurelia-pal@1.2.0"
    },
    "npm:aurelia-polyfills@1.1.1": {
      "aurelia-pal": "npm:aurelia-pal@1.2.0"
    },
    "npm:aurelia-route-recognizer@1.1.0": {
      "aurelia-path": "npm:aurelia-path@1.1.1"
    },
    "npm:aurelia-router@1.1.1": {
      "aurelia-dependency-injection": "npm:aurelia-dependency-injection@1.3.0",
      "aurelia-event-aggregator": "npm:aurelia-event-aggregator@1.0.1",
      "aurelia-history": "npm:aurelia-history@1.0.0",
      "aurelia-logging": "npm:aurelia-logging@1.2.0",
      "aurelia-path": "npm:aurelia-path@1.1.1",
      "aurelia-route-recognizer": "npm:aurelia-route-recognizer@1.1.0"
    },
    "npm:aurelia-task-queue@1.1.0": {
      "aurelia-pal": "npm:aurelia-pal@1.2.0"
    },
    "npm:aurelia-templating-binding@1.2.0": {
      "aurelia-binding": "npm:aurelia-binding@1.1.1",
      "aurelia-logging": "npm:aurelia-logging@1.2.0",
      "aurelia-templating": "npm:aurelia-templating@1.2.0"
    },
    "npm:aurelia-templating-resources@1.2.0": {
      "aurelia-binding": "npm:aurelia-binding@1.1.1",
      "aurelia-dependency-injection": "npm:aurelia-dependency-injection@1.3.0",
      "aurelia-loader": "npm:aurelia-loader@1.0.0",
      "aurelia-logging": "npm:aurelia-logging@1.2.0",
      "aurelia-metadata": "npm:aurelia-metadata@1.0.3",
      "aurelia-pal": "npm:aurelia-pal@1.2.0",
      "aurelia-path": "npm:aurelia-path@1.1.1",
      "aurelia-task-queue": "npm:aurelia-task-queue@1.1.0",
      "aurelia-templating": "npm:aurelia-templating@1.2.0"
    },
    "npm:aurelia-templating-router@1.0.1": {
      "aurelia-binding": "npm:aurelia-binding@1.1.1",
      "aurelia-dependency-injection": "npm:aurelia-dependency-injection@1.3.0",
      "aurelia-logging": "npm:aurelia-logging@1.2.0",
      "aurelia-metadata": "npm:aurelia-metadata@1.0.3",
      "aurelia-pal": "npm:aurelia-pal@1.2.0",
      "aurelia-path": "npm:aurelia-path@1.1.1",
      "aurelia-router": "npm:aurelia-router@1.1.1",
      "aurelia-templating": "npm:aurelia-templating@1.2.0"
    },
    "npm:aurelia-templating@1.2.0": {
      "aurelia-binding": "npm:aurelia-binding@1.1.1",
      "aurelia-dependency-injection": "npm:aurelia-dependency-injection@1.3.0",
      "aurelia-loader": "npm:aurelia-loader@1.0.0",
      "aurelia-logging": "npm:aurelia-logging@1.2.0",
      "aurelia-metadata": "npm:aurelia-metadata@1.0.3",
      "aurelia-pal": "npm:aurelia-pal@1.2.0",
      "aurelia-path": "npm:aurelia-path@1.1.1",
      "aurelia-task-queue": "npm:aurelia-task-queue@1.1.0"
    },
    "npm:babel-runtime@5.8.38": {
      "process": "github:jspm/nodelibs-process@0.1.2"
    },
    "npm:buffer@3.6.0": {
      "base64-js": "npm:base64-js@0.0.8",
      "child_process": "github:jspm/nodelibs-child_process@0.1.0",
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "ieee754": "npm:ieee754@1.1.8",
      "isarray": "npm:isarray@1.0.0",
      "process": "github:jspm/nodelibs-process@0.1.2"
    },
    "npm:core-js@1.2.7": {
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "path": "github:jspm/nodelibs-path@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.2",
      "systemjs-json": "github:systemjs/plugin-json@0.1.2"
    },
    "npm:inherits@2.0.1": {
      "util": "github:jspm/nodelibs-util@0.1.0"
    },
    "npm:path-browserify@0.0.0": {
      "process": "github:jspm/nodelibs-process@0.1.2"
    },
    "npm:process@0.11.9": {
      "assert": "github:jspm/nodelibs-assert@0.1.0",
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "vm": "github:jspm/nodelibs-vm@0.1.0"
    },
    "npm:util@0.10.3": {
      "inherits": "npm:inherits@2.0.1",
      "process": "github:jspm/nodelibs-process@0.1.2"
    },
    "npm:vm-browserify@0.0.4": {
      "indexof": "npm:indexof@0.0.1"
    }
  }
});

package.json

The following JSON file contains all the dependencies of Aurelia.

{
  "jspm": {
    "directories": {
      "baseURL": "wwwroot"
    },
    "dependencies": {
      "aurelia-bootstrapper": "npm:aurelia-bootstrapper@^2.0.1",
      "aurelia-framework": "npm:aurelia-framework@^1.0.8",
      "aurelia-pal-browser": "npm:aurelia-pal-browser@^1.1.0"
    },
    "devDependencies": {
      "babel": "npm:babel-core@^5.8.24",
      "babel-runtime": "npm:babel-runtime@^5.8.24",
      "core-js": "npm:core-js@^1.1.4"
    }
  }
}

Reference 

Conclusion

We learned how to configure Aurelia Single Page Applications in ASP.NET Core 1.0. I hope, you liked this article. Please share your valuable suggestions and feedback.

Middleware And Staticfiles in Asp.Net Core 1.0 – Part 2


Introduction

We will continue the second part of Middleware And Staticfiles in ASP.NET Core 1.0. Before reading this article, you must read my previous article Middleware And Staticfiles in Asp.Net Core 1.0 – Part 1 because I have explained some important parts in my previous article. In this article, I will teach you the remaining part of Middleware & Staticfiles in ASP.NET Core 1.0.

Before reading this article, you must read the articles given below for ASP.NET Core knowledge.

Assemblies Required

The preceding namespace contains PhysicalFileProvider, PathString, library for the path & directory libraries and other libraries.

using System.IO;
using Microsoft.Extensions.FileProviders;

ASP.NET Core 1.0 StartUp Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.FileProviders;
using System.IO;

namespace DotnetCore
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDirectoryBrowser();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            
            app.UseStaticFiles(); // wwwroot inside file access.
            app.UseDefaultFiles(); // Default startup file of app.
            //app.UseWelcomePage(); // Welcome Page.
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(
           Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot","StaticFiles")),
                RequestPath = new PathString("/InsideRoot") // accessing wwwroot inside folder contents.
            });

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"StaticFiles","Home")),
                RequestPath = new PathString("/OutsideRoot") // accessing outside wwwroot folder contents.
            });
            app.UseDirectoryBrowser(new DirectoryBrowserOptions()
            {
                FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"StaticFiles", "Home")),
                RequestPath = new PathString("/Directory") // listing directory details for specified folder.
            });

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(
           Path.Combine(Directory.GetCurrentDirectory(), @"StaticFiles", "Home")),
                RequestPath = new PathString("/Directory") // accessing listed directory contents.
            });
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }
}

Staticfiles are Inside and Outside of wwwroot or Webroot

In the project structure given below, Staticfiles are placed inside and outside of the wwwroot or Webroot.

Asp.Net Core Folder Structure

Asp.Net Core 1.0 : Folder Structure

Serving Staticfiles are Inside and Outside of wwwroot or Webroot

  • Accessing Inside folder Staticfiles contents in wwwroot or Webroot
  • Accessing Outside folder Staticfiles contents wwwroot or Webroot
  • Directory browsing in ASP.NET Core 1.0
  • Accessing Directory browsing contents in ASP.NET Core 1.0

Accessing Inside folder Staticfiles contents in wwwroot or Webroot

In the code given below, Staticfiles are placed inside the “StaticFiles” folder. We created the customized path string “/InsideRoot” to access Staticfiles.

app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(
           Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot","StaticFiles")),
                RequestPath = new PathString("/InsideRoot") // accessing wwwroot inside folder contents.
            });

Output

StaticFiles is Inside the folder

StaticFiles is Inside the folder

Accessing Outside folder Staticfiles contents wwwroot or Webroot

In the code given below, Staticfiles are placed outside the wwwroot or Webroot and placed inside the Home folder in StaticFiles folder. We created the customized path string “/OutsideRoot” to access Staticfiles.

app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"StaticFiles","Home")),
                RequestPath = new PathString("/OutsideRoot") // accessing outside wwwroot folder contents.
            });

Output

Outside the wwwroot

Outside the wwwroot

Directory browsing in ASP.NET Core 1.0

It allows the user of your Web app to see all the list of directories and files within a specified directory. Directory browsing is disabled by default for security reasons because it will show the secret files in the directory. To enable directory browsing in ASP.NET Core 1.0, call “UseDirectoryBrowser” extension method from Startup.Configure.

We created the customized path string “/Directory” to access the directory.


app.UseDirectoryBrowser(new DirectoryBrowserOptions()
            {
                FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"StaticFiles", "Home")),
                RequestPath = new PathString("/Directory") // listing directory details for specified folder.
            });

Output

Directory Browsing in ASP.NET Core 1,0

Directory Browsing in ASP.NET Core 1,0

Accessing Directory browsing contents in ASP.NET Core 1.0

If you want to access the directory contents in ASP.NET Core 1.0, add the same path string in “UseStaticFiles” extension method.


app.UseDirectoryBrowser(new DirectoryBrowserOptions()
            {
                FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"StaticFiles", "Home")),
                RequestPath = new PathString("/Directory") // listing directory details for specified folder.
            });

app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(
           Path.Combine(Directory.GetCurrentDirectory(), @"StaticFiles", "Home")),
                RequestPath = new PathString("/Directory") // accessing listed directory contents.
            });

Reference

Conclusion

We learned Middleware & Staticfiles in ASP.NET Core 1.0 Part Two and I hope you liked this article. Please share your valuable suggestions and feedback.

%d bloggers like this: