Advertisements

QR Code Generator in ASP.NET Core Using Zxing.Net


Introduction

In this article, we will explain how to create a QR Code Generator in ASP.NET Core 1.0, using Zxing.Net.

Background

I tried to create a QR Code Generator in ASP.NET Core, using third party libraries but in most of the cases codes are not fully supported in ASP.NET Core because of some version issues etc. I searched a lot in Google but finally I found “Zxing.Net” and it is a library, which supports decoding and generating of the barcodes. I had a discussion with MicJahn and came up  with a great solution.

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

Zxing.Net

A library, which supports decoding and generating of the barcodes (Example: QR Code, PDF 417, EAN, UPC, Aztec, Data Matrix, Codabar) within the images.

Assemblies Required

The assemblies given below are required for QR Code Generator.

using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.IO;
using ZXing.QrCode;

Packages required

We need the packages given below for drawing and creating QR Code Generator.

"CoreCompat.System.Drawing": "1.0.0-beta006",    
"ZXing.Net": "0.15.0" 

C#

QRCodeTagHelper class given below contains QR Code Generator methods etc.

namespace QRCodeApp {  
    [HtmlTargetElement("qrcode")]  
    public class QRCodeTagHelper: TagHelper {  
        public override void Process(TagHelperContext context, TagHelperOutput output) {  
            var QrcodeContent = context.AllAttributes["content"].Value.ToString();  
            var alt = context.AllAttributes["alt"].Value.ToString();  
            var width = 250; // width of the Qr Code    
            var height = 250; // height of the Qr Code    
            var margin = 0;  
            var qrCodeWriter = new ZXing.BarcodeWriterPixelData {  
                Format = ZXing.BarcodeFormat.QR_CODE,  
                    Options = new QrCodeEncodingOptions {  
                        Height = height, Width = width, Margin = margin  
                    }  
            };  
            var pixelData = qrCodeWriter.Write(QrcodeContent);  
            // creating a bitmap from the raw pixel data; if only black and white colors are used it makes no difference    
            // that the pixel data ist BGRA oriented and the bitmap is initialized with RGB    
            using(var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb))  
            using(var ms = new MemoryStream()) {  
                var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);  
                try {  
                    // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image    
                    System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length);  
                } finally {  
                    bitmap.UnlockBits(bitmapData);  
                }  
                // save to stream as PNG    
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);  
                output.TagName = "img";  
                output.Attributes.Clear();  
                output.Attributes.Add("width", width);  
                output.Attributes.Add("height", height);  
                output.Attributes.Add("alt", alt);  
                output.Attributes.Add("src", String.Format("data:image/png;base64,{0}", Convert.ToBase64String(ms.ToArray())));  
            }  
        }  
    }  
}   

Index.chtml

The code given below will display QR Code Generator.

@{  
    ViewData["Title"] = "Home";  
}  
   
<h2>@ViewData["Title"].</h2>  
<h3>@ViewData["Message"]</h3>  
   
A library which supports decoding and generating of barcodes (like QR Code, PDF 417, EAN, UPC, Aztec, Data Matrix, Codabar) within images.  
   
<qrcode alt="QR Code" content="https://rajeeshmenoth.wordpress.com/" />  
 https://rajeeshmenoth.wordpress.com/  

_ViewImports.cshtml

The code Injecting TagHelper given below is in the entire Application.

@addTagHelper "*, QRCodeApp"  

project.json

The dependencies given below are required to create QR Code Application.

{  
  "dependencies": {  
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",  
    "Microsoft.AspNetCore.Mvc": "1.1.2",  
    "Microsoft.AspNetCore.Mvc.Core": "1.1.2",  
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",  
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",  
    "Microsoft.AspNetCore.StaticFiles": "1.1.1",  
    "Microsoft.Extensions.Logging.Console": "1.0.0",  
    "CoreCompat.System.Drawing": "1.0.0-beta006",  
    "ZXing.Net": "0.15.0"  
  },  
   
  "tools": {  
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"  
  },  
   
  "frameworks": {  
    "net452": { }  
  },  
   
  "buildOptions": {  
    "emitEntryPoint": true,  
    "preserveCompilationContext": true  
  },  
   
  "publishOptions": {  
    "include": [  
      "wwwroot",  
      "web.config"  
    ]  
  },  
   
  "scripts": {  
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]  
  }  
}  

Output

QRCode Generator

QRCode Generator

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 create a QR Code Generator in ASP.NET Core 1.0 Using Zxing.Net. I hope, you liked this article. Please share your valuable suggestions and feedback.

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.

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.

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.

%d bloggers like this: