.NET Core Startup

In this article, we will learn about .Net Core Features & short overview on .Net Framework (existing), we will explore what changes made/added in new environment of .Net Core.

After that we are also going to explore ASP .NET Core Initial Template one by one, then perform some basic operations (CRUD) with data using MVC Core & Entity Framework Core. 

Topics to be discussed:

  1. Short Overview on .Net Framework
  2. What is .Net Core?
  3. What is ASP.Net Core?
  4. How to start?
  5. Detail Overview on initial sample application
    1. Global.json
    2. Properties
    3. wwwroot
    4. Controller
    5. Views
    6. appsettings.json
    7. bower.json
    8. bundleconfig.json
    9. program.cs
    10. project.json
    11. startup.cs
    12. web.config
  6. Working with data using
    1. ASP.Net Core &
    2. Entity Framework-7 (Core)
    3. MVC-6 (Core)

 

Ok, let’s start with our topic one by one to be clarified our thought on magical world of .Net.

.Net Framework:

The .NET Framework (pronounced dot net) is a software development platform developed by Microsoft. Provides tools and libraries that allow developers to develop applications.

Microsoft started development on the .NET Framework in the late 1990s originally under the name of Next Generation Windows Services (NGWS). By late 2001 the first beta versions of .NET 1.0 were released.

.Net Framework Releases:

Here I have provided a short overview on .Net Framework Version evaluation that all we knew about, but it was just recapping for better understand of .Net thinking & road-map.

core_1

So fur we have known all those releases, but what about the new announcement? Is .Net Core another framework? Ok, let’s just be easy, Step by step we will uncover all those issues.

.Net Today: Microsoft has announced a lots of exciting new innovations that is including with .Net in this year, among them the most power full is open source development (Any developer, Any app, Any platform). Learn …

core_2

 .Net Core:

Simply .NET Core is modern, lightweight, high performance modular platform for creating web apps and RESTful APIs that run on Cross-Platform (Windows, Linux and Mac).

It is smaller set/sub-set of .Net Framework (Full), that maintained by Microsoft & the .NET community on .

.Net Core Facilities:

  • Cross-platform that runs on Windows, macOS and Linux.
  • Open source.
  • Command-line tools that can be exercised at the command-line.
  • Compatible with .NET Framework, Xamarin and Mono, via the.
  • Flexible deployment.

Learn

 .NET Core Platform:

The .NET Core platform is made of several

  1. CoreFX – .NET Core foundational libraries
  2. CoreCLR – .NET Core runtime
  3. CLI – .NET Core command-line tools
  4. Roslyn – .NET Compiler Platform

 

Diagram of .Net Core vs .Net Framwork

core_3

.Net Core :

  1. .NET Core 1.1 released on 11/16/2016
  2. .NET Core 1.0 Preview 1 released on 10/24/2016
  3. .NET Core 0.1 released on 9/13/2016
  4. .NET Core 0.0 released on 6/27/2016
  5. .NET Core RC2(Release Candidate) released on 5/16/2016
  6. .NET Core RC1(Release Candidate) released on 11/18/2015

the latest .Net Core SDK (Runtime + Command line Tool) or Only Runtime.

.NET Core supports: Initially .NET core supports four types of application development, among them we will focus on ASP.Net Core application development.

  1. NET Core web apps,
  2. Command-line apps,
  3. Libraries, and
  4. Universal Windows Platform (UWP) apps.

ASP.Net Core:

is re-written new open source ASP.Net web framework for building web based application (web apps, IoT apps & mobile backends) that run on both full .Net Framework and .Net Core.

ASP.Net Core Facilities:

  1. Developed and run on Cross Platform (Windows, Mac and Linux).
  2. Open Source.
  3. Built on the .NET Core runtime & also on .NET Framework.
  4. Facility of dynamic compilation.
  5. Built in Dependency Injection (DI).
  6. MVC & Web Api Controller are unified, Inherited from same base class.
  7. New light-weight and modular HTTP request pipeline
  8. Ability to host on IIS or self-host in own process.
  9. Ships entirely as NuGet packages
  10. Smart tooling like (Bower, Grunt & Gulp).

Learn on ASP.Net Core

How to start?

Here are the quick installation guide for .

Steps:

  1. Install Visual Studio 2015 (provides a full-featured development environment).
  2. Make sure you have Visual Studio 2015
  3. Install the .NET Core preview for Visual Studio.
  4. Create a new .NET Core project
  5. Run the application

