Advertisements

Startup Page In ASP.NET Core


Introduction

I think we all are familiar with the configuration of the default startup page in the previous versions of AP.NET but it’s slightly different in ASP.NET Core Applications. In this article, I will explain how to configure the default startup page In ASP.NET Core.

Default Startup Page Configuration

In this way, we can implement the default startup page In ASP.NET Core.

  • Default Configuration
  • Customized Configuration

Default Configuration

We can use UseDefaultFiles() extension method in ASP.NET Core. UseDefaultFiles() will only search for the files given in “wwwroot”. If any of the files are detected first in “wwwroot” the files are run as default in the client Browser.

  • default.html
  • default.htm
  • index.html
  • index.htm

UseDefaultFiles must be called before UseStaticFiles or Anyother method(app.Run,app.Use) to serve the default file in the client-side Browser. As you mention UseStaticFiles() method after UseDefaultFiles(), it will run UseStaticFiles() method as a default and automatically terminates the other files, which come after UseStaticFiles() method.

Customized Configuration

In this case, we are calling other customized pages as default startup pages in ASP.NET Core. Thus, we can use DefaultFilesOptions in ASP.NET Core. If you want to run other files as default, check the code give below in Startup.Cs.

Code

DefaultFilesOptions DefaultFile = new DefaultFilesOptions();
DefaultFile.DefaultFileNames.Clear();
DefaultFile.DefaultFileNames.Add("Welcome.html");
app.UseDefaultFiles(DefaultFile);
app.UseStaticFiles();

Reference

Summary

We learned how to configure the default startup page In ASP.NET Core. I hope, this article is useful for all ASP.NET Core beginners.

Advertisements

Session State In ASP.NET Core and MVC Core


Introduction

In this article, we will explain how to create a “Session State in ASP.NET Core and MVC Core”.

Session State

In Session State, we can use to save and store user data while the user browses your web app. We already know that in previous versions of ASP.NET, we could store session as key value pair like this “Session[“Name”] = “Rajeesh Menoth”” and implement it in an easy way. But in the latest version of ASP.NET or ASP.NET Core, we need to do a few configurations for accessing and enabling Session State in the application. The main purpose of session is maintaining user data in memory because of HTTP is a stateless protocol.

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

Package Required

We need to install the stable version of “Microsoft.AspNetCore.Session” from Nuget Package Manager. Then only we can access Session State in ASP.NET Core 1.1.

Session In Nuget

Microsoft.AspNetCore.Session

.csproj

In “.csproj” we can check all the installed packages and versions details in ASP.NET Core 1.1.

<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
    <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />

Assemblies Required

These are the assemblies mainly required for accessing functionality of Session State, MVC, JSON, etc

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

Home Controller

The following code is the example of sharing session in ASP.NET Core 1.1.

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace SessionInCore.Controllers
{
    public class HomeController : Controller
    {
        const string SessionKeyName = "_Name";
        const string SessionKeyAge = "_Age";
        const string SessionKeyDate = "_Date";

        public IActionResult Index()
        {
            HttpContext.Session.SetString(SessionKeyName, "Rajeesh Menoth");
            HttpContext.Session.SetInt32(SessionKeyAge, 28);
            // Requires you add the Set extension method mentioned in the SessionExtensions static class.
            HttpContext.Session.Set<DateTime>(SessionKeyDate, DateTime.Now);

            return View();
        }

        public IActionResult About()
        {
            ViewBag.Name = HttpContext.Session.GetString(SessionKeyName);
            ViewBag.Age = HttpContext.Session.GetInt32(SessionKeyAge);
            ViewBag.Date = HttpContext.Session.Get<DateTime>(SessionKeyDate);

            ViewData["Message"] = "Session State In Asp.Net Core 1.1";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "My Contact Details";

            return View();
        }

        public IActionResult Error()
        {
            return View();
        }
        
    }

    public static class SessionExtensions
    {
        public static void Set<T>(this ISession session, string key, T value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T Get<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default(T) :
                                  JsonConvert.DeserializeObject<T>(value);
        }
    }
}

The following code contains the Key name as “SessionKeyName” & Value name as “Rajeesh Menoth”. So we can set the Session String “Key” and “Value” in SetString(“Key”,”Value”).

const string SessionKeyName = "_Name";
HttpContext.Session.SetString(SessionKeyName, "Rajeesh Menoth");

The following code contains a similar Session code as an older version of ASP.NET.

Session["Name"] = "Rajeesh Menoth";

We can Assign and Get the Session string value using “GetString(Name)” Method in a simple way.

ViewBag.Name = HttpContext.Session.GetString(SessionKeyName);

In the following way we can set and get serializable objects to Session in our application.

//Accessing Extension Method.
HttpContext.Session.Set<DateTime>(SessionKeyDate, DateTime.Now);
//Example of Extension Method.
 public static class SessionExtensions
    {
        public static void Set<T>(this ISession session, string key, T value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T Get<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default(T) :
                                  JsonConvert.DeserializeObject<T>(value);
        }
    }

