European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting - HostForLIFEASP.NET :: Getting Started With ASP.NET Core 7.0 MVC

clock February 10, 2023 07:32 by author Peter

In this article, I am going to explain Asp.Net Core 7.0 MVC, Asp.net Core MVC features. The Latest version of Asp.Net Core MVC is Asp .Net Core 7.0 MVC and how to create a simple ASP.NET Core 7.0 MVC application and run.


ASP .NET Core 7.0 MVC version was released on November 08, 2022. Visual Studio 2022 version 17.4.0 is required to develop ASP.Net Core 7.0 MVC web application. It focuses on being unified, modern, simple, and first. Asp.NET Core 7.0 MVC will be supported for only 18 months as standard-term support (STS).

Some New Features of Asp.Net Core 7.0 MVC
When using null state checking, Nullable page and view models are now supported to improve the experience.
Improvements to endpoint routing, link generation, and parameter binding.
Various improvements to the Razor compiler to improve performance.
The IParsable<TSelf>.TryParse using in MVC & API supports binding controller action parameter values.

What is Asp.Net Core MVC?
The ASP.NET Core MVC framework is a lightweight, open source, highly testable presentation framework for building web apps and APIs using the Model-View-Controller design pattern.

It is an architectural pattern that separates the representation and user interaction. It is divided into three sections Model, View, and Controller; this is called separation of concerns.

Model
It represents the real world object and provides data to the view. It is a set of classes that describes the business logic. Also defines business rules for data means how the data can be changed and manipulated.

View
The view is responsible for looking and feel. It represents the UI components like CSS, JQuery, and Html etc. It is only responsible for displaying the data that is received from the controller as the result.

Controller

The controller is responsible to take the end user request and load the appropriate “Model” and “View”.

Note

  • User interacts with the controller.
  • There is one-to-many relationship between controller and view means one controller can mapped to multiple views.
  • Controller and view can talk to each other.
  • Model and view can not talk to each other directly. They communicate to each other with the help of controller.

Prerequisites

    Install Visual Studio 2022 updated version 17.4.0
    Install .NET SDK 7.0

Connect To Visual Studio 2022 Community Edition and Create Your First Project

Step 1
First, install Visual Studio 2022 in your system.

Step 2
Go to all programs in your systems, we can see Visual Studio 2022 and Visual Studio Installer.

Step 3
Double-click on Visual Studio 2022 and it will open. It looks like the below screenshot. Opening it the first time it will take few time.

 

Creating Your First Project
Click on; create a new Project to create a new project.


You can see various project types there. Choose “Asp.Net Core Web App (Model-View-Controller)” project type for now.
Select Asp.Net Core Web App (Model-View-Controller), and then click Next.

Give a valid name to your project and select a path for it. Then click Next button.


Now, Select framework .NET 7.0 (Standard Term Support). You can select the Authentication Type as None. You can select Configure for HTTPS based on your need.If you need Docker in your project then Select Enable Docker.

Uncheck Do not use top-level statements.

Then click the create button.

Asp.Net Core 7.0 MVC Web application created and project structure is shown below,

Program.cs file looks like the below.

The Project.cspoj file looks like the below. Where you can see the target Framework net7.0, by default Nullanle and ImplicitUsings are enabled.


I have made some minor changes in the Index.cshtml view pages.

 

Now, build and Press Ctrl+F5 to run without the debugger.
If, Visual Studio displays the following dialog:

Select Yes if you trust the IIS Express SSL certificate.
If Again, The below dialog is displayed:

Select Yes if you agree to trust the development certificate.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Action Filter In MVC

clock February 2, 2023 08:27 by author Peter

Action filter in MVC provides the option to handle the scenarios when we would like to perform an operation before and after the execution of a controller action. For this purpose, we create a custom class, which inherits the FilterAttribute class and implements the IActionFilter interface. After creating the filter, we simply apply the class name as an attribute on the controller.
 

Here, the FilterAttribute class makes it possible to use the class as an attribute and IActionFilter interface contains two methods named OnActionExecuting and OnActionExecuted. The OnActionExecuting is executed before the controller method is executed and OnActionExecuted is called after the execution of the controller method. This kind of technique is quite helpful for the logging purposes. Thus, let's see how we can use this filter.
 
Let's start by adding a new class named MyActionFilter.cs. Now, derive this class from the FilterAttribute and the IActionFilter. Implement the  OnActionExecuting and OnActionExecuted methods and add your custom logic into the methods.Thus, the code will look as shown below.  
    public class MyActionFilter : FilterAttribute, IActionFilter 
    { 
        public void OnActionExecuted(ActionExecutedContext filterContext) 
        { 
            //Fires after the method is executed 
        } 
     
        public void OnActionExecuting(ActionExecutingContext filterContext) 
        { 
            //Fires before the action is executed 
        } 
    } 


Simply, apply the class as an attribute on the controller. Add debuggers on both the methods as well as the controller method.
    public class HomeController : Controller 
    { 
        [MyActionFilter] 
        public ActionResult Index() 
        { 
            return View(); 
        } 
     
        public ActionResult About() 
        { 
            ViewBag.Message = "Your application description page."; 
            return View(); 
        } 
     
        public ActionResult Contact() 
        { 
            ViewBag.Message = "Your contact page."; 
            return View(); 
        } 
    } 


Run the Application and debug step by step to see the order of execution of the methods. First, the OnActionExecuting will be executed, then the controller method and finally the OnActionExecuted method.

 



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Generate QR Code In ASP.NET Core MVC

clock January 24, 2023 10:16 by author Peter

In this article, we are going to create an ASP.Net Core MVC application that generates QR Code for different purposes like Email, Website, Bookmark Websites, SMS, WhatsApp, etc. For this, we are going to use NuGet package called QRCoder.

About QRCoder NuGet Package
QRCoder is a simple library, written in C#.NET, which enables you to create QR codes. It hasn't any dependencies on other libraries and is available as .NET Framework and .NET Core PCL version on NuGet.

QRCoder provides many types of QR Codes but in this article, I will use only the following types.

    URL
    Bookmark Website
    Send SMS
    Send WhatsApp Message
    Compose Email
    Connect To WIFI

Create ASP.Net Core MVC project.

Step 1
Open Visual Studio and click on Create New Project.

Step 2
Select ASP.NET CORE Web App (Model-View-Controller) Template as shown in the below image and click on next button.

Step 3
Configure your project by specifying the name of the project and the location where you want to save your project.

Step 4
Select the version of the .Net Core framework you want to use and click on create button.
Add New Controller

Step 1
Right Click on Controller Folder then click on Add then Controller.

Step 2
Select MVC Empty Controller. And give a name whatever you want here I gave QRCode.


Add NuGet Package
Step 1
Right click on your project and then click on Manage NuGet Packages.

Step 2
Search for QRCoder in browse tab.

Step 3
Click on the install button and it will install in your project.

Create a new Model Class
For transferring data from controller to view and view to controller we have to use model class.

Step 1