Learn on how to get started…

Anatomy of ASP.Net Core Initial Application:

Global.json

It is a JSON schema for the ASP.NET global configuration files, Contains the Solution information/metadata. In this file we can configure the sdk with version, architecture or runtime that specifies which processor architecture to target. Which runtime to target.

Let’s get the properties in details

  1. Projects: Specify the folders to search that contain the project.
  2. Packages: Specify the package location.
  3. Sdk: Specify information about the SDK.

Here is our global.json properties by default.

{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-preview2-003131"
  }
}

To get other’s properties information details go to > http://json.schemastore.org/global

"properties": {
  "projects": {
    "type": "array",
    "description": "A list of project folders relative to this file.",
    "items": {
      "type": "string"
    }
  },
  "packages": {
    "type": "string",
    "description": "The location to store packages"
  },
  "sdk": {
    "type": "object",
    "description": "Specify information about the SDK.",
    "properties": {
      "version": {
        "type": "string",
        "description": "The version of the SDK to use."
      },
      "architecture": {
        "enum": [ "x64", "x86" ],
        "description": "Specify which processor architecture to target."
      },
      "runtime": {
        "enum": [ "clr", "coreclr" ],
        "description": "Chose which runtime to target."
      }
    }
  }
}

Properties > launchSettings.json

JSON schema for the ASP.NET DebugSettings.json files.

This is where we can configure our debug profile by using IDE interface, another way to set properties is launchSetting.json file.

Right Click on Project Properties > Debug.

core_4

Here’s the configuration properties by default in launchSetting.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:17023/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "CoreMVC": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

We can add another profile as production to the json file using same command as IISExpress. Based on this environment profile we can show hide html tags on different environment mood, which is known as working with multi environment, later we will discuss on it.

"IIS Production": {
  "commandName": "IISExpress",
  "launchBrowser": true,
  "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Production"
  }
}

The new debug profile will appear like below image.

core_5

Let’s get the properties in details

  1. commandLineArgs: The arguments to pass to the command.
  2. workingDirectory: Sets the working directory of the command.
  3. launchBrowser: Set to true if the browser should be launched.
  4. launchUrl: The relative URL to launch in the browser.
  5. environmentVariables: Set the environment variables as key/value pairs.
  6. sdkVersion: Sets the version of the SDK.

To get other’s properties information details go to > http://json.schemastore.org/launchsettings

"properties": {
  "commandLineArgs": {
    "type": "string",
    "description": "The arguments to pass to the command.",
    "default": ""
  },
  "workingDirectory": {
    "type": "string",
    "description": "Sets the working directory of the command."
  },
  "launchBrowser": {
    "type": "boolean",
    "description": "Set to true if the browser should be launched.",
    "default": false
  },
  "launchUrl": {
    "type": "string",
    "description": "The relative URL to launch in the browser.",
    "format": "uri"
  },
  "environmentVariables": {
    "type": "object",
    "description": "Set the environment variables as key/value pairs.",
    "additionalProperties": {
      "type": "string"
    }
  },
  "sdkVersion": {
    "type": "string",
    "description": "Sets the version of the SDK."
  }
}

wwwroot

It’s all about serving directly to client. We need to serve static file all we need to add extension method UseStaticFiles() in startup class Configure method.

core_6

Then resolve the dependency package “Microsoft.AspNetCore.StaticFiles”: “1.0.0” for static file in project.json.

core_7

Controller

ASP.Net Core the Controllers are now unified, there’s no differences between MVC Controllers (Controller base class) & WebAPI Controllers (ApiController base class).

As you can see I have put it side by side to show the difference between both MVC & WebAPI Controller, both controller is being inherited from same controller.

core_8

Views

ASP.Net Core MVC views are .cshtml files as we know earlier version of ASP.Net MVC views that use the  to render views. Here I have showed MVC folder structure and the related .cshtml files in our ASP.Net Core application.

core_9

Learn more about & ……

appsettings.json

This is the application file that keep the configuration value of Key/Value pair. Previously this configuration were stored in web.config file.

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

We can add the connection string to the appsetting file and then we have accessed the connection in startup.

"ConnectionStrings": {
"dbConn": "Server=DESKTOP-5B67SHH;Database=TicketBooking;Trusted_Connection=True;MultipleActiveResultSets=true"
}

In startup file we added our service in ConfigureService method to enable the database connectivity through connection string.

public void ConfigureServices(IServiceCollection services)
{ 
    //Add database services.
    var connectionString = this.Configuration.GetConnectionString("dbConn");
    services.AddDbContext(options => options.UseSqlServer(connectionString));

    // Add framework services.
    services.AddMvc();
}
var connectionString = this.Configuration.GetConnectionString("dbConn");

Here GetConnectionString is an extension method that passing the connection name “dbConn”.

bower.json

is a Package manager the automatically add/update client side packages (like bootstrap, jquery etc) while we add/remove listed packages in json file.

{
  "name": "asp.net",
  "private": true,
  "dependencies": {
    "bootstrap": "3.3.6",
    "jquery": "2.2.0",
    "jquery-validation": "1.14.0",
    "jquery-validation-unobtrusive": "3.2.6"
  }
}

Here is the listed Client-side dependencies, there is another type of dependencies called Server-side dependencies.

Here private: true means it will refuse to publish, prevent accidental publication of private repositories.

core_10

To change bower installation location open .bowerrc and change the directory value.

core_11

{
  "directory": "wwwroot/lib"
}

Here you can see the dependencies have installed in wwwroot/lib folder as initial value.

core_12

bundleconfig.json

Bundling and minifying JavaScript, CSS and HTML files in any project. Download & install in visual studio 2015. Restart the IDE.

core_13

Task Runner Explorer will appear, to update all right click > Update all files > Run

core_14

Finally the output file will generated.

core_15

Here is a bundleconfig.json look like:

// Configure bundling and minification for the project.
// More info at https://go.microsoft.com/fwlink/?LinkId=808241
[
  {
    "outputFileName": "wwwroot/css/site.min.css",
    // An array of relative input file paths. Globbing patterns supported
    "inputFiles": [
      "wwwroot/css/site.css"
    ]
  },
  {
    "outputFileName": "wwwroot/js/site.min.js",
    "inputFiles": [
      "wwwroot/js/site.js"
    ],
    // Optionally specify minification options
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    // Optinally generate .map file
    "sourceMap": false
  }
]

program.cs

This is the main point of any ASP.Net core application that prepare the host to run all configured services. Here is the program.cs code snippet.

public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup()
            .Build();

        host.Run();
    }
}

In program.cs class simply do the job of configuring & launching a host using WebHostBuilder. As we know .Net Core application are Console Application that need to execute by host. WebHostBuilder is creating the host to bootstrap the server by UseKestrel() extension method, this means Kestrel server is going to host the application. There is another extension method UseIISIntegration() that is for IIS Server.

Here’s a diagram that clarify the process between IIS and ASP.NET Core applications.

core_16

Source: By Tom Dykstra, Rick Strahl, and Chris Ross

The WebHostBuilder is responsible for creating the host that will bootstrap the server for the app. learn about hosting…

We can say that .Net Core Application need a host to launch that define which is going to use, where to get the content files and specify the startup (middleware) services.

project.json

The project.json file store the application information, dependencies, and compiler settings. It’ has several section like Dependencies, Tools, Frameworks, Build Options and much more.

Here I have shown how the default project.json content looks like:

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Microsoft.AspNetCore.Routing": "1.0.1",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0"
  },

  "tools": {
    "BundlerMinifier.Core": "2.0.238",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "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",
      "**/*.cshtml",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "prepublish": [ "bower install", "dotnet bundle" ],
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

Let’s explorer the different section in it step by step:

project.json > Dependencies:

This section manages the project dependencies using key/value pair, we can add new dependencies if required, intellisense will help up to include with name & version.

core_17

As you can see from the upper image I was adding three new packages for database service, intellisense was helping me by showing with the version of that package. While I saved the changes it was automatically restoring the required dependencies from NuGet.

core_18

project.json > Tools:

This section manage & list command line tools, we can see IISIntegration. Tools is added by default which is a tools that contain dotnet publish iis command for publishing the application on IIS.

"tools": {
  "BundlerMinifier.Core": "2.0.238",
  "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
  "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
  "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
}

EntityFrameworkCore Tools ( tool for EF Core) Includes Commands

For Package Manager Console:

  • Scaffold-DbContext,
  • Add-Migration,
  • Udate-Database

For Command Window:

  • dotnet ef dbcontext scaffold

Both EF command shows here please have a close look on that.

If we disable the EntityFrameworkCore Tools and run the command it will show’s below error in Package Manager Console:

core_19

project.json > Frameworks:

Define the framework that support in this application, we can use multiple framework by configuring in this section.

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

Let’s clarify a bit more, in the framework section we are targeting netcoreapp1.0 framework. By configuring import section we can use several targeted packages/class libraries that are different from our application target version.

Here “dotnet5.6” for older .NET Core preview versions, and “portable-net45+win8” for portable class library (PCL) profiles, that known as Target Framework Monikers (TFMs).

We can use multiple framework by adding “net461”: {} in framework section.

"frameworks": {
  "net461": {
    "dependencies": {

    }
  },
  "netcoreapp1.0": {
    "dependencies": {
      "Microsoft.NETCore.App": {
        "version": "1.0.1",
        "type": "platform"
      }
    },
    "imports": [
      "dotnet5.6",
      "portable-net45+win8"
    ]
  }
}

You may notice that we have move our Microsoft.NETCore.App dependency from global dependencies to specific framework dependency section.

core_20

This is how we are using that support.

project.json > Build Options:

Options that are passed to compiler while build application.

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

project.json > RuntimeOptions:

Manage server garbage collection at application runtime.

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

project.json > PublishOptions:

This define the file/folder to include/exclude to/from the output folder while publish the application.

"publishOptions": {
  "include": [
    "wwwroot",
    "**/*.cshtml",
    "appsettings.json",
    "web.config"
  ]
}

project.json > Scripts:

Scripts is object type which specifies that scripts to run during build or publish the application.

"scripts": {
  "prepublish": [ "bower install", "dotnet bundle" ],
  "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
}

Learn more about file…….

startup.cs

This is the of every ASP.Net Core application, provide services that application required.

Here’s a diagram that show what happened at runtime while first-time it’s run.

core_21

In Startup class there are several method with different responsibilities. Here I have separated them, the very first is the constructor of Startup class. In the constructor IHostingEnvironment instance is passed as parameter to get the web hosting environment details.

public Startup(IHostingEnvironment env)
{
   var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
       Configuration = builder.Build();
} 

core_22

The instance of ConfigurationBuilder call the extension methods of multiple configuration source then chain calls together by order by as a fluent API.

core_23

public IConfigurationRoot Configuration { get; }

The IConfigurationRoot force the configuration values to be reloaded while application is running & configuration data is changed.

Next method is that is get called before Configure method. This section we can configure our required service to use at runtime in our application. Instance of IServiceCollection has passed as parameter. IServiceCollection Specifies collection of different services.

public void ConfigureServices(IServiceCollection services)
{
    //Add framework services.
    services.AddMvc();

    //Add database services.
    var connectionString = this.Configuration.GetConnectionString("dbConn");
    services.AddDbContext(options => options.UseSqlServer(connectionString));
}

In Startup class the Configure() mothod handle the HTTP request .

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
}

The full startup look like this:

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework 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(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

web.config

In ASP.Net Core the application configuration is now store in appsettings.json file, previously this was stored in file. Here is the default web.config file look like:




  

  
    
      
    
    
  

Web.config is using only for configuration while hosting in IIS. In handler section, this is where IIS handle a request by passing it to ASP.Net Core Module.


  

We can specify environment through web.config in IIS.


   
     
   

Working with Data Using ASP.Net Core MVC (CRUD)

Database Creation

Create a new database using SSMS, name it “TicketBooking”. Copy the below query & run it using query editor of SSMS.

USE [TicketBooking]
GO

/****** Object:  Table [dbo].[Ticket]    Script Date: 11/22/2016 1:25:55 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Ticket](
        [TicketID] [int] NOT NULL,
        [DestinationFrom] [nvarchar](50) NULL,
        [DestinationTo] [nvarchar](50) NULL,
        [TicketDate] [datetime] NULL,
        [TicketFee] [numeric](18, 2) NULL,
 CONSTRAINT [PK_Ticket] PRIMARY KEY CLUSTERED 
(
        [TicketID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Reverse Engineer:

Add Dependency Packages

"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
"Microsoft.EntityFrameworkCore.Tools":"1.0.0-preview2-final",
"Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.1"

Add Tools

"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"

Packages will automatically restored by IDE

core_25

Create the EF model from existing database.

  1. Tools –> NuGet Package Manager –> Package Manager Console
  2. Run the following command.
Scaffold-DbContext "Server=DESKTOP-5B67SHH;Database=TicketBooking;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

core_26

As you can see models has created in Models folder. Rewrite Entity from Database with below Command if database has any changes.

Scaffold-DbContext "Server=DESKTOP-5B67SHH;Database=TicketBooking;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -force

Context

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace CoreMVC.Models
{
    public partial class TicketBookingContext : DbContext
    {
        public TicketBookingContext(DbContextOptions options) : base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity(entity =>
            {
                entity.Property(e => e.TicketId).HasColumnName("TicketID");

                entity.Property(e => e.DestinationFrom).HasMaxLength(50);

                entity.Property(e => e.DestinationTo).HasMaxLength(50);

                entity.Property(e => e.TicketDate).HasColumnType("datetime");

                entity.Property(e => e.TicketFee).HasColumnType("numeric");

                entity.Property(e => e.Vat)
                    .HasColumnName("VAT")
                    .HasColumnType("numeric");
            });
        }

        public virtual DbSet Ticket { get; set; }
    }
}

MVC Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using CoreMVC.Models;
using Microsoft.EntityFrameworkCore;

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

namespace CoreMVC.Controllers
{
    public class TicketsController : Controller
    {
        private TicketBookingContext _ctx = null;
        public TicketsController(TicketBookingContext context)
        {
            _ctx = context;
        }

        // GET: Tickets/Index/
        public async Task Index()
        {
            List tickets = null;
            try
            {
                tickets = await _ctx.Ticket.ToListAsync();

            }
            catch (Exception ex)
            {
                ex.ToString();
            }

            return View(tickets);
        }

        // GET: Tickets/Create
        public IActionResult Create()
        {
            return View();
        }


        [ValidateAntiForgeryToken, HttpPost]
        public async Task Create(Ticket ticket)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    _ctx.Add(ticket);
                    await _ctx.SaveChangesAsync();
                    return RedirectToAction("Index");
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }
            return View(ticket);
        }


        // GET: Tickets/Details/5 
        public async Task Details(int? id)
        {
            object ticket = null;
            try
            {
                if ((id != null) && (id > 0))
                {
                    ticket = await _ctx.Ticket.SingleOrDefaultAsync(m => m.TicketId == id);
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            return View(ticket);
        }

        // GET: Tickets/Edit/5
        public async Task Edit(int? id)
        {
            object ticket = null;
            try
            {
                if ((id != null) && (id > 0))
                {
                    ticket = await _ctx.Ticket.SingleOrDefaultAsync(m => m.TicketId == id);
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            return View(ticket);
        }

        [ValidateAntiForgeryToken, HttpPost]
        public async Task Edit(int id, Ticket ticket)
        {
            if (id == ticket.TicketId)
            {
                if (ModelState.IsValid)
                {
                    try
                    {
                        _ctx.Update(ticket);
                        await _ctx.SaveChangesAsync();
                    }
                    catch (DbUpdateConcurrencyException dce)
                    {
                        if (!TicketExists(ticket.TicketId))
                        {
                            return NotFound();
                        }
                        else
                        {
                            dce.ToString();
                        }
                    }
                    return RedirectToAction("Index");
                }
            }

            return View(ticket);
        }

        // GET: Tickets/Delete/5
        public async Task Delete(int? id)
        {
            object ticket = null;

            try
            {
                if ((id != null) && (id > 0))
                {
                    ticket = await _ctx.Ticket.SingleOrDefaultAsync(m => m.TicketId == id);
                    if (ticket == null)
                    {
                        return NotFound();
                    }
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            return View(ticket);
        }

        // POST: Tickets/Delete/5
        [ValidateAntiForgeryToken, HttpPost, ActionName("Delete")]
        public async Task DeleteConfirmed(int id)
        {
            try
            {
                var ticket = await _ctx.Ticket.SingleOrDefaultAsync(m => m.TicketId == id);
                _ctx.Ticket.Remove(ticket);
                await _ctx.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            return RedirectToAction("Index");
        }

        private bool TicketExists(int id)
        {
            return _ctx.Ticket.Any(e => e.TicketId == id);
        }
    }
}

WebAPI Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using CoreMVC.Models;
using Microsoft.EntityFrameworkCore;

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

namespace CoreMVC.Controllers
{
    [Route("api/[controller]")]
    public class TicketController : Controller
    {
        private TicketBookingContext _ctx = null;
        public TicketController(TicketBookingContext context)
        {
            _ctx = context;
        }

        // GET: api/Ticket/GetTicket
        [HttpGet("GetTicket"), Produces("application/json")]
        public async Task GetTicket()
        {
            List Tickets = null;
            object result = null;
            try
            {
                using (_ctx)
                {
                    Tickets = await _ctx.Ticket.ToListAsync();
                    result = new
                    {
                        Tickets
                    };
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            return Tickets;
        }

        // GET api/Ticket/GetTicketByID/5
        [HttpGet("GetTicketByID/{id}"), Produces("application/json")]
        public async Task GetTicketByID(int id)
        {
            Ticket contact = null;
            try
            {
                using (_ctx)
                {
                    contact = await _ctx.Ticket.FirstOrDefaultAsync(x => x.TicketId == id);
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            return contact;
        }

        // POST api/Ticket/PostTicket
        [HttpPost, Route("PostTicket"), Produces("application/json")]
        public async Task PostTicket([FromBody]Ticket model)
        {
            object result = null; string message = "";
            if (model == null)
            {
                return BadRequest();
            }
            using (_ctx)
            {
                using (var _ctxTransaction = _ctx.Database.BeginTransaction())
                {
                    try
                    {
                        _ctx.Ticket.Add(model);
                        await _ctx.SaveChangesAsync();
                        _ctxTransaction.Commit();
                        message = "Saved Successfully";
                    }
                    catch (Exception e)
                    {
                        _ctxTransaction.Rollback();
                        e.ToString();
                        message = "Saved Error";
                    }

                    result = new
                    {
                        message
                    };
                }
            }
            return result;
        }

        // PUT api/Ticket/PutTicket/5
        [HttpPut, Route("PutTicket/{id}")]
        public async Task PutContact(int id, [FromBody]Ticket model)
        {
            object result = null; string message = "";
            if (model == null)
            {
                return BadRequest();
            }
            using (_ctx)
            {
                using (var _ctxTransaction = _ctx.Database.BeginTransaction())
                {
                    try
                    {
                        var entityUpdate = _ctx.Ticket.FirstOrDefault(x => x.TicketId == id);
                        if (entityUpdate != null)
                        {
                            entityUpdate.DestinationFrom = model.DestinationFrom;
                            entityUpdate.DestinationTo = model.DestinationTo;
                            entityUpdate.TicketFee = model.TicketFee;

                            await _ctx.SaveChangesAsync();
                        }
                        _ctxTransaction.Commit();
                        message = "Entry Updated";
                    }
                    catch (Exception e)
                    {
                        _ctxTransaction.Rollback(); e.ToString();
                        message = "Entry Update Failed!!";
                    }

                    result = new
                    {
                        message
                    };
                }
            }
            return result;
        }

        // DELETE api/Ticket/DeleteTicketByID/5
        [HttpDelete, Route("DeleteTicketByID/{id}")]
        public async Task DeleteContactByID(int id)
        {
            object result = null; string message = "";
            using (_ctx)
            {
                using (var _ctxTransaction = _ctx.Database.BeginTransaction())
                {
                    try
                    {
                        var idToRemove = _ctx.Ticket.SingleOrDefault(x => x.TicketId == id);
                        if (idToRemove != null)
                        {
                            _ctx.Ticket.Remove(idToRemove);
                            await _ctx.SaveChangesAsync();
                        }
                        _ctxTransaction.Commit();
                        message = "Deleted Successfully";
                    }
                    catch (Exception e)
                    {
                        _ctxTransaction.Rollback(); e.ToString();
                        message = "Error on Deleting!!";
                    }

                    result = new
                    {
                        message
                    };
                }
            }
            return result;
        }

    }
}

 Output:

core_27

Source Code: I’ve uploaded the full source code to download/clone , Hope this will help 🙂

References:

  1. https://en.wikipedia.org/wiki/.NET_Framework
  2. https://en.wikipedia.org/wiki/.NET_Framework_version_history
  3. http://www.codeproject.com/Articles/1115771/NET-CORE-MVC-ANGULARJS-STARTUP
  4. http://www.codeproject.com/Articles/1118189/CRUD-USING-NET-CORE-ANGULARJS-WEBAPI

 

Author:

Since March 2011, have 8+ years of professional experience on software development, currently working as Senior Software Engineer at s3 Innovate Pte Ltd.

One thought on “.NET Core Startup”

  • Jaya kumar says:

    Reply

    Hi
    ShashangkaShekhar

    Good Article Nice Explanation

    can you share with me

    How to start sample project step by step with snapshot then project Folder Structure

Leave a Reply