Configure Services

The first step is we need to add the Session services to the container. So we can add the services in “ConfigureServices” method in “Startup.cs” class in our application.

public void ConfigureServices(IServiceCollection services)
        {
            //In-Memory
            services.AddDistributedMemoryCache();
            services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromMinutes(1);
            });              
            // Add framework services.
            services.AddMvc();
        }

Configure the HTTP request pipeline

We add the “app.UseSession()” inside the Configure Method in “Startup.cs” Class because it gets called by the runtime. One more advantage is we can use this method to configure the HTTP request pipeline in our application.

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.UseSession();

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

OutPut – Active Session

Session Active

Session Active

OutPut – Session Expired

We set 1 mins as the Session Timeout in “ConfigureServices” method in Startup.cs class.

 services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromMinutes(1);//Session Timeout.
            });
Session Expire

Session Expire

Reference

See Also

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

Conclusion

We learned how to create Session State In ASP.NET Core and MVC Core. I hope you liked this article. Please share your valuable suggestions and feedback.

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.

Send Email Using ASP.NET Core 1.1 With MailKit In Visual Studio 2017


Introduction

We are familiar with Sending Email Using Asp.Net With C#. But today, we are going to teach you how to send email using ASP.NET Core 1.1 with MailKit. We can implement it in ASP.Net Core very easily as compared to the previous versions of ASP.NET.

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

MailKit

MailKit is a cross-platform mail client library built on top of MimeKit. That means we get all the mail sending libraries from MailKit, such as – Simple Mail Transfer Protocol (SMTP) etc.

Simple Mail Transfer Protocol (SMTP)

Simple Mail Transfer Protocol (SMTP) is a TCP/IP protocol used in sending and receiving e-mail. Most e-mail systems that send mail over the Internet use SMTP to send messages from one server to another.The messages can then be retrieved with an e-mail client using either POP or IMAP.

The following is a list of SMTP Server and Port Numbers.

Sl.No Mail Server SMTP Server( Host ) Port Number
1 Gmail smtp.gmail.com 587
2 Outlook smtp.live.com 587
3 Yahoo Mail smtp.mail.yahoo.com 465
4 Yahoo Mail Plus plus.smtp.mail.yahoo.com 465
5 Hotmail smtp.live.com 465
6 Office365.com smtp.office365.com 587
7 zoho Mail smtp.zoho.com 465

Assemblies Required

The following assemblies are required for sending email using ASP.NET Core with MailKit.

using MailKit.Net.Smtp;
using MimeKit;

Adding MailKit in Our Project

Go to “Tools -> NuGet Package Manager -> Manage Nuget Package for Solutions…” Then, search “MailKit”, Choose and Install the latest version “V1.12.0” in your application.

MailKit Installation

MailKit Installation

Project Structure

New .NET Core tooling is available in Visual Studio 2017 by default. In the Dependencies folder, every package tool has separate folder like MailKit saved into NuGet folder. If you have a client side tool like bower, then its dependencies are saved into it’s folder.

Project Structure ASP.NET Core 1.1

Project Structure ASP.NET Core 1.1

Code

The following code contains the mail sending code of ASP.NET Core.

using MailKit.Net.Smtp;
using MimeKit;
using System;

namespace EmailApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //From Address
                string FromAddress = "From Email Address";
                string FromAdressTitle = "Email from ASP.NET Core 1.1";
                //To Address
                string ToAddress = "To Email Address";
                string ToAdressTitle = "Microsoft ASP.NET Core";
                string Subject = "Hello World - Sending email using ASP.NET Core 1.1";
                string BodyContent = "ASP.NET Core was previously called ASP.NET 5. It was renamed in January 2016. It supports cross-platform frameworks ( Windows, Linux, Mac ) for building modern cloud-based internet-connected applications like IOT, web apps, and mobile back-end.";

                //Smtp Server
                string SmtpServer = "smtp.gmail.com";
                //Smtp Port Number
                int SmtpPortNumber = 587;

                var mimeMessage = new MimeMessage();
                mimeMessage.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
                mimeMessage.To.Add(new MailboxAddress(ToAdressTitle, ToAddress));
                mimeMessage.Subject = Subject;
                mimeMessage.Body = new TextPart("plain")
                {
                    Text = BodyContent

                };

                using (var client = new SmtpClient())
                {

                    client.Connect(SmtpServer, SmtpPortNumber, false);
                    // Note: only needed if the SMTP server requires authentication
                    // Error 5.5.1 Authentication 
                    client.Authenticate("From Address Email", "Password");
                    client.Send(mimeMessage);
                    Console.WriteLine("The mail has been sent successfully !!");
                    Console.ReadLine();
                    client.Disconnect(true);

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}

Important Points

  • When you are sending mail with your “gmail” account, enable less secure apps so that you will be able to login from all apps. Otherwise, it will throw authentication error like 5.5.1 authentication.
  • Remove 2-Step Verification.