For creating a model right click on the Model folder and click on Add then class.

Step 2
Give a suitable name for your class, Here I gave QRCodeModel.

Step 3
Create required properties in your class. As you can see in the below code I have created different properties for different types of QR Codes.
public class QRCodeModel {
    public int QRCodeType {
        get;
        set;
    }
    public string QRImageURL {
        get;
        set;
    }
    //for bookmark qr code
    public string BookmarkTitle {
        get;
        set;
    }
    public string BookmarkURL {
        get;
        set;
    }
    // for email qr codes
    public string ReceiverEmailAddress {
        get;
        set;
    }
    public string EmailSubject {
        get;
        set;
    }
    public string EmailMessage {
        get;
        set;
    }
    //for sms qr codes
    public string SMSPhoneNumber {
        get;
        set;
    }
    public string SMSBody {
        get;
        set;
    }
    //for website
    public string WebsiteURL {
        get;
        set;
    }
    // for whatsapp qr message code
    public string WhatsAppNumber {
        get;
        set;
    }
    public string WhatsAppMessage {
        get;
        set;
    }
    // for wifi qr code
    public string WIFIName {
        get;
        set;
    }
    public string WIFIPassword {
        get;
        set;
    }
}


Design View

Step 1
Create an action method in your controller as you want. Here I used the index action method.

Step 2

Right-click on the action method and click on Add View to add a new view.

Step 3
Return the model from the controller which you have created. If you want to pass some extra data you can pass it. Here as you see in the below code I just created object of model and pass that model to view.
public IActionResult Index() {
    QRCodeModel model = new QRCodeModel();
    return View(model);
}


Step 4
Design your view as per your requirements.
@model QRCodeModel
@{
    ViewData["Title"] = "Generate QR Code";
}

<form asp-action="Index">

    <div class="row mt-2">
        <div class="col-lg-6 col-md-6 col-sm-12">
            <label>Select QR Code Type</label>
            <select asp-for="QRCodeType" id="QRCodeType" class="form-control" onchange="onQRCodeTypeChange()">
                <option value="1">Website</option>
                <option value="2">Bookmark URL</option>
                <option value="3">SMS</option>
                <option value="4">WhatsApp</option>
                <option value="5">Email</option>
                <option value="6">WIFI</option>
            </select>
        </div>
    </div>

    <!--  Website  -->
    <div class="row mt-2 hideDiv" id="DIV1">
        <div class="col-lg-6 col-md-6 col-sm-12">
            <label>Enter your website URL</label>
            <input autocomplete="off" type="url" asp-for="WebsiteURL" class="form-control" />
        </div>
    </div>

    <!-- Book Mark URL   -->
    <div class="row mt-2 hideDiv" id="DIV2">
        <div class="col-lg-6 col-md-6 col-sm-12">
            <label>Enter your URL</label>
            <input type="url" asp-for="BookmarkURL" class="form-control" autocomplete="off" />
        </div>
    </div>

    <!--  SMS  -->
    <div id="DIV3" class="hideDiv">
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter Phone Number with country code(eg. +91)</label>
                <input type="text" asp-for="SMSPhoneNumber" class="form-control" autocomplete="off" />
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter your Message</label>
                <textarea asp-for="SMSBody" class="form-control"></textarea>
            </div>
        </div>
    </div>

    <!--  Whats App Message  -->
    <div id="DIV4" class="hideDiv">
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter WhatsApp Number with country code(eg. +91)</label>
                <input type="text" asp-for="WhatsAppNumber" class="form-control" autocomplete="off" />
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter your Message</label>
                <textarea asp-for="WhatsAppMessage" class="form-control"></textarea>
            </div>
        </div>
    </div>

    <!--  Compose Email  -->
    <div id="DIV5" class="hideDiv">
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter Receive's Email Address</label>
                <input type="text" asp-for="ReceiverEmailAddress" class="form-control" autocomplete="off" />
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter Email Subject</label>
                <input type="text" asp-for="EmailSubject" class="form-control" autocomplete="off" />
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter Email Message</label>
                <textarea asp-for="EmailMessage" class="form-control"></textarea>
            </div>
        </div>
    </div>

    <!--   WIFI   -->
    <div id="DIV6" class="hideDiv">
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter WIFI Name</label>
                <input type="text" asp-for="WIFIName" class="form-control" autocomplete="off" />
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter WIFI Password</label>
                <input type="text" asp-for="WIFIPassword" class="form-control" autocomplete="off" />
            </div>
        </div>
    </div>

    <div class="row mt-2">
        <div class="col-lg-6 col-md-6 col-sm-12">
            <button type="submit" class="btn btn-primary">Generate</button>
            <button type="reset" class="btn btn-secondary">Reset</button>
        </div>
    </div>

    @if (!string.IsNullOrEmpty(Model.QRImageURL))
    {
        <div class="row mt-2" id="qrCodeImage">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <img height="250" width="250" src="@Model.QRImageURL" />
            </div>
        </div>
    }

</form>

@section Scripts{

    <script>
        $(document).ready(function () {
            $("#QRCodeType").trigger("change");
        });

        function onQRCodeTypeChange() {
            let qrcodeType = $("#QRCodeType").val();
            $(".hideDiv").hide();
            $("#DIV" + qrcodeType).show();
        }
    </script>
}


Code Explanation
As you can see in the above HTML code I created inputs as per my properties.

Here I add drop-down for QR Code type and based on that type I show and hide DIV of codes.
<div class="row mt-2">
  <div class="col-lg-6 col-md-6 col-sm-12">
    <label>Select QR Code Type</label>
    <select asp-for="QRCodeType" id="QRCodeType" class="form-control" onchange="onQRCodeTypeChange()">
      <option value="1">Website</option>
      <option value="2">Bookmark URL</option>
      <option value="3">SMS</option>
      <option value="4">WhatsApp</option>
      <option value="5">Email</option>
      <option value="6">WIFI</option>
    </select>
  </div>
</div>

For different types of QR Codes, I have created different div and gave an id to that div same as I gave the value in dropdown. Also gave same class name to all div.

At bottom, there are two buttons for submitting and resetting page.

Below button, there is an image that shows QR Code Image when the view return from controller after generating QR Code. Here we directly pass QR Code Image as base64 string instead of saving image and then show it on view side.
@if (!string.IsNullOrEmpty(Model.QRImageURL))
{
    <div class="row mt-2" id="qrCodeImage">
        <div class="col-lg-6 col-md-6 col-sm-12">
            <img height="250" width="250" src="@Model.QRImageURL" />
        </div>
    </div>
}


At last, there is JavaScript code in the Scripts section which contain a function called onQRCodeTypeChange which gets value of QR Code Type drop-down then hide all the divs and only show which has id same as drop down value.
function onQRCodeTypeChange() {
    let qrcodeType = $("#QRCodeType").val();
    $(".hideDiv").hide();
    $("#DIV" + qrcodeType).show();
}


On the document ready event I triggered the change event of QR Code type drop-down.
$(document).ready(function() {
    $("#QRCodeType").trigger("change");
});

Code for Generate QR Code
Create post action method in your controller to post data from form. In this method, we are going to generate QR Code as per its type.
[HttpPost]
public IActionResult Index(QRCodeModel model) {
    Payload payload = null;
    switch (model.QRCodeType) {
        case 1: // website url
            payload = new Url(model.WebsiteURL);
            break;
        case 2: // bookmark url
            payload = new Bookmark(model.BookmarkURL, model.BookmarkURL);
            break;
        case 3: // compose sms
            payload = new SMS(model.SMSPhoneNumber, model.SMSBody);
            break;
        case 4: // compose whatsapp message
            payload = new WhatsAppMessage(model.WhatsAppNumber, model.WhatsAppMessage);
            break;
        case 5: //compose email
            payload = new Mail(model.ReceiverEmailAddress, model.EmailSubject, model.EmailMessage);
            break;
        case 6: // wifi qr code
            payload = new WiFi(model.WIFIName, model.WIFIPassword, WiFi.Authentication.WPA);
            break;
    }
    QRCodeGenerator qrGenerator = new QRCodeGenerator();
    QRCodeData qrCodeData = qrGenerator.CreateQrCode(payload);
    QRCode qrCode = new QRCode(qrCodeData);
    var qrCodeAsBitmap = qrCode.GetGraphic(20);
    // use this when you want to show your logo in middle of QR Code and change color of qr code
    //Bitmap logoImage = new Bitmap(@"wwwroot/img/Virat-Kohli.jpg");
    //var qrCodeAsBitmap = qrCode.GetGraphic(20, Color.Black, Color.Red, logoImage);
    string base64String = Convert.ToBase64String(BitmapToByteArray(qrCodeAsBitmap));
    model.QRImageURL = "data:image/png;base64," + base64String;
    return View("Index", model);
}
private byte[] BitmapToByteArray(Bitmap bitmap) {
    using(MemoryStream ms = new MemoryStream()) {
        bitmap.Save(ms, ImageFormat.Png);
        return ms.ToArray();
    }
}

Step 1
Create a new object of QRCodeGenerator class.
QRCodeGenerator qrGenerator = new QRCodeGenerator();

Step 2

Call the CreateQrCode method using this object and pass payload in its constructor. Payload is an object of PayloadGenerator.Payload type. There are different payload types as per QR Code types. We will discuss different types of payload later in this article.
QRCodeData qrCodeData = qrGenerator.CreateQrCode(payload);

Step 3
Create object of QRCode type and Pass QR Data object to its constructor.
QRCode qrCode = new QRCode(qrCodeData);

Step 4
Call GetGraphic method of this QR Code object which take one integer parameter which define pixels per module.
var qrCodeAsBitmap = qrCode.GetGraphic(20);

There are also some overloaded methods using which you can change the color of QR Code and also set logo in QR Code.
// use this when you want to show your logo in middle of QR Code and change color of qr code
Bitmap logoImage = new Bitmap(@"wwwroot/img/Peter.jpg");
var qrCodeAsBitmap = qrCode.GetGraphic(20, Color.Black, Color.Red, logoImage);

Step 5
GetGraphic method return bitmap image as return type. You can save this image in your local path but here I convert this bitmap image to byte array and then convert this byte array to base64 string which I’m going to bind in QRImageURL property and pass it to the view so user can view this QR Code.
string base64String = Convert.ToBase64String(BitmapToByteArray(qrCodeAsBitmap));
model.QRImageURL = "data:image/png;base64," + base64String;

For converting bitmap to byte first convert it to memory stream and then get byte array from this stream in user define method BitmapToByteArray. As you can see in below code.
private byte[] BitmapToByteArray(Bitmap bitmap) {
    using(MemoryStream ms = new MemoryStream()) {
        bitmap.Save(ms, ImageFormat.Png);
        return ms.ToArray();
    }
}


Step 6
Return view data after generating QR Code so user can see Generated QR Code in their browser.
Followings are different payload type which is used in this article.
Payload payload = null;

URL Payload
To generate QR Code that opens URL or any Website QRCoder provider payload type of URL class.

This class takes one argument in its constructor which is URL of website.
payload = new Url(model.WebsiteURL);

Bookmark Payload
To generate QR Code for bookmark type we have to Use Bookmark payload.
Bookmark class’s constructor takes two parameters first is the URL of the website and second is the title of the bookmark.
payload = new Bookmark(model.BookmarkURL, model.BookmarkURL);

SMS Payload

To generate QR Code for composing SMS we have to pass payload of SMS type. QR Code provider SMS class for this type of payload.

SMS class’s constructor takes two parameters first is phone number to whom you want to send the SMS and the second is the message you want to send. Message parameter s optional you can only pass phone number to it.
payload = new SMS(model.SMSPhoneNumber, model.SMSBody);

WhatsApp Message Payload
To generate QR Code that send WhatsApp message we have to pass WhatsAppMessage payload. QRCoder provides WhatsAppMessage class to generate payload.
WhatsAppMessage provides two overloaded methods one only takes one parameter which is message only and second takes two parameter WhatsApp number and message both.
payload = new WhatsAppMessage(model.WhatsAppNumber, model.WhatsAppMessage);

Mail Payload
To generate QR Code which compose email we have to use MAIL payload.

Mail class’s constructor does not required any parameter. It’s all parameters are by default set to null. But here we are going to pass receiver email address, Subject, and body of mail.
payload = new Mail(model.ReceiverEmailAddress, model.EmailSubject, model.EmailMessage);

WiFi Payload
To generate QR Code which connect to WIFI we have to pass data in WIFI payload.
WiFi class’s constructor takes three required parameter wifi name, wifi password, and authentication mode (WEP, WPA, nopass). You can pass any theme but mostly WPA is used in all wifi so here I by default set it.
payload = new WiFi(model.WIFIName, model.WIFIPassword, WiFi.Authentication.WPA);



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Folder Structure Of ASP.NET Core MVC 6.0 Project

clock January 20, 2023 06:25 by author Peter

In this article, I am going to explain to you, the default folder structure of an ASP.NET Core MVC 6.0 web application and describe the purpose of each folder. In my previous article, we created an empty ASP.NET Core MVC 6.0 Project and the structure of the project as shown in the following image.

Let’s start exploring each folder and file that exists in the Project Structure for easy understanding.

Project Folder Structure Description
The details of the default project structure can be seen in the solution explorer, it displays all the projects related to a single solution.


.csproj File

Double click on the project name in Solution Explorer to open .csproj file in the editor. Right-click on the project and then click on Edit Project File in order to edit the .csproj file. As shown in the following image.

Once clicked on Edit Project File, .csproj file will be opened in Visual Studio as shown below.

As you can see the project’s SDK is Microsoft.NET.Sdk.Web. The target framework is net6.0 indicating that we are using .NET 6. Notice the Nullable and ImplicitUsings elements.
The <Nullable> elements decide the project wide behaviour of Nullable of Nullable reference types. The value of enable indicates that the Nullable reference types are enabled for the project.

The < ImplicitUsings > element can be used to enable or disable. When < ImplicitUsings > is set to enable, certain namespaces are implicitly imported for you.

Connected Services
It contains the details about all the service references added to the project. A new service can be added here, for example, if you want to add access to Cloud Storage of Azure Storage you can add the service here. As shown in the following image.

Dependencies
The Dependencies node contains all the references of the NuGet packages used in the project. Here the Frameworks node contains reference two most important dotnet core runtime and asp.net core runtime libraries. Project contains all the installed server-side NuGet packages, as shown below.


Properties
Properties folder contains a launchSettings.json file, which containing all the information required to lunch the application. Configuration details about what action to perform when the application is executed and contains details like IIS settings, application URLs, authentication, SSL port details, etc.

 

WWWroot
This is the webroot folder and all the static files required by the project are stored and served from here. The webroot folder contains a sub-folder to categorize the static file types, like all the Cascading Stylesheet files, are stored in the CSS folder, all the javascript files are stored in the js folder and the external libraries like bootstrap, jquery are kept in the library folder.

Generally, there should be separate folders for the different types of static files such as JavaScript, CSS, Images, library scripts, etc. in the wwwroot folder as shown below.

Controllers
Controller handles all the incoming requests. All the controllers needed for the project are stored here. Controllers are responsible for handling end user interaction, manipulating the model and choose a view to display the UI. Each controller class inherits a Controller class or ControllerBase class. Each controller class has “Controller” as a suffix on the class name, for example, the default “HomeController.cs” file can be found here. As shown below.

Models
A Model represents the data of the application and a ViewModel represents data that will be displayed in the UI. The models folder contains all the domain or entity classes. Please note user can add folders of his choice to create logical grouping in the project.

Views
A view represents the user interface that displays ViewModel or Model data and can provide an option to let the user modify them. Mostly a folder in name of the controller is created and all the views related to it are stored in it. Here HomeController related view Index.cshtml and Privacy.cshtml is stored in Home folder and all the shared view across the application is kept in Shared folder. Under this shared folder there are _Layout.cshtml, _ValidationScriptsPartial.cshtml and Error.cshtml view files. There are two more view files, _ViewImports.cshtml and _ViewStart.cshtml under the view folder.

appsettings.json
This file contains the application settings, for example, configuration details like logging details, database connection details.


Program.CS
This class is the entry point of the web application. It builts the host and executes the run method.

I hope the article helped you to understand ASP.NET Core MVC 6.0 Project Structure.

Conclusion
In this article we explained, the folder structure of ASP.NET Core MVC 6.0 application. I hope this article is useful to understand.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: ASP.NET MVC 5 With Entity Framework And MySQL

clock January 17, 2023 07:46 by author Peter

We know how to use Code First Migration in SQL Server. But in most cases, a customer will think we can use it for the open source database. So that’s the reason we pick the “MySQL” database, and we can follow the same steps we follow in the “SQL” database. In this article, we are going to explain Code First Migration in ASP.NET MVC 5 with Entity FrameWork & MySQL.

Create a Web Application using MVC 5
Click on File -> New -> Project -> Visual C# -> Web -> ASP.Net Web Application ( .Net Framework ).


Click on “OK” then click on “MVC”.
 
Install Entity Framework & MySQL Entity
Go to Visual Studio “Tools -> NuGet Package Manager -> Manage Nuget Packages for Solution” or right click on your web application then click on “Manage NuGet Packages”.
 
EntityFramework
Search EntityFramework in the “Browse” Section.

Once we installed EntityFramework & MySql Entity in our application then it will generate a SQL and MySQL Provider inside the EntityFramework Section in Web.Config.
    <entityFramework> 
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> 
        <providers> 
          <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> 
          <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.8.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider></providers>   
      </entityFramework> 

Model Class
We just created a sample model class for demo purposes.
    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
      
    namespace WebAppWithMySql.Models 
    { 
        public class Student 
        { 
            public int Id { get; set; } 
      
            public string Name { get; set; } 
      
            public string Password { get; set; } 
        } 
    } 


Creation of DBContext

Create a db context class in our application. The following dbcontext will point out our connection string in WebConfig.
    using MySql.Data.Entity; 
    using System.Data.Entity; 
    using WebAppWithMySql.Models; 
      
    namespace WebAppWithMySql 
    { 
        [DbConfigurationType(typeof(MySqlEFConfiguration))] 
        public class WebAppContext : DbContext 
        { 
            public DbSet<Student> Products 
            { 
                get; 
                set; 
            } 
            public WebAppContext() 
                //Reference the name of your connection string ( WebAppCon ) 
                : base("WebAppCon") { } 
        } 
    } 


Connection String
We added the same connection string name that we added in the dbcontext class. The following connection string represents “MySql” Db.
    <connectionStrings> 
        <add name="WebAppCon" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;userid=root;password=peter123;database=WebAppMySql;persistsecurityinfo=True" /> 
      </connectionStrings> 


Migration Steps

Go to Visual Studio "Tools -> NuGet Package Manager -> Package Manager Console". Then execute the following command.
    Enable-Migrations – ( We need to enable the migration, only then can we do the EF Code First Migration ).
    Add-Migration IntialDb (migration name) – ( Add a migration name and run the command ).
    Update-Database -Verbose — if it is successful then we can see this message (Running Seed method).

Once Migration is done; then, we can see that the respective files are auto-generated under the “Migrations” folder.

Output


 



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Pass Data Across Views In .NET MVC

clock January 10, 2023 06:17 by author Peter

In previous articles, we discussed both View Variables in ASP.NET MVC and View Variables in ASP.NET Core MVC, respectively.  Although each has some distinctive points, both share a lot of common features. In this article, we will discuss something new: pass data across views. We will also summarize some common or important shared features for various vew variables.


A: Brief Summary of ViewData
We will start our discussion from ViewData, but most or all features are the same for other MVC View Variables. The ASP.NET Core also has the same features. So, we will discuss ViewData in the most, and have the last part to see the extension to other View variables.

A - 1: MVC Data Passing Techniques
This is a different approach to summarize the MVC Data Passing Techniques from Data Passing Techniques in ASP.NET Core (dotnettricks.com). We will not repeat the conclusion here, but we can go to the page to learn the different approaches or understanding.

B: Type of ViewData
We have discussed ViewData, ViewBag, TempData, Session type features. They are all the Type of Dictionary:

Where the difference between ViewBag and ViewData:


Besides ViewBag, all other View Variables need to be cast before using. We define a ViewData named "book": as type BookModel with data such as Id = 1:


When we retrieve data, we have to cast the data back to the data type. Otherwise, we will get an error message:


After casting:

C: Pass Data into _Layout.cshtml Page by ViewData
The _layout.cshtml is a shared page by other specific views. It belongs to no Controller or Action, or we can say it belongs to every Controller or Action when the related view is using _layout.cshtml. Therefore, we can pass data into Layout either from the Controller or Action view, which uses the _layout.cshtml, such as, if we have a Contact Us Action:

Or, we can define the ViewData from the Contact Us View:

Both ways will pass the data into Layout page:

Notes
1, We usually introduce the Layout into View by the code in the View as below:

2, in some cases, if we want to make the Layout page(s) dynamic, we can assign the layout to the view through Controller/Action:

3, A related important shared concept for MVC, _Viewstat.cshtml

D: Pass Data into _Layout.cshtml Page by Other View Variables
The same is true for other MVC View Variables, such as ViewBag, TempData, and absolutely Session variable:


Pass TempData to Layout:

Pass ViewData to Layout:

Pass ViewBag to Layout:

This article discussed using ASP.NET MVC ViewData to pass data into Layout View through either Controller or View.  The features are available or the same as other View Variables in ASP.NET MVC, and the same is true for ASP.NET Core MVC.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Two-Factor Authentication Using Google Authenticator in Asp.Net MVC

clock December 19, 2022 07:35 by author Peter

In this article, I'll explain how to create an ASP.NET MVC web application with two-factor authentication using Google Authenticator to decrease the possibility of account takeovers and boost user and account security.


As it authenticates users using two possible authentication factors, two-factor authentication is a wonderful technique to help secure user accounts.

In this article, we are not taking user id and password from database but using static data. Here we only learn about Two-Factor Authentication using Google Authenticator.
Two-Factor Authentication using Google Authenticator in Asp.Net MVC

Step 1
Create a new project in Visual Studio, select an ASP.NET Web Application (.Net Framework), and press the Next button.

Step 2
Give the project a name, select the save location folder, and click on the Create button.


Step 3
Select MVC Option for project type and click on the Create button. Now your project is created.

Step 4
Add the Google.Authenticator package from NuGet.
Go to Tools Menu - NuGet Package Manager - Manage NuGetPackages For Solution - Search for Google.Authenticator > Install > Close.

Step 5
Add the Model class LoginModel.cs under Model Folder for login details that stores the username and password.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace GoogleAuthenticatorDemo.Models
{
    public class LoginModel
    {
        public string UserName { get; set; }

        public string Password { get; set; }
    }
}


Step 6
Add the Google Authentication Private Key In Web.Config File under <appSettings>.
This key is not fixed; you can create it yourself with any character combination.
Any character combination use as private key in google authenticator.
<appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

    <add key="GoogleAuthKey" value="U1d2A3y4" />
</appSettings>


Step 7
Create a Login action method in your controller; in my case, it's HomeController.
public ActionResult Login()
{
    Session["UserName"] = null;
    Session["IsValidTwoFactorAuthentication"] = null;
    return View();
}


Step 8

Right click on the Login action method and select Add View Option, and then select the following: Then click the Add Button button to add a view for this action method.

Now a new file is created under View > Home > Login.cshtml.

Step 9
Add the following code into Login.cshtml:
@model GoogleAuthenticatorDemo.Models.LoginModel
@{
    ViewBag.Title = "Login";
}

<center>
    <h2>Login Page</h2>
    @if (ViewBag.Status == null || !ViewBag.Status)
    {
        <div>@ViewBag.Message</div>
        <div>
            @using (Html.BeginForm())
            {
                <div class="form-group">
                    <label for="UserName">UserName : </label>
                    @Html.TextBoxFor(a => a.UserName, new { @class = "form-control" })
                </div>
                <div class="form-group">
                    <label for="Password">Password : </label>
                    @Html.TextBoxFor(a => a.Password, new { @class = "form-control", type = "password" })
                </div>
                <input type="submit" value="Login" class="btn btn-default" />
            }
        </div>
    }
    else
    {

        <div>@ViewBag.Message</div>
        <div>
            <img src="@ViewBag.BarcodeImageUrl" width="300" height="300" />

        </div>
        <div>
            Manual Setup Code : @ViewBag.SetupCode
        </div>
        <div>
            @using (Html.BeginForm("TwoFactorAuthenticate", "Home", FormMethod.Post))
            {
                <input type="text" name="CodeDigit" />
                <input type="submit" class="btn btn-success" />
            }
        </div>
    }
</center>


Step 10
Create a Post type Login Action method in your controller and add the following code:
[HttpPost]
public ActionResult Login(LoginModel login)
{
  bool status = false;

  if (Session["Username"] == null || Session["IsValidTwoFactorAuthentication"] == null || !(bool) Session["IsValidTwoFactorAuthentication"])
  {
      string googleAuthKey = WebConfigurationManager.AppSettings["GoogleAuthKey"];
      string UserUniqueKey = (login.UserName + googleAuthKey);

      //Take UserName And Password As Static - Admin As User And 12345 As Password
      if (login.UserName == "Admin" && login.Password == "12345")
      {
         Session["UserName"] = login.UserName;

         //Two Factor Authentication Setup
         TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();
         var setupInfo = TwoFacAuth.GenerateSetupCode("UdayDodiyaAuthDemo.com", login.UserName, ConvertSecretToBytes(UserUniqueKey, false), 300);
         Session["UserUniqueKey"] = UserUniqueKey;
         ViewBag.BarcodeImageUrl = setupInfo.QrCodeSetupImageUrl;
         ViewBag.SetupCode = setupInfo.ManualEntryKey;
         status = true;
      }
  }
  else
  {
    return RedirectToAction("Index");
  }
  ViewBag.Status = status;
  return View();
}

Step 11
Create the ConvertSecretToBytes function in the controller.
private static byte[] ConvertSecretToBytes(string secret, bool secretIsBase32) =>
           secretIsBase32 ? Base32Encoding.ToBytes(secret) : Encoding.UTF8.GetBytes(secret);


Step 12
Create a TwoFactorAuthenticate Action action method for your controller.
public ActionResult TwoFactorAuthenticate()
{
     var token = Request["CodeDigit"];
     TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();
     string UserUniqueKey = Session["UserUniqueKey"].ToString();
     bool isValid = TwoFacAuth.ValidateTwoFactorPIN(UserUniqueKey, token, false);
     if (isValid)
     {
         HttpCookie TwoFCookie = new HttpCookie("TwoFCookie");
         string UserCode =Convert.ToBase64String(MachineKey.Protect(Encoding.UTF8.GetBytes(UserUniqueKey)));

         Session["IsValidTwoFactorAuthentication"] = true;
         return RedirectToAction("Index");
      }

      ViewBag.Message = "Google Two Factor PIN is expired or wrong";
      return RedirectToAction("Login");
}


Step 13
Create a Logoff Action Method in your controller to handle the logout action.
public ActionResult Logoff()
{
     Session["UserName"] = null;
     Session["IsValidTwoFactorAuthentication"] = null;
     return RedirectToAction("Login");
}


Step 14
To handle an unauthorised login, add the following condition to all of your action methods, which in my case are three method.
public ActionResult Index()
{
    if (Session["Username"] == null || Session["IsValidTwoFactorAuthentication"] == null || !(bool)Session["IsValidTwoFactorAuthentication"])
    {
        return RedirectToAction("Login");
    }
    return View();
}

public ActionResult About()
{
     if (Session["Username"] == null || Session["IsValidTwoFactorAuthentication"] == null || !(bool)Session["IsValidTwoFactorAuthentication"])
     {
         return RedirectToAction("Login");
     }

     ViewBag.Message = "Your application description page.";
     return View();
}

public ActionResult Contact()
{
     if (Session["Username"] == null || Session["IsValidTwoFactorAuthentication"] == null || !(bool)Session["IsValidTwoFactorAuthentication"])
     {
         return RedirectToAction("Login");
     }

     ViewBag.Message = "Your contact page.";
     return View();
}

Final HomeController.cs File
using Google.Authenticator;
using GoogleAuthenticatorDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Security;

namespace GoogleAuthenticatorDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            if (Session["Username"] == null || Session["IsValidTwoFactorAuthentication"] == null || !(bool)Session["IsValidTwoFactorAuthentication"])
            {
                return RedirectToAction("Login");
            }
            return View();
        }

        public ActionResult About()
        {
            if (Session["Username"] == null || Session["IsValidTwoFactorAuthentication"] == null || !(bool)Session["IsValidTwoFactorAuthentication"])
            {
                return RedirectToAction("Login");
            }

            ViewBag.Message = "Your application description page.";
            return View();
        }

        public ActionResult Contact()
        {
            if (Session["Username"] == null || Session["IsValidTwoFactorAuthentication"] == null || !(bool)Session["IsValidTwoFactorAuthentication"])
            {
                return RedirectToAction("Login");
            }

            ViewBag.Message = "Your contact page.";
            return View();
        }

        public ActionResult Login()
        {
            Session["UserName"] = null;
            Session["IsValidTwoFactorAuthentication"] = null;
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginModel login)
        {
            bool status = false;

            if (Session["Username"] == null || Session["IsValidTwoFactorAuthentication"] == null || !(bool)Session["IsValidTwoFactorAuthentication"])
            {
                string googleAuthKey = WebConfigurationManager.AppSettings["GoogleAuthKey"];
                string UserUniqueKey = (login.UserName + googleAuthKey);


                //Take UserName And Password As Static - Admin As User And 12345 As Password
                if (login.UserName == "Admin" && login.Password == "12345")
                {
                    Session["UserName"] = login.UserName;

                    //Two Factor Authentication Setup
                    TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();
                    var setupInfo = TwoFacAuth.GenerateSetupCode("UdayDodiyaAuthDemo.com", login.UserName, ConvertSecretToBytes(UserUniqueKey, false), 300);
                    Session["UserUniqueKey"] = UserUniqueKey;
                    ViewBag.BarcodeImageUrl = setupInfo.QrCodeSetupImageUrl;
                    ViewBag.SetupCode = setupInfo.ManualEntryKey;
                    status = true;
                }
            }
            else
            {
                return RedirectToAction("Index");
            }
            ViewBag.Status = status;
            return View();
        }


        private static byte[] ConvertSecretToBytes(string secret, bool secretIsBase32) =>
           secretIsBase32 ? Base32Encoding.ToBytes(secret) : Encoding.UTF8.GetBytes(secret);


        public ActionResult TwoFactorAuthenticate()
        {
            var token = Request["CodeDigit"];
            TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();
            string UserUniqueKey = Session["UserUniqueKey"].ToString();
            bool isValid = TwoFacAuth.ValidateTwoFactorPIN(UserUniqueKey, token, false);
            if (isValid)
            {
                HttpCookie TwoFCookie = new HttpCookie("TwoFCookie");
                string UserCode = Convert.ToBase64String(MachineKey.Protect(Encoding.UTF8.GetBytes(UserUniqueKey)));

                Session["IsValidTwoFactorAuthentication"] = true;
                return RedirectToAction("Index");
            }
            ViewBag.Message = "Google Two Factor PIN is expired or wrong";
            return RedirectToAction("Login");
        }

        public ActionResult Logoff()
        {
            Session["UserName"] = null;
            Session["IsValidTwoFactorAuthentication"] = null;
            return RedirectToAction("Login");
        }
    }
}

Step 15
All pages display the user's name and the option to log out. So add that code to the _Layout.cshtml page, and your _Layout.cshtml should now look like this:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" title="more options">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>

                @if (@HttpContext.Current.Session["UserName"] != null && @HttpContext.Current.Session["IsValidTwoFactorAuthentication"] != null)
                {
                   if(bool.Parse(@HttpContext.Current.Session["IsValidTwoFactorAuthentication"].ToString()) == true)
                   {
                        <ul class="nav navbar-nav navbar-right">
                            <li style="color: White; font-size: 15px; margin-top: 10px; margin-right: 100px;">
                                USER: @HttpContext.Current.Session["UserName"].ToString()
                            </li>
                            <li>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                @Html.ActionLink("Log Out", "Logoff", "Home", new { style = "color:White; font-size: 15px" })
                            </li>
                        </ul>
                   }
                }
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

Step 16
Display the username on the index page. So, add the following code to your index.cshtml page, and your index.cshtml should now look like this:
@{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h1>ASP.NET</h1>
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
    <p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>
<center><h2 style="color: red;">Welcome Mr. @HttpContext.Current.Session["UserName"].ToString()</h2></center>
<div class="row">
    <div class="col-md-4">
        <h2>Getting started</h2>

        <p>
            ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
            enables a clean separation of concerns and gives you full control over markup
            for enjoyable, agile development.
        </p>
        <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Get more libraries</h2>
        <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
        <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Web Hosting</h2>
        <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
        <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p>
    </div>
</div>


You can design your page yourself and according to your needs, but I've used default content, only adding a username to understand the concept.

Step 17
Now run your project.

When you run the project, by default, the index method will invoke but not authorize, so it will redirect to the login page.

Enter "Admin" as the user name and "12345" as the password, then click the login button.


\Step 18

After clicking the login button, a QR code and the setup key for two-factor authentication were generated, which will be used later on the mobile app for code generation.

Step 19
Install the Google Authenticator app from the Play Store or here on your mobile device, and open it; you have two options: scan a QR code or enter a setup key.
We scan the QR code here, so you only have one Authenticator Code, which will change after a while. Enter this code on your website.

Step 20
If your code is correct, you will be redirected to your index page after clicking the submit button in the above screen.

As you can see, the implementation of Google Authenticator in ASP.Net MVC is very simple.
In this article, we learned about Two-Factor Authentication using Google Authenticator in Asp.Net MVC.
Thank you for reading my article. Please leave your comments in the comment box below.
Enjoy Coding!



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Partial View in MVC

clock December 13, 2022 07:32 by author Peter

Partial view in ASP.NET MVC is special view which renders a portion of view content. It is just like a user control of a web form application. Partial can be reusable in multiple views. It helps us to reduce code duplication. In other word a partial view enables us to render a view within the parent view.

The partial view is instantiated with its own copy of a ViewDataDictionary object which is available with the parent view so that partial view can access the data of the parent view. If we made the change in this data (ViewDataDictionary object), the parent view's data is not affected. Generally the Partial rendering method of the view is used when related data that we want to render in a partial view is part of our model.
 
Creating Partial View

To create a partial view, right-click on view -> shared folder and select Add -> View option. In this way we can add a partial view.


It is not mandatory to create a partial view in a shared folder but a partial view is mostly used as a reusable component, it is a good practice to put it in the "shared" folder.

HTML helper has two methods for rendering the partial view: Partial and RenderPartial.
    <div> 
        @Html.Partial("PartialViewExample") 
    </div> 
    <div> 
        @{ 
            Html.RenderPartial("PartialViewExample"); 
        } 
    </div>


@Html.RenderPartial
The result of the RenderPartial method is written directly into the HTTP response, it means that this method used the same TextWriter object as used by the current view. This method returns nothing.
 
@Html.Partial
This method renders the view as an HTML-encoded string. We can store the method result in a string variable.
The Html.RenderPartial method writes output directly to the HTTP response stream so it is slightly faster than the Html.Partial method.
Returning a Partial view from the Controller's Action method:
    public ActionResult PartialViewExample() 
    { 
        return PartialView(); 
    }


Render Partial View Using jQuery
Sometimes we need to load a partial view within a model popup at runtime, in this case we can render the partial view using JQuery element's load method.
    <script type="text/jscript"> 
            $('#partialView').load('/shared/PartialViewExample’); 
    </script> 

View Vs Partial View

View Partial View
View contains the layout page Partial view does not contain the layout page
_viewstart page is rendered before any view is rendered Partial view does not check for a _viewstart.cshtml. We cannot place any common code for a partial view within the _viewStart.cshtml page.
View may have markup tags like html, body, head, title, meta etc. The Partial view is specially designed to render within the view and as a result it does not contain any mark up.
Partial view is more lightweight than the view. We can also pass a regular view to the RenderPartial method.
If there is no layout page specified in the view, it can be considered as a partial view. In razor, there is no distinction between views and partial views as in the ASPX view engine (aspx and ascx).

 

 



ASP.NET MVC Hosting - HostForLIFEASP.NET :: CRUD Operation With Dapper Using ASP.NET Core 6 MVC

clock December 6, 2022 08:03 by author Peter

In this article will learn CURD (Create, Update, Read and Delete) operation which is common for most web applications. Here will understand SQL Database, Dapper Micro-ORM (Object Relation Mapper) along with repository pattern using ASP.NET Core 6 MVC.


What is Dapper?
Dapper is a micro ORM or it is a simple object mapper framework that helps to map the native query output to a domain class.
Creating a New Project in Visual Studio 2022

Start Visual Studio software and select Create a new project.

In the Create a new project dialog, select ASP.NET Core Web App (Model-View Controller) > Next.

In the Create a new project dialog, select ASP.NET Core Web App (Model-View Controller) > Next.

In the Configure your new project dialog, enter CURDWithDapperCore6MVC_Demo for Project name. It's important to name the project CURDWithDapperCore6MVC_Demo. The capitalization needs to match each namespace when code is copied. Select Next.

In the Additional information dialog, select .NET 6.0 (Long-term support). Select Create

The Visual Studio project 2022 will now generate the structure for the selected application. In this example, we are using ASP.Net MVC so we can create a controller to write the code, or so we can use the existing controller. There you can enter the code and build/run the application.
Install the Dapper, Microsoft.Data.SqlClient Library through NuGet Package Manager

The Visual Studio software provides the NuGet Package manager option to install the package directly to the solution.

In Visual Studio Select Tools > NuGet Package Manager > Manage NuGet Packages for the solution. The below screenshot shows how to open the NuGet Package Manager.

Search for the specific package Dapper, Microsoft.Data.SqlClient using the search box on the upper left. Select a package from the list to display its information, enable the Install button and a version-selection drop-down, as shown in the below screenshot. The NuGet package will be installed for your project and reference will be added, as seen in the screenshot below.

In the above image, we can see the list of the related search items. We need to select the required option to install the package to the solution.

Add Connection String
In solution explorer select a file appsettings.json double click on this file to open "Add" connection string as shown below.
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=Companies-DB;Integrated Security=True;Pooling=False;Encrypt=false"
  }
}


Add Models class
Right-click the Models folder > Add > Class. Name the file Company.cs
using System.ComponentModel.DataAnnotations;

namespace CURDWithDapperCore6MVC_Demo.Models
{
    public class Company
    {
        public int Id { get; set; }
        [Display(Name ="Company Name")]
        public string CompanyName { get; set; }

        [Display(Name = "Company Address")]
        public string CompanyAddress { get; set; }

        public string Country { get; set; }

        [Display(Name = "Glassdoor Rating")]
        public int GlassdoorRating { get; set; }
    }
}


Add DBContext Folder and DapperContext Class
Right click on Project in Solution Explorer>Add New>New Folder. Rename this folder to DBContext. Now right click on DBContext folder > Add> New Item> C# class name this class DapperContext.

using Microsoft.Data.SqlClient;
using System.Data;

namespace CURDWithDapperCore6MVC_Demo.DBContext
{
    public class DapperContext
    {
        private readonly IConfiguration _configuration;
        private readonly string _connectionString;
        public DapperContext(IConfiguration configuration)
        {
            _configuration = configuration;
            _connectionString = _configuration.GetConnectionString("DefaultConnection");
        }
        public IDbConnection CreateConnection() => new SqlConnection(_connectionString);
    }
}


Add Repositories Folder and ICompanyRepository Interface

Right click on Project in Solution Explorer>Add New>New Folder. Rename this folder to Repositories. Now right click on DBContext folder > Add> New Item>C# Interface and name this interface ICompanyRepository.
using CURDWithDapperCore6MVC_Demo.Models;

namespace CURDWithDapperCore6MVC_Demo.Repositories
{
    public interface ICompanyRepository
    {
        Task<IEnumerable<Company>> GetCompanies();
        Task<Company> GetCompany(int? id);
        Task CreateCompany(Company company);
        Task UpdateCompany(int id, Company company);
        Task DeleteCompany(int id);
    }
}


Add Company Repository class to Implement Interface

Right click on Repositories Add> New Item>C# class and name this class to CompanyRepository.
using CURDWithDapperCore6MVC_Demo.DBContext;
using CURDWithDapperCore6MVC_Demo.Models;
using Dapper;
using System.Data;

namespace CURDWithDapperCore6MVC_Demo.Repositories
{
    public class CompanyRepository : ICompanyRepository
    {
        private readonly DapperContext context;

        public CompanyRepository(DapperContext context)
        {
            this.context = context;
        }

        public async Task<IEnumerable<Company>> GetCompanies()
        {
            var query = "SELECT * FROM Companies";

            using (var connection = context.CreateConnection())
            {
                var companies = await connection.QueryAsync<Company>(query);
                return companies.ToList();
            }
        }

        public async Task<Company> GetCompany(int? id)
        {
            var query = "SELECT * FROM Companies WHERE Id = @Id";

            using (var connection = context.CreateConnection())
            {
                var company = await connection.QuerySingleOrDefaultAsync<Company>(query, new { id });
                return company;
            }
        }

        public async Task CreateCompany(Company company)
        {
            var query = "INSERT INTO Companies (CompanyName, CompanyAddress, Country,GlassdoorRating) VALUES (@CompanyName, @CompanyAddress, @Country, @GlassdoorRating)";

            var parameters = new DynamicParameters();
            parameters.Add("Name", company.CompanyName, DbType.String);
            parameters.Add("Address", company.CompanyAddress, DbType.String);
            parameters.Add("Country", company.Country, DbType.String);
            parameters.Add("Country", company.GlassdoorRating, DbType.Int32);

            using (var connection = context.CreateConnection())
            {
                await connection.ExecuteAsync(query, parameters);
            }
        }

        public async Task UpdateCompany(int id, Company company)
        {
            var query = "INSERT INTO Companies (CompanyName, CompanyAddress, Country,GlassdoorRating) VALUES (@CompanyName, @CompanyAddress, @Country, @GlassdoorRating WHERE Id = @Id)";
            var parameters = new DynamicParameters();
            parameters.Add("Name", company.CompanyName, DbType.String);
            parameters.Add("Address", company.CompanyAddress, DbType.String);
            parameters.Add("Country", company.Country, DbType.String);
            parameters.Add("Country", company.GlassdoorRating, DbType.Int32);
            using (var connection = context.CreateConnection())
            {
                await connection.ExecuteAsync(query, parameters);
            }
        }
        public async Task DeleteCompany(int id)
        {

            var query = "DELETE FROM Companies WHERE Id = @Id";
            using (var connection = context.CreateConnection())
            {
                await connection.ExecuteAsync(query, new { id });
            }
        }
    }
}

Add a controller
In Solution Explorer, right-click Controllers > Add > Controller.
In the Add New Scaffolded Item dialog box, select MVC Controller – MVC Controller with read/write actions > Add.
In the Add New Item - Companies dialog, enter CompaniesController.cs and select Add.
Replace the contents of Controllers/ CompaniesController.cs with the following code:

Add a view

Right-click on the Action in CompaniesController, and then Add View.
In the Add New Scaffolded Item dialog:
    Select Razor View Select Add
    View Name: Index
    Template: List
    Model Class: Company
    Select Add

Replace the contents of the Views/Companies/Index.cshtml Razor view file with the following:
@model IEnumerable<CURDWithDapperCore6MVC_Demo.Models.Company>

@{
    ViewData["Title"] = "Index";
}

<h2 class="text-capilization text-center">List of Companies</h2>

<p>
    <a asp-action="Create" class="btn btn-primary"> <i class="fa-solid fa-circle-plus"></i> Add New</a>
</p>
<table class="table table-bordered">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Id)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.CompanyName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.CompanyAddress)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Country)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.GlassdoorRating)
            </th>
            <th>Action(s)</th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CompanyName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CompanyAddress)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Country)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.GlassdoorRating)
            </td>
            <td>
                 <a href="@Url.Action("Details",new { id=item.Id})" class="btn btn-sm btn-primary"><i class="fa-solid fa-eye"></i></a>
                 <a href="@Url.Action("Edit",new { id=item.Id})" class="btn btn-sm btn-info"><i class="fa-solid fa-pen-to-square"></i></a>
                 <a href="@Url.Action("Delete",new { id=item.Id})" class="btn btn-sm btn-danger"><i class="fa-solid fa-trash"></i></a>
            </td>
        </tr>
}
    </tbody>
</table>

Note: Similarly Add all action view like Details, Create, Edit and Delete
Now its time to build and run your application Ctrl+F5

 

The above article has taught us. How we can use dapper with repository pattern. Dapper is Micro ORM whereas Entity Framework is ORM. Dapper is faster than entity framework. Hope you enjoyed the article. Happy Coding.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Working With Areas In MVC

clock November 30, 2022 07:27 by author Peter

The primary purpose of areas in MVC is to separate and manage Model, View, Controller, Themes and routing registration file into separate sections. In other words, areas serve as a technique for dividing and managing a large Application into well managed smaller modules with the separate M-V-C in each module.


Why to use areas in MVC Application?
If you are building a CRM Application for a small Educational Consultancy with multiple business units such as Registration on Arrival, Information Gathering by Receptionist, Updates by Consular, Documentation Management, Interview Preparation, Billing, and Report Generation by different departments etc. Each of these units have their own logical components views, controllers and models. In this scenario, you can use ASP.NET MVC areas to physically partition the business components in the same project.

It is also possible that we can have large projects that uses MVC, then we need to split the Application into smaller units called areas that isolates the larger MVC Application into smaller functional groupings. A MVC Application can contain several MVC structures (areas).

Areas are the small functional units with its own set of Model, View and Controller

    MVC Application can have any number of areas.
    Each area has its own controllers, models and views.
    Areas are put under separate folders called areas.

Today, we will be creating a new ASP.NET MVC Application and define a new area inside the project.

Creating new MVC Application


Step 1
Open Visual Studio.

Step 2
Create an ASP.NET Web Application with MVC template, as shown below.

Step 3
In Solution Explorer, right-click on the project and click Add. Select areas to add an area.

Step 4
Enter the name for the area, such as "Consular" or “SuperAdmin”.

Adding Controller for Area
Now, let’s add a controller in Area.

Step 1
Right-click on the Controller in your article area to add a controller.

Step 2
Select "MVC 5 Empty Controller.


Step 3
Provide controller name as "ManageInterviewController”. Now, your Area folder should look, as shown below.

Adding Views for Area
We have successfully added a controller for our area. Now, let’s add a view for the area.

Step 1
Right-click on the "Index" method of ManageInterviewConsular Controller and click on Add View.

Step 2
Enter the view name and select Layout page.

Step 3
Generate some content in the View of Index method, as shown below.


Index g (table table-hover table-bordered table-responsive" >Time< /tr>Kathmandu< /tr> " "picture_x0020_6"="">
 
Area Registration
Step 1
Open the "Global.asax" file.

Step 2
Add the code given below in your Application_Start() method.

AreaRegistration.RegisterAllAreas();


Till here, we have successfully added an area. Inside Area is the one, where we have added aController and a View for Index method.
Now, let’s add a link in Navbar of an Application to navigate to the view, which we created just now.

Step 1
Open the project view Layout file.

Step 2
Modify the <ul> </ul> in the layout file, as shown in the code given below.

Step 3
Debug the Application and open List Interview link, as shown below.

Let’s notice the URL
As highlighted, to invoke the controller of the area, we need to use

Baseurl/Areaname/Controller/{actionname}




About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in