In the following code, we can mention username for “gmail” account but in other service like “hotmail”, we must provide the full email address because other Microsoft accounts, like Outlook, live, etc. have the same SMTP Server Address “smtp.live.com”.

client.Authenticate("From Address Email", "Password");

csproj

In previous version, ASP.NET Core 1.0 contained all the versions & dependencies in project.json file but in new version, i.e., ASP.NET Core 1.1, they are saved in csproj.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="MailKit" Version="1.12.0" />
  </ItemGroup>

</Project>

Output

References

Conclusion

We learned how to send email using ASP.NET Core 1.1 with MailKit in Visual Studio 2017. I hope, you liked this article. Please share your valuable suggestions and feedback.

Visual Studio 2017 : New Features & Installation


Introduction

Feeling great & Looking Smart. I know every one is excited for the new release of “Visual Studio 2017”. Yes , Microsoft Visual Studio celebrated it’s 20th years of glory with all tech lovers in the world love it. Now, it has come up with lots of excitement. Thus, I am happy to share the important features of Visual Studio 2017 with all the tech lovers.

Visual Studio 2017 System Requirements

The following are the minimum requirements of Visual Studio 2017 installation.

Download Visual Studio 2017

Go to this link Visual Studio 2017 , choose & download your favorite edition.

Installing Visual Studio 2017

Visual Studio 2017 Installation Window shows 3 sections.

  1. Workloads
  2. Individual components
  3. Language packs

Workloads

We can choose the appropriate development section from Visual Studio Workloads. I selected “ASP.NET and Web development & .NET Core cross-platform development”. It also contains around 5.50 GB. Thus, If you select all Workloads, then it will reach 50 GB+.

Individual components

We can choose the required component from this section.

Language packs

We can use different languages in Visual Studio. Thus, we can choose the appropriate language in this section.

Installation Process

We are going to install Visual Studio Community 2017 edition in our machine. Ones the following process is complete, we can launch & access the new features in Visual Studio 2017.

Features in Visual Studio 2017

The following are the new features in Visual Studio 2017.

Live Unit Testing

This feature is only available in Visual Studio 2017 Enterprise edition. Without running the solution, we can easily test the Application because few hidden background process happens in our Application through “Live Unit Testing”. We can enable Live Unit Testing for which you need to go to the “Test” command of the top-level menu bar in VS, choose “Live Unit Testing”, then “Start”.

Image Credit : Channel 9 Visual Studio 2017 Lanuch

Image Credit : Channel 9 Visual Studio 2017 Lanuch

We noticed that 3 symbols appeared in our code due to running on background Live Testing.

  • Cross Sign – line of executable code. The test is covered and it indicates that a failure test.
  • Tick Mark – line of executable code. The test is covered and it indicates that a success test.
  • Minus – line of executable code. Not yet covered a single Test.

Dotted Line

The is a very cool feature in Visual Studio 2017 because this option helps to identify the exact open and close curly braces “{}” through dotted line in our code. This dotted line is really helpful for when you are working on a bulk amount of code in a single page.

Filttered IntelliSense Search

The new Filtering IntelliSense Search option is available in Visual Studio 2017. This option is one of the powerful way to consume the search time in our code. The following IntelliSense bottom tray contains icons as Properties, Interface, Modules, Namespaces, Enums, Classes, Constants etc. For example, if i want to search an Interface, then I can choose an Interface Icon from the bottom of the tray, else it will show all the possible contents in our solution.

Improvements Of Navigation Controls

  1. Go to All ( Cntrl + T )
  2. Go to Line ( Cntrl + G )
  3. Go to File ( Cntrl + 1 + F )
  4. Go to Type ( Cntrl + 1 + T )
  5. Go to Member ( Cntrl + 1 + M )
  6. Go to Symbol ( Cntrl + 1 + S )

Go to All ( Cntrl + T )

Press “Cntrl + T”, then it will display one tray above the search bar. Thus, we can search the content with the help of the options given below like Line/Files/Types/Members/Symbols. For example, I want to search type in our entire solution or an Application. Now, choose “Type” Icon in the tray and type in the search bar, so it will filter and show the exact results as much as faster than the earlier versions of VS. The shortcut is “Cntrl + 1 + T”.

Find All Reference ( Shift + F12 )

We can find all the references in our entire solution. The highlighted one is all the reference results by a combination of project, definition and path.

Code Suggestions

This is a very exciting feature in VS2017. It gives us the good code practice in our Application. The code given below notices that we have written an “If” condition without curl braces. Thus, it gives us the suggestion tp add the curl braces to understand the code.

Code Style Changing

We can change the code style option in our VS2017. Go to “Tools -> Options -> Text Editor -> Basic -> Code Style -> Naming”.

Reference

Conclusion

We learnt installation & new features of Visual Studio 2017. I hope, you liked this article. Please share your valuable suggestions and feedback.

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.

%d bloggers like this: