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 :: Dependency Injection In ASP.NET MVC 5

clock June 11, 2024 09:26 by author Peter

I was inspired to produce an article about utilizing Dependency Injection in ASP.NET MVC5 after reading many ones about it in MVC and C#.


In MVC, Dependency Injection (DI)

One way to put "Inversion of Control" into practice is through dependency injection. According to the theory known as Inversion of Control (IoC), objects obtain the objects they require from an external source (such as an XML configuration file) rather than creating other objects that they depend on to do their tasks.

Let's now put the same into practice.
Create a new project for ASP.NET MVC.

No, install the "Unity.Mvc5" Container using NuGet Package Manager, as shown below.

When it is installed successfully, you will find the following two references added to your project and a UnityConfig.cs class file in App-Start folder.

Now, let’s create the repository that will be accessed by the Controller.

  • Add a folder named Repository.
  • Add an interface IUserMasterRepository.

interface IUserMasterRepository
    {
        IEnumerable<UserMaster> GetAll();
        UserMaster Get(int id);
        UserMaster Add(UserMaster item);
        bool Update(UserMaster item);
        bool Delete(int id);
    }

Now, add the repository which has your data access code.
public class UserMasterRepository : IUserMasterRepository
{
    private List<UserMaster> users = new List<UserMaster>();
    private int Id = 1;

    public UserMasterRepository()
    {
        // Add products for the Demonstration
        Add(new UserMaster { Name = "User1", EmailID = "[email protected]", MobileNo = "1234567890" });
        Add(new UserMaster { Name = "User2", EmailID = "[email protected]", MobileNo = "1234567890" });
        Add(new UserMaster { Name = "User3", EmailID = "[email protected]", MobileNo = "1234567890" });
    }

    public UserMaster Add(UserMaster item)
    {
        if (item == null)
        {
            throw new ArgumentNullException("item");
        }

        item.ID = Id++;
        users.Add(item);
        return item;
    }

    public bool Delete(int id)
    {
        users.RemoveAll(p => p.ID == id);
        return true;
    }

    public UserMaster Get(int id)
    {
        return users.FirstOrDefault(x => x.ID == id);
    }

    public IEnumerable<UserMaster> GetAll()
    {
        return users;
    }

    public bool Update(UserMaster item)
    {
        if (item == null)
        {
            throw new ArgumentNullException("item");
        }

        int index = users.FindIndex(p => p.ID == item.ID);
        if (index == -1)
        {
            return false;
        }
        users.RemoveAt(index);
        users.Add(item);
        return true;
    }
}

Note. Here, we have used a repository. You can use services which will consume your Repository.
Now, register this repository to container in UnityConfig.cs.
    public static void RegisterComponents()
    {
        var container = new UnityContainer();
        container.RegisterType<IUserMasterRepository, UserMasterRepository>();
        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }
Add UnityConfiguration in AppStart method of Global.asax
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    UnityConfig.RegisterComponents();
}

Inject the Dependency in Controller.

Create UserController

Now, in the below code, we have created a constructor of UserContoller, injected the UserMasterRepository, and accessed it in Index action.

public class UserController : Controller
{
    readonly IUserMasterRepository userRepository;

    public UserController(IUserMasterRepository repository)
    {
        this.userRepository = repository;
    }

    // GET: User
    public ActionResult Index()
    {
        var data = userRepository.GetAll();
        return View(data);
    }
}


Add a View for the same.
Add User folder in Views folder.
Add Index View.

Below is the code which needs to be written in Index View file.

@model IEnumerable<MVCWithDI.Repository.UserMaster>

@{
    ViewBag.Title = "Users";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.EmailID)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.MobileNo)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.EmailID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.MobileNo)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

</table>


Now, run the project. Here is the output.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Consuming Web Service In ASP.NET MVC

clock May 27, 2024 07:50 by author Peter

In order to transfer information, web services are still crucial in many modern applications. Because of my well-received series of articles on ASP.NET Web Services from two or three years ago, people have been requesting that I publish a straightforward piece on how to use Web Services in MVC applications. I have therefore chosen to produce an essay on ASP.NET MVC about using Web Services based on that requirement. We will learn how to use Web Services in ASP.NET MVC applications in this tutorial.

Step 1. Create MVC Application

  • "Start", followed by "All Programs" and select "Microsoft Visual Studio 2015".
  • Click "File", followed by "New" and click "Project". Select "ASP.NET Web Application Template", provide the Project; whatever name you wish, and click OK.
  • After clicking, the Window given below will appear. Choose an empty project template and check the MVC option.

The preceding step creates the simple empty ASP.NET MVC Application without a Model, View, and Controller. The Solution Explorer of the created Web Application will look as shown below.

Step 2. Adding Web Service reference
There are many ways to consume Web Services but in this article, we will learn to consume the Web Service by using the Add Service reference method. Note. We are using Web Services, which are hosted in IIS. For more details, please watch my video by using the link given in the prerequisites section. The URL is given below, hosted by Service, which we are going to use in this application .

http://localhost:8080/PaymentWebService.asmx

Right-click on the created ASP.NET MVC Application and click Add Service Reference, as shown below.

Now, after clicking on the preceding Service reference option, it will show the Window given below.

Now, click on the advanced button. It shows the Window given below, which allows us to configure how the entities and output should behave.

After configuring the appropriate Service reference settings, click Add Web Service reference. It will show the Window given below.

As shown in the preceding image, our Web Service found two web service methods which are highlighted with a red rectangle. Now provide the web service reference name as you wish and click on ok , it will add the Web Service reference in our created ASP.NET MVC application, as shown below.

As you can see in the preceding highlighted square section, the Web Service reference gets added to our created ASP.NET MVC application. Now, we are done with adding the Web Service reference.

Step 3. Add Controller Class
Now, let us add the ASP.NET MVC controller, as shown in the screenshot given below.

After clicking the Add button, it will show in the Window. Specify the Controller name as Home with the suffix Controller. Now, let's modify the default code of the Home controller. After modifying the code of Homecontroller class, the code will look, as shown below.

Home controller. cs
using System.Linq;
using System.Web.Mvc;

namespace ConsumingWebServiceInASPNETMVC.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public JsonResult BookingStatus()
        {
            //Creating Web Service reference object
            HotepBookingPayReference.PaymentWebService objPayRef = new HotepBookingPayReference.PaymentWebService();

            //calling and storing web service output into the variable
            var BookingStatusInfo = objPayRef.RoomBookingStatus().ToList();
            //returning json result
            return Json(BookingStatusInfo, JsonRequestBehavior.AllowGet);
        }
    }
}


I hope, you have gone through the same steps and understood how to use and call ASP.NET Web Service.

Step 4. Create Empty View
Now, right-click on the Views folder of the created Application and create View, which is named by Index, to display hotel booking details from hosted ASP.NET Web Services, as shown below.

Now, click the Add button. It will create a View named index. Now, modify the code and write the jQuery function to bind the HTML table, using JSON data after modifying the default code. The code snippet of the Index View looks, as shown below.

Index. cshtml
@{
    ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery-1.10.2.intellisense.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $.getJSON("/Home/BookingStatus", function (data) {
            var tr;
            $.each(data, function (d, i) {
                tr = $('<tr/>');
                tr.append("<td>" + i.RoomId + "</td>");
                tr.append("<td>" + i.RooType + "</td>");
                tr.append("<td>" + i.BookingStatus + "</td>");
                $('#tblBookingStatus').append(tr);
            });
        });
    });
</script>

<p class="form-horizontal">
    <hr />
    <p class="form-group">
        <table id="tblBookingStatus" class="table table-responsive" style="width:400px">
            <tr>
                <th>
                    Room Id
                </th>
                <th>
                    Room Type
                </th>
                <th>
                    Booking Status
                </th>
            </tr>
            <tbody>
            </tbody>
        </table>
    </p>
</p>


The preceding View will display all hotel booking details. Now, we have done all the coding.

Step 5. Run the Application
After running the Application, the hotel booking details from hosted ASP.NET Web Service will look, as shown below.

I hope, from the above examples, you have learned how to consume ASP.NET Web Services in ASP.NET MVC Applications.

Note

Download the zip file of the published code to learn and start quickly.
This article is just a guideline on how to consume ASP.NET Web Service in ASP.NET MVC Applications.
In this article, the optimization is not covered in depth; do it as per your skills.

Summary

I hope this article is useful for all the readers. If you have any suggestions, please mention them in the comments section.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: New Features in ASP.NET MVC 6

clock May 8, 2024 09:02 by author Peter

An overview of MVC, or Model View Controller
A framework called Model View Controller (MVC) is used to create web applications based on predetermined designs.

  • M is an acronym for model.
  • V is an acronym for view.
  • Controller is represented by the letter C.

The portion of the program that manages the logic for application data is represented by ModelModel. The Model object's primary functions are data retrieval and database storage.

Views
The portion of a program that manages data display is called a view. Model data are used to construct views.

Controller
The portion of the program that manages user interaction is called the Controller. It serves as a link between the View and the Model. Usually, the Controller provides input data to the model after reading data from the View and controlling user input.

What has ASP.NET MVC 6 added?
Cloud-optimized Framework vs. Entire Framework

Because System.Web.Dll is so expensive and often uses 30k of memory for each request and answer, Microsoft eliminated its reliance from MVC 6. As a result, MVC 6 now only uses 2k of memory for requests and responses, which is a relatively minimal amount of memory. One benefit of utilizing the cloud-optimized framework is that your website will come with a copy of the mono CLR. We don't need to update the.NET version on the whole system only for one website. A separate CLR version operating side by side with another website.

ASP.NET 5's MVC 6 component was created with cloud-optimized apps in mind. When our MVC application is pushed to the cloud, the runtime chooses the appropriate version of the library automatically.

It is also intended to optimize the Core CLR with a high degree of resource efficiency.

Microsoft created numerous Web API, WebPage, MVC, and SignalLr components that we refer to as MVC 6.

The Roslyn Compiler is used to solve the majority of the difficulties. The Roslyn Compiler is used with ASP.NET vNext. We can avoid compiling the program by using the Roslyn Compiler, which builds the application code automatically. Without pausing or restarting the project, you will update a code file and be able to view the changes by refreshing the browser.

Use hosts other than Windows
On the other hand, MVC 6 has an improved functionality that is housed on an IIS server and a self-user pipeline. Where we use MVC5, we can host it on an IIS server and we can also run it on top of an ASP. Net Pipeline.

Configuration system based on the environment
An environment for cloud application deployment is made available via the configuration system. Our program functions similarly to one that provides configurations. Retrieving the value from other configuration sources, such as XML files, is helpful.

A brand-new environment-based configuration system is part of MVC6. It is dependent only on the Web, as opposed to something else. Configuration file from the prior iteration.

Dependency injection
Using the IServiceProvider interface we can easily add our own dependency injection container. We can replace the default implementation with our own container.

Supports OWIN

We have complete control over the composable pipeline in MVC 6 applications. MVC 6 supports the OWIN abstraction.
Important components of an MVC6 application

The is a new file type in MVC6 as in the following.

The preceding files are new in MVC 6. Let's see what each of these files contains.

Config.Json

This file contains the application configuration in various places. We can define our application configuration, not just this file. There is no need to be concerned about how to connect to various sources to get the confutation value.

In the following code, we add a connection string in the Config.json file.
{
    "Data": {
        "DefaultConnection": {
            "ConnectionString": "Server=server_name;Database=database_name;Trusted_Connection=True;MultipleActiveResultSets=true"
        }
    }
}


Project.json

This file contains the build information as well as project dependencies. It can contain the commands used by the application.
{
    "webroot": "wwwroot",
    "version": "1.0.0-*",
    "dependencies": {
        "Microsoft.AspNet.Mvc": "6.0.0-beta1",
        "Microsoft.AspNet.Server.IIS": "1.0.0-alpha4"
    },
    "commands": {
        /* Change the port number when you are self hosting this application */
        "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000"
    },
    "frameworks": {
        "aspnet50": {},
        "aspnetcore50": {}
    }
}

Startup.cs

The Application Builder is used as a parameter when the configure method is used when the Startup class is used by the host.

Global.json
Define the location for the project reference so that the projects can reference each other.

Defining the Request Pipeline

If we look at the Startup.cs it contains a startup method.
public Startup(IHostingEnvironment env)
{
    // Setup configuration sources.
    var Configuration = new Configuration();
    Configuration.AddJsonFile("config.json");
    Configuration.AddEnvironmentVariables();
}


Create a Controller

If we look at the controller it is similar to the controller in a MVC 5 application.
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

The namespace for MVC6 is Microsoft.ASPNET.MVC, unlike the System.Web.MVC in the previous version. That is a big difference. In MVC 6 the application does not need to be derived from the controller class. In our controller, there are many default functionalities. Most of the time we might need to derive from the controller class, but if we do not need access to all of the functionally provided by the controller class, we can define our controller class.
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public string atul()
    {
        return "hello i am mvc6";
    }
}


If you execute the preceding method we may see the following page.

Summary
In this article, we have learned about the new features of MVC 6. We have now become familiar with MVC 6.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Different ActionResult Types in ASP.NET MVC & Their Uses

clock April 2, 2024 07:32 by author Peter

In ASP.NET MVC, the ActionResult class plays a crucial part in the result that is sent to the client when an action method is invoked. It's important to know the different ActionResult types and when to use them when developing MVC applications that are both secure and effective. This article will examine the various types of ActionResult and provide usage examples.

View Outcome

  • Use this technique when producing an entire HTML view in response to a user request.
  • typically used to display entire views or pages containing significant information.
  • ideal for displaying intricate information representations or user interface components.

public ActionResult Index()
{
    return View();
}


PartialViewResult

  • Purpose- Including particular page portions by rendering partial views.
  • Use Case- Perfect for containing reusable user interface elements such as sidebars, footers, headers, or widgets.Helps in maintaining modular and reusable code by separating UI components into smaller parts.


public ActionResult Sidebar()
{
    return PartialView("_Sidebar");
}


RedirectResult

  • Use when the client needs to be redirected to an alternative URL.
  • frequently used following successful login/logout processes, form submissions, or the permanent move of a resource.
  • helpful for handling URL changes or for putting HTTP redirects into place for SEO reasons.


public ActionResult RedirectCsharpcorner()
{
    return Redirect("https://www.c-sharpcorner.com/");
}

RedirectToRouteResult

  • Use in cases where route values require redirecting to an alternative action method inside the same application.
  • especially when utilizing named routes, useful for navigating around the application.
  • makes redirecting based on routing configuration possible in a more organized manner.


public ActionResult RedirectToAction()
{
    return RedirectToAction("Index", "Home");
}


JsonResult

  • Use in situations where you must give the client data in JSON format.
  • Perfect for creating online APIs that use JSON for data interchange or for AJAX requests.
  • makes it possible for client-side JavaScript frameworks to efficiently consume data without requiring refreshing entire pages.


public ActionResult GetJsonData()
{
    var data = new { Name = "Peter", Age = 25 };
    return Json(data, JsonRequestBehavior.AllowGet);
}


ContentResult

  • Use this method when you have to send the client plain text or HTML as raw material.
  • Ideal for producing dynamic content such as error warnings, delivering short replies, or presenting static material.
  • allows you to create and deliver content directly from the controller action with more flexibility.


public ActionResult ContentText()
{
    return Content("This is plain text content.");
}


FileResult

  • Use this if you need to download a document or an image and then return it to the client.
  • permits users to download data from the program, including Excel spreadsheets, photos, and PDFs.
  • allows for the customization of the file name and content type while offering a smooth method of file serving.


public ActionResult DownloadFile()
{
    byte[] fileBytes = System.IO.File.ReadAllBytes("path_to_file.pdf");
    return File(fileBytes, "application/pdf", "filename.pdf");
}


HttpStatusCodeResult

  • Use this when you need to provide the client with just a certain HTTP status number and no more content.
  • useful for indicating different HTTP status codes, such as redirection, success, and client or server issues.
  • permits appropriate HTTP status code processing to improve server-client communication.


public ActionResult Index()
{
    // Return HTTP 404 (Not Found) status code
    return new HttpStatusCodeResult(HttpStatusCode.NotFound);
}


EmptyResult

  • Use in situations where an action method doesn't need to give the client any data; this is usually the case for actions that have side effects.
  • Ideal for situations where the answer is not important in and of itself, like logging actions or updating database entries.
  • helps in keeping the answer brief and effective when the client doesn't need any data to be returned.


​public ActionResult ClearCache()
{
    // Code to clear cache goes here
    // For example:
    Cache.Clear();

    // Return EmptyResult since no data needs to be sent back to the client
    return new EmptyResult();
}

Developers have a lot of options when it comes to creating dynamic and responsive web apps with the diverse range of ActionResult types available in ASP.NET MVC. Through an understanding of the subtle differences between each ActionResult subtype and matching them to the particular needs of their applications, developers may coordinate smooth server-client interactions, improving the user experience in general.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How to Restrict Uploaded File Type in ASP.NET Core?

clock March 15, 2024 08:57 by author Peter

In ASP.NET Core MVC, you can restrict the file types that can be uploaded by adding server-side validation. Here's a simple example of how to accomplish this:

Why do we need to restrict uploaded File Type in an ASP.NET Core?

  • Security: Allowing unrestricted file uploads can pose security risks. Certain file types, such as executable files (.exe), scripts (.js, .ps1), or files containing macros (.docm), could be used to execute malicious code on the server or client-side when downloaded. Restricting file types mitigates these risks by preventing potentially harmful files from being uploaded.
  • Data Integrity: Limiting the accepted file types ensures that the application only processes files that are compatible with its functionality. Accepting only specific file types reduces the chances of errors or unexpected behavior caused by unsupported file formats.
  • Compliance: In some industries or applications, there might be regulatory or compliance requirements regarding the types of files that can be uploaded. Enforcing restrictions helps ensure compliance with such standards.
  • Resource Management: Different file types require different processing and storage resources. By restricting the allowed file types, you can better manage server resources and avoid unnecessary strain on the system.
  • User Experience: Providing clear restrictions on acceptable file types helps users understand what they can upload, reducing confusion and errors during the file upload process. This improves the overall user experience of the application.

1-Client-Side Validation (Optional): You can use the HTML5 accept attribute on your file input to restrict file types. However, keep in mind that this can be easily bypassed by users, so server-side validation is essential.
<input type="file" name="file" accept=".pdf,.doc,.docx">

2. Server-Side Validation: In your controller action, where you handle the file upload, you can check the file's content type or extension and reject files that are not allowed.
Add a controller

  • In Solution Explorer, right-click Controllers > Add > Controller.
  • In the Add New Scaffolded Item dialog box, select MVC Controller - Empty > Add.
  • In the Add New Item - RestrictUploadedFileSize_Demo dialog, enter FileUploadController.cs and select Add.

Replace the contents of Controllers/ FileUploadController.cs with the following code.
using Microsoft.AspNetCore.Mvc;

namespace RestrictUploadedFileSize_Demo.Controllers
{
    public class FileUploadController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> FileUpload(IFormFile SingleFile)
        {
            if (SingleFile == null || SingleFile.Length == 0)
            {
                ModelState.AddModelError("", "File not selected");
                return View("Index");
            }

            var permittedExtensions = new[] { ".jpg", ".png", ".gif" };
            var extension = Path.GetExtension(SingleFile.FileName).ToLowerInvariant();

            if (string.IsNullOrEmpty(extension) || !permittedExtensions.Contains(extension))
            {
                ModelState.AddModelError("", "Invalid file type.");
            }

            // Optional: Validate MIME type as well
            var mimeType = SingleFile.ContentType;
            var permittedMimeTypes = new[] { "image/jpeg", "image/png", "image/gif" };
            if (!permittedMimeTypes.Contains(mimeType))
            {
                ModelState.AddModelError("", "Invalid MIME type.");
            }

            //Validating the File Size
            if (SingleFile.Length > 10000000) // Limit to 10 MB
            {
                ModelState.AddModelError("", "The file is too large.");
            }

            if (ModelState.IsValid)
            {
                var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", SingleFile.FileName);

                //Using Streaming
                using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                {
                    await SingleFile.CopyToAsync(stream);
                }

                // Process the file here (e.g., save to the database, storage, etc.)
                return View("UploadSuccess");
            }

            return View("Index");
        }
    }
}


This code snippet checks both the file extension and content type to ensure that it meets your criteria. You can adjust the allowed file types and content types according to your requirements. Additionally, you can improve this validation logic based on your specific needs, such as checking the file's signature or using a more comprehensive file type validation library.Add a view

  • Right-click on the Views folder, then Add > New Folder and name the folder Companies
  • Right-click on the Views/ FileUpload folder, and then Add > New Item.
  • In the Add New Item dialog, select Show All Templates.
  • In the Add New Item - RestrictUploadedFileSize_Demo dialog:
  • In the search box in the upper-right, enter the view
  • Select Razor View - Empty
  • Keep the Name box value, Index.cshtml.
  • Select Add
  • Replace the contents of the Views/Companies/Index.cshtml Razor view file with the following:

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

<h2>File Upload</h2>
<hr />
<div class="row">
    <div class="col-md-12">
        <form method="post" asp-controller="FileUpload" asp-action="FileUpload"enctype="multipart/form-data">
            <div asp-validation-summary="All" class="text-danger"></div>
            <input type="file" name="SingleFile" class="form-control" />
            <button type="submit" name="Upload" class="btn btn-primary">Upload</button>
        </form>
    </div>
</div>


Run the Application

Select Ctrl+F5 to run the app without the debugger. Visual Studio runs the ASP.NET app and opens the default browser.

Restricting uploaded file types in ASP.NET Core increases security, data integrity, regulatory compliance, resource efficiency, and user experience. It's a critical component of developing robust and secure web apps.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Session Management in ASP.NET Core MVC

clock March 4, 2024 08:32 by author Peter

Importance of Sessions in Web Applications
Sessions bridge this gap by providing a means to preserve user-specific data across multiple requests within a defined period.

  • Maintain User Identity: Sessions are instrumental in user authentication and authorization processes. They allow web applications to identify and track users across various interactions, ensuring secure access to restricted resources.
  • Customized User Experience: Sessions facilitate the personalization of user experiences by storing user preferences, settings, and browsing history. This enables applications to tailor content and functionality based on individual user profiles.
  • Shopping Carts and E-commerce: In e-commerce applications, sessions are indispensable for managing shopping carts and order processing. By persisting cart contents and user selections across page transitions, sessions streamline the purchasing journey and enhance user convenience.
  • Form Persistence: Sessions enable the retention of form data entered by users, safeguarding against data loss during navigation or submission errors. This ensures a seamless and uninterrupted form-filling experience.
  • Tracking User Activity: Sessions empower web analytics and tracking mechanisms by storing user session data, such as page views, interactions, and session duration. This information aids in understanding user behavior and optimizing website performance.

Implement Session Management in ASP.NET Core MVC
Create a New ASP.NET Core MVC Project: Start by creating a new ASP.NET Core MVC project in Visual Studio or using the .NET CLI.

Install Required Packages
Install the required packages for session management using NuGet Package Manager or the .NET CLI. In this example, we'll need the Microsoft.AspNetCore.Session package.

Configure Services

In the ConfigureServices method of the Startup class, add the session services using services.AddSession().

Configure Middleware

In the Configure method of the Startup class, use the session middleware using the app.UseSession().

Create Controllers

Create controllers to handle your application's logic. For this example, we'll use HomeController and RecordsController.

Here I have created a home cotroller with an Index action method to set data into session.
public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        // Add list of records to session
        var records = new List<Record>
        {
            new Record { Id = 1, Name = "Record 1" },
            new Record { Id = 2, Name = "Record 2" },
            // Add more records here as needed
        };

        var serializedRecords = JsonSerializer.Serialize(records);
        HttpContext.Session.SetString("Records", serializedRecords);
        return RedirectToAction("GetRecords", "Records");
    }
}


Store Data in Session
In one of your controller actions (for example, the Index action of HomeController), store the data you want to maintain in the session. Serialize complex types like lists into strings or byte arrays before storing them.

I have stored data using var serializedRecords = JsonSerializer.Serialize(records);

Retrieve Data from Session
In another controller action (for example, the GetRecords action of RecordsController), retrieve the data from the session. Deserialize the stored data back into its original type if necessary.

public class RecordsController : Controller
{
    public IActionResult GetRecords()
    {
        // Retrieve list of records from session
        var records = HttpContext.Session.Get<List<Record>>("Records");
        return View(records);
    }
}


Summary
Session management is a fundamental aspect of web development, enabling developers to create interactive, personalized, and secure web applications.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How Do I Use Twilio to Send SMS in a C#.NET MVC Project?

clock February 27, 2024 06:45 by author Peter

In today's fast-paced world, where everyone uses hundreds of websites and applications every day, there are numerous in-app notifications, and all communication is critical. However, these in-app notifications will only appear when we start the app. As a result, introducing SMS capabilities into projects can greatly boost user engagement and participation. Twilio, a well-known cloud communications company, has a robust API that enables developers to easily send and receive SMS texts, among other communication functions.


This post will show you how to integrate Twilio to send SMS in a C# MVC project from scratch. So, before we get started with the project, let's register a Twilio account.

Setting up a Twilio account
To create a Twilio account, we first need to sign up, which is simple. If you already have a Twilio account, you can skip step 1 and proceed to step 2.

Step 1: Sign up for Twilio
Sign up by entering your basic information on the following link: www.twilio.com. By clicking "Continue," you will be taken to another page to validate your email address. Once the email address has been verified, you must also verify your phone number. Following that, you will be taken to another page containing a recovery code. Please copy the code and store it somewhere safe for future use.

Step 2: Login to Twilio
If you are checking in for the first time, Twilio will prompt you with a few questions. Simply answer them, and it will lead you to the dashboard/

Step 3. Get the Phone Number
Click on the "Get Phone Number" button, and you will receive the number. Before purchasing their plan, your account will be a trial account, and the number given to you will be a trial number.

Step 4. Get SID and Auth Token
In the same screen, you will have a section named "Account Info", where you will following information -Account SID, Auth Token, and My Twilio phone number, which we will be using during development.

Step 5. Verify Phone Numbers
This step is only for trial account users. Since it is a trial account, you will need to verify the numbers, on which you want to send the SMS using your project. You can skip this step if you have purchased a Twilio SMS plan. To verify numbers follow the following steps.

  • Click on the verified phone numbers link, you will be redirected to another page.
  • Click on the "Add a new caller ID" button in the right corner. A popup will open to add the number.
  • Select the country, number, and mode through which you want to verify the number.
  • Click verify the number, you will get an OTP on the number you just entered.
  • Enter the OTP to verify the number and it will be shown in verified caller IDs.

Now that you have set up the Twilio account. Let's move to the project.

Setting up the project

You can either create a new project or you can integrate Twilio into an existing project. Here, I have created a demo project to integrate Twilio in it and created a Controller named "TwilioIntegrationController". In this controller, I will be writing Twilio-related code. Let's move to the project.

Step 1. Install dependencies
To be able to integrate Twilio in the project, you will need some dependencies, that will help Twilio run.

  • Click on Tools.
  • Select "Nuget Package Manager".
  • Click "Manage Nuget Package for solution".
  • In the Browse section, search for Package "Twilio" and install the solution.
  • Then, search "Twilio.AspNet.Mvc" and install it too.

Now that you have installed all the necessary dependencies. Let's move to the next step.

Step 2. Code to Send SMS

In the "TwilioIntegrationController", write your code for sending SMS. Here, I am putting all my code in one file. But you should put the necessary code where it should be.
using Microsoft.AspNetCore.Mvc;
using Twilio;
using Twilio.Rest.Api.V2010.Account;

namespace TwilioIntegration.Controllers
{
public class TwilioIntegrationController : Controller
{
    [Route("send-SMS")]
    public IActionResult SendSMS()
    {
        string sId = ""; // add Account from Twilio
        string authToken = ""; //add Auth Token from Twilio
        string fromPhoneNumber = "+120*******"; //add Twilio phone number

        TwilioClient.Init(sId, authToken);
        var message = MessageResource.Create(
            body: "Hi, there!!",
            from: new Twilio.Types.PhoneNumber(fromPhoneNumber),
            to: new Twilio.Types.PhoneNumber("+9175********") //add receiver's phone number
        );
        Console.WriteLine(message.ErrorCode);
        return View(message);
    }
}
}

Code Explanation
In the above code,

  • Add 'using Microsoft.AspNetCore.Mvc;', 'using Twilio;', 'using Twilio.Rest.Api.V2010.Account;' to use Twilio API in the code.
  • Then, I have created a method named SendSMS().
  • In the method, I created three string variables - sId, authToken, and fromPhoneNumber to store Twilio account SId, Auth Token, and Twilio phone number. I have placed all three in this method, but you should store them in an appsettings file and access them from there.
  • Then initiate TwilioClient by passing your account SId and Auth Token, using this lineTwilioClient.Init(sId, authToken);.
  • In the next line "MessageResource.Create()" is a method call to create a new SMS message using the Twilio API. It indicates that we are creating a new message resource. We are passing the message body, from phone number and to phone number in it. It creates the message and sends it using the Twilio API.
  • In the next line, I have consoled the ErrorCode, if any error occurs during the sending of SMS.
Step 3: Call the aforementioned procedure
Call the method we defined previously from your code to send SMS from anywhere in your code, and Twilio will send the SMS to the account you specified earlier.

The above image shows that the message was successfully sent from the project, and the body is the same as we specified in our code. However, because we are using a trial account, Twilio automatically inserts the prefix "Sent from your Twilio trial account-" to all messages sent from your trial account. As a result, real-world projects benefit from purchasing a plan.

Conclusion
In this article, we learned how to create a Twilio account, configure it, and connect Twilio with the code in the C# MVC project. By setting up a Twilio account and using Twilio's API, developers may simply send and receive SMS messages, providing a valuable tool for increasing project functionality and user experience.

In the same way, Twilio can be integrated into other languages. The method is virtually identical. You may also use Twilio to deliver WhatsApp messages, audio messages, and other types of messaging by integrating it into your project. This connection enables developers to use Twilio's strong cloud communication infrastructure to improve their projects across many programming languages, resulting in more effective communication and user engagement.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Async Patterns in MVC Controllers: Are they Efficient or Add Unnecessary Complexity?

clock February 22, 2024 09:05 by author Peter

Previously, when I started implementing action methods within controllers, I took a standard approach that seemed to work. However, my curiosity drove me to investigate various ways, and what I discovered was a wide world of coding styles. It became clear that the way I developed my code was only one option among several. As I compared my methods to those used by other developers, I began to wonder if there were major disparities in logic, performance, or other factors.

In this post, we will delve into the complexities of MVC controller methods, investigating the influence of asynchronous design decisions and throwing light on the rationale for seemingly complex async patterns.

As you can see below.

In MVC controllers, one function gets users regularly, while another adds 'async' but not 'await.'

1. Normal action method in the controller
[HttpGet]
public IActionResult GetUsers()
{
    // Retrieve a list of all user objects synchronously.
    List<User> userList = _dbService.ReadAllUsers();
    return View(userList);
}
2) Action method contains async keyword without await keyword[HttpGet]
public async Task<IActionResult> GetUsers()
{
  //Do some work and get a list of all user-objects.
  List<User> userList = _dbService.ReadAllUsers();
  return View(userList);
}

In terms of functionality, the first and second methods will act similarly because the 'async' method does not contain the 'await' keyword. Both techniques will execute simultaneously, and the distinction is not relevant in this case. However, it's worth noting that the second function is declared as an asynchronous method (async Task<IActionResult>), although there are no asynchronous operations.

The method is declared as asynchronous (async Task<IActionResult>), but there are no actual asynchronous actions with the await keyword. The ReadAllUsers() method is called synchronously, with no asynchronous operations awaiting it.

3) The Action method contains async and await keyword
[HttpGet]
public async Task<IActionResult> GetUsers()
{
    // Do some work and get a list of all user-objects.
    List<User> userList = await _dbService.ReadAllUsersAsync();
    return View(userList);
}


When you use 'await' with an asynchronous operation, like _dbService.ReadAllUsersAsync(), the method will pause and wait for the asynchronous operation to complete. Importantly, the thread is not blocked during this waiting period, allowing other tasks or operations to proceed concurrently. However, in this specific case, where there is no additional asynchronous work to be performed while waiting for the _dbService.ReadAllLinesAsync() operation, the asynchronous version doesn't offer any noticeable advantages. Consequently, there wouldn't be a significant difference between the two methods.

Summary
All three of the approaches listed above will work the same way. Why write in such a sophisticated way? In a web application, using async and await might be useful, especially when dealing with many requests. It is regarded best practice to utilize async and await when there are true asynchronous operations to run or when they are expected to be introduced in the future.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Custom Filter In MVC Or Logging Using MVC Filter

clock February 15, 2024 08:34 by author Peter

In my MVC project, I want to build a filter that records every controller action. All I'm doing is injecting an ILogger object to log the logs into my table storage. This blog post explains how to make an action filter and how to add it to any action, controller, or global location.


Make an Action filter class:

    namespace Filter {  
        using System;  
        using Microsoft.AspNetCore.Mvc.Filters;  
        using Microsoft.AspNetCore.Routing;  
        using Core.Logging;  
        /// <summary>  
        /// This is tog every action activity  
        /// </summary>  
        /// <seealso cref="Microsoft.AspNetCore.Mvc.Filters.ActionFilterAttribute" />  
        [AttributeUsage(AttributeTargets.Class)]  
        public class LogActionFilterAttribute: ActionFilterAttribute {  
            private readonly ILogger logger;  
            /// <summary>  
            /// Initializes a new instance of the <see cref="LogActionFilterAttribute" /> class.  
            /// </summary>  
            /// <param name="logger">The logger.</param>  
            public LogActionFilterAttribute(ILogger logger) {  
                this.logger = logger;  
            }  
            /// <summary>  
            /// Called when [action executing].  
            /// </summary>  
            /// <param name="context">The filter context.</param>  
            public override void OnActionExecuting(ActionExecutingContext context) {  
                this.Log("OnActionExecuting", context.RouteData);  
                base.OnActionExecuting(context);  
            }  
            /// <summary>  
            /// Called when [action executed].  
            /// </summary>  
            /// <param name="context"></param>  
            /// <inheritdoc />  
            public override void OnActionExecuted(ActionExecutedContext context) {  
                this.Log("OnActionExecuted", context.RouteData);  
                base.OnActionExecuted(context);  
            }  
            /// <summary>  
            /// Called when [result executing].  
            /// </summary>  
            /// <param name="context">The filter context.</param>  
            public override void OnResultExecuting(ResultExecutingContext context) {  
                this.Log("OnResultExecuting", context.RouteData);  
                base.OnResultExecuting(context);  
            }  
            /// <summary>  
            /// Called when [result executed].  
            /// </summary>  
            /// <param name="context">The filter context.</param>  
            public override void OnResultExecuted(ResultExecutedContext context) {  
                this.Log("OnResultExecuted", context.RouteData);  
                base.OnResultExecuted(context);  
            }  
            /// <summary>  
            /// Logs the specified method name.  
            /// </summary>  
            /// <param name="methodName">Name of the method.</param>  
            /// <param name="routeData">The route data.</param>  
            private void Log(string methodName, RouteData routeData) {  
                var controllerName = routeData.Values["controller"];  
                var actionName = routeData.Values["action"];  
                string message = $ "MethodName :{methodName} , controller:{controllerName} , action:{actionName}";  
                this.logger.log(message);  
            }  
        }  
    }  

How to make any controller to use this action filter:

Method 1
If you want the functionality to enable for all controllers by default

In starup.cs write the below line:
services.AddMvc(options =>  

options.Filters.Add(typeof(LogActionFilterAttribute));  

});  

Method 2
If you want to use it in Controller specifically:

In starup.cs write the below line:
services.AddScoped<LogActionFilterAttribute>();    

In Action Method or controller use the below attribute:
[ServiceFilter(typeof(ExampleFilterWithDI))]  



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Stars Rating System in ASP.NET Core MVC with Dapper

clock January 30, 2024 07:14 by author Peter

The construction of ASP.NET Core MVC web applications using controllers and views is covered in this lesson. There are various phases involved in implementing a star rating system using Dapper in.NET Core. To save ratings, you must first configure your database schema. Next, in order to communicate with the database, you'll need to establish the Dapper repository and the required model classes.

What is Rate Yo?
Rate Yo is a free, tiny, and flexible jQuery star rating plugin, it uses SVG to generate an image and render rating, so no images are required.

Prerequisites

  • Visual Studio is the latest version with the ASP.NET and web development workload.
  • .NET SDK latest version (.NET 8.0)
  • SQL SERVER latest

Making a table in a database
Start SQL Server, choose Database, then click Create New Database.

CREATE TABLE [dbo].[t_company_rating]
(
    [f_uid]              UNIQUEIDENTIFIER PRIMARY KEY NOT NULL,
    [f_iid]              INT              IDENTITY (1, 1) NOT NULL,
    [f_company_name]     NVARCHAR (100)   NULL,
    [f_company_location] NVARCHAR (100)   NULL,
    [f_country]          NVARCHAR (100)   NULL,
    [f_glassdoor_rating] FLOAT (53)       NULL,
)

Starting a New Visual Studio Project
Open Visual Studio, then choose File > New Project.


Make a Web Application

  • Launch Visual Studio, then choose File > New Project
  • Select the ASP.NET Core Web App (Model-View-Controller) > Next option from the Create a new project dialog box

Setting Up Your New Project
Enter RatingSystem_Demo as the project name in the Configure your new project dialog.

  • The project should be named RatingSystem_Demo. When copying code, capitalization must match each namespace.
  • Select a place to work on your project.
  • Name the solution.
  • Click on Next.

Additional information
In the Additional information dialog.

  • Select .NET 8.0 (Long Term Support).
  • Verify that Do not use top-level statements is unchecked.
  • Select Create.

Option 1. Install the Dapper, Microsoft.Data.SqlClient Library through NuGet Package Manager

  • Go to Project > Manage NuGet Packages.
  • On the NuGet Package Manager page, select nuget.org as the Package source.
  • Under the Browse tab, search for Dapper, then choose Dapper from the list and select Install.
  • If prompted to verify the installation, click OK.

Option 2: Using the Visual Studio Command Line to install the Dapper Library
Go to Tools > NuGet Package Manager > Package Manager Console in Visual Studio.
Under the Package Manager Console tab, type the following command.
Install-Package Dapper

Add RateYo library files

Library files can be added to an ASP.NET Core project in two different ways.

  • Use the Add Client-Side Library dialog
  • Manually configure LibMan manifest file entries

Use the Add Client-Side Library dialog
Follow these steps to install a client-side library.
In Solution Explorer, right-click the project folder in which the files should be added. Choose Add > Client-Side Library. The Add Client-Side Library dialog appears.

Add Client-side Library

The suggested Target Location folder is based on the location from which the dialog is launched.
If launched from the project root.

  • wwwroot/lib is used if wwwroot exists.
  • lib is used if wwwroot doesn't exist.
  • If launched from a project folder, the corresponding folder name is used.

The folder suggestion is suffixed with the library name. The following table illustrates folder suggestions when installing jQuery in a Razor Pages project.

Click the Install button to download the files, per the configuration in libman.json.

Add a data model class

Right-click the Models folder > Add > Class. Name the file CompanyModel.cs.
Replace the Models/CompanyModel.cs file with using c# following code.
The CompanyModel class contains a f_uid field, which is required by the database for the primary key.

CompanyModel.cs
using System.ComponentModel.DataAnnotations;

namespace RatingSystem_Demo.Models
{
    public class CompanyModel
    {
        public Guid f_uid { get; set; }

        [Display(Name ="ID")]
        public int f_iid { get; set; }

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

        [Display(Name = "Location")]
        public string f_company_location { get; set; }

        [Display(Name = "Country")]
        public string f_country { get; set; }

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


Adding interfaces

  • In Solution Explorer, right-click Add New Folder.
  • Rename the folder to Repositories.
  • Right-click on the renamed folder and Add the interface name IGenericRepository.cs

IGenericRepository.cs
namespace RatingSystem_Demo.Repositories
{
    public interface IGenericRepository<T> where T : class
    {
        Task<IEnumerable<T>> Get();
        Task<T> Find(Guid uid);
        Task<T> Add(T model);
        Task<T> Update(T model);
        Task<T> Remove(T model);
    }
}


IUnitOfWork.cs
namespace RatingSystem_Demo.Repositories
{
    public interface IUnitOfWork
    {
        ICompany Companies { get; }
    }
}

ICompany.cs
using RatingSystem_Demo.Models;

namespace RatingSystem_Demo.Repositories
{
    public interface ICompany:IGenericRepository<CompanyModel>
    {

    }
}


Interface Implementation
UnitOfWork.cs
namespace RatingSystem_Demo.Repositories
{
    public class UnitOfWork : IUnitOfWork
    {
        public ICompany Companies { get; set; }
        public UnitOfWork(ICompany Companies)
        {
            this.Companies = Companies;
        }
    }
}

CompanyRepository.cs
using Dapper;
using Microsoft.Data.SqlClient;
using RatingSystem_Demo.Models;

namespace RatingSystem_Demo.Repositories
{
    public class CompanyRepository : ICompany
    {
        private readonly IConfiguration _configuration;
        private readonly SqlConnection _connection;
        public CompanyRepository(IConfiguration configuration)
        {
            _configuration = configuration;
            _connection = new SqlConnection(_configuration.GetConnectionString("DefaultConnection"));
        }
        public async Task<IEnumerable<CompanyModel>> Get()
        {
            var sql = $@"
                        SELECT [f_uid]
                              ,[f_iid]
                              ,[f_company_name]
                              ,[f_company_location]
                              ,[f_country]
                              ,[f_glassdoor_rating]
                          FROM
                               [Sample-DB].[dbo].[t_company_rating]
                               ORDER BY f_iid ASC";

            return await _connection.QueryAsync<CompanyModel>(sql);
        }
        public async Task<CompanyModel> Find(Guid uid)
        {
            var sql = $@"
                        SELECT [f_uid]
                              ,[f_iid]
                              ,[f_company_name]
                              ,[f_company_location]
                              ,[f_country]
                              ,[f_glassdoor_rating]
                          FROM [Sample-DB].[dbo].[t_company_rating]
                          WHERE
                               [f_uid]=@uid";

            return await _connection.QueryFirstOrDefaultAsync<CompanyModel>(sql, new { uid });
        }
        public async Task<CompanyModel> Add(CompanyModel model)
        {
            model.f_uid = Guid.NewGuid();

            var sql = $@"
                     INSERT INTO [dbo].[t_company_rating]
                           ([f_uid]
                           ,[f_company_name]
                           ,[f_company_location]
                           ,[f_country]
                           ,[f_glassdoor_rating])
                     VALUES
                           (@f_uid,
                            @f_company_name,
                            @f_company_location,
                            @f_country,
                            @f_glassdoor_rating)";

            await _connection.ExecuteAsync(sql, model);
            return model;
        }
        public async Task<CompanyModel> Update(CompanyModel model)
        {
            var sql = $@"UPDATE [dbo].[t_company_rating]
                        SET
                            [f_company_name] = @f_company_name,
                            [f_company_location] = @f_company_location,
                            [f_country] = @f_country,
                            [f_glassdoor_rating] = @f_glassdoor_rating
                         WHERE
                            f_uid=@f_uid";

            await _connection.ExecuteAsync(sql, model);
            return model;
        }
        public async Task<CompanyModel> Remove(CompanyModel model)
        {
            var sql = $@"
                        DELETE FROM
                            [dbo].[t_company_rating]
                        WHERE
                            [f_uid]=@f_uid";

            await _connection.ExecuteAsync(sql, model);
            return model;
        }
    }
}

Add a controller

  • In Solution Explorer, right-click Controllers > Add > Controller.
  • In the Add New Scaffolded Item dialog box, select MVC Controller - Empty > Add.
  • In the Add New Item - RatingSystem_Demo dialog, enter CompaniesController.cs and select Add.

Replace the contents of Controllers/CompaniesController.cs with the following code.
using Microsoft.AspNetCore.Mvc;
using RatingSystem_Demo.Models;
using RatingSystem_Demo.Repositories;

namespace RatingSystem_Demo.Controllers
{
    public class CompaniesController : Controller
    {
        private readonly IUnitOfWork unitOfWork;
        public CompaniesController(IUnitOfWork unitOfWork)
        {
            this.unitOfWork = unitOfWork;
        }
        public async Task<IActionResult> Index()
        {
            var companies = await unitOfWork.Companies.Get();
            var ratings = companies.Select(x => x.f_glassdoor_rating).ToList();
            ViewBag.Ratings = string.Join(", ", ratings);
            return View(companies);
        }
        public async Task<IActionResult> Details(Guid id)
        {
            var company = await unitOfWork.Companies.Find(id);
            return View(company);
        }

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

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(CompanyModel model)
        {
            var company = await unitOfWork.Companies.Add(model);
            return RedirectToAction(nameof(Index));
        }

        [HttpGet]
        public async Task<IActionResult> Edit(Guid id)
        {
            if (id == Guid.Empty)
            {
                return NotFound();
            }
            var company = await unitOfWork.Companies.Find(id);
            if (company == null)
            {
                return BadRequest();
            }
            return View(company);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(Guid id, CompanyModel model)
        {
            if (id == Guid.Empty)
            {
                return NotFound();
            }
            var company = await unitOfWork.Companies.Find(id);
            if (company == null)
            {
                return BadRequest();
            }
            await unitOfWork.Companies.Update(model);
            return RedirectToAction(nameof(Index));
        }
        public async Task<IActionResult> Delete(Guid id)
        {
            if (id == Guid.Empty)
            {
                return NotFound();
            }
            var company = await unitOfWork.Companies.Find(id);
            if (company == null)
            {
                return BadRequest();
            }
            return View(company);
        }

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> ConfirmDelete(Guid id)
        {
            var company = await unitOfWork.Companies.Find(id);
            await unitOfWork.Companies.Remove(company);
            return RedirectToAction(nameof(Index));
        }
    }
}


Add a view

  • Right-click on the Views folder, then Add > New Folder, and name the folder Companies
  • Right-click on the Views/Companies folder, and then Add > New Item.
  • In the Add New Item dialog, select Show All Templates.
  • In the Add New Item - RatingSystem_Demo dialog:
  • In the search box in the upper-right, enter the view
  • Select Razor View - Empty
  • Keep the Name box value, Index.cshtml.
  • Select Add

Replace the contents of the Views/Companies/Index.cshtml, Create.cshtml, Edit.cshtml and Delete.cshtml Razor view file with the following:

Index.cshtml
@model IEnumerable<RatingSystem_Demo.Models.CompanyModel>

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

<h4 class="text-uppercase text-center">List of companies</h4>

<p style="float:right"><a asp-action="Create" class="btn btn-primary btn-md rounded-0"><i class="fa-solid fa-plus"></i> Add New</a></p>
<table class="table table-bordered table-striped">
    <thead>
        <tr>
            <th>@Html.DisplayNameFor(model => model.f_iid)</th>
            <th>@Html.DisplayNameFor(model => model.f_company_name)</th>
            <th>@Html.DisplayNameFor(model => model.f_company_location)</th>
            <th>@Html.DisplayNameFor(model => model.f_country)</th>
            <th>@Html.DisplayNameFor(model => model.f_glassdoor_rating)</th>
            <th>Action(s)</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model) {
        <tr>
            <td>@item.f_iid</td>
            <td><a style="text-decoration:none" href="@Url.Action("Details","Companies", new { id = item.f_uid })">@item.f_company_name</a></td>
            <td>@item.f_company_location</td>
            <td>@item.f_country</td>
            <td>
                <span style="float:left;display:inline">@item.f_glassdoor_rating <span style="float:left;display:inline" class="rateYo"></span></span>
            <td>
                <a href="@Url.Action("Edit","Companies", new { id = item.f_uid })" class="btn btn-info btn-sm rounded-0"><i class="fa-solid fa-pen-to-square"></i></a>
                <a href="@Url.Action("Delete","Companies", new { id = item.f_uid })" class="btn btn-danger btn-sm rounded-0"><i class="fa-solid fa-trash"></i></a>
            </td>
        </tr>
}
    </tbody>
</table>
@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
    <script type="text/javascript">
        $(function () {
             var demoRatings = [@ViewBag.Ratings],
            stars = $('.rateYo');
            for (var i = 0; i < stars.length; i++) {
                $('.rateYo').eq(i).rateYo({
                    rating: demoRatings[i],
                    readOnly: true
                });
            }
        });
    </script>
}

Create.cshtml
@model RatingSystem_Demo.Models.CompanyModel

@{
    ViewData["Title"] = "Create";
}
<div class="container">
    <div class="card">
        <div class="card-header">
            <h4>Compnay</h4>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-4">
                    <form asp-action="Create">
                        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                        <div class="form-group">
                            <label asp-for="f_company_name" class="control-label"></label>
                            <input asp-for="f_company_name" class="form-control" />
                            <span asp-validation-for="f_company_name" class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label asp-for="f_company_location" class="control-label"></label>
                            <input asp-for="f_company_location" class="form-control" />
                            <span asp-validation-for="f_company_location" class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label asp-for="f_country" class="control-label"></label>
                            <input asp-for="f_country" class="form-control" />
                            <span asp-validation-for="f_country" class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label asp-for="f_glassdoor_rating" class="control-label"></label>
                            <input asp-for="f_glassdoor_rating" readonly class="form-control counter" />
                            <br />
                            <div id="rateYo"></div>
                            <br />
                            <span asp-validation-for="f_glassdoor_rating" class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <input type="submit" value="Save" class="btn btn-primary btn-md rounded-0" />
                            <a asp-action="Index" class="btn btn-primary btn-md rounded-0"><i class="fa-solid fa-backward"></i>Back to List </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
     </div>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script>
        $(function () {
            $("#rateYo").rateYo({
                onChange: function (rating, rateYoInstance) {
                    $("#f_glassdoor_rating").val(rating);
                }
            });
        });
    </script>
}

Edit.cshtml
@model RatingSystem_Demo.Models.CompanyModel

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

<div class="container">
    <div class="card">
        <div class="card-header">
            <h4>Compnay</h4>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-4">
                    <form asp-action="Edit">
                        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                        <input hidden asp-for="f_uid" />
                        <input hidden asp-for="f_iid" />
                        <div class="form-group">
                            <label asp-for="f_company_name" class="control-label"></label>
                            <input asp-for="f_company_name" class="form-control" />
                            <span asp-validation-for="f_company_name" class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label asp-for="f_company_location" class="control-label"></label>
                            <input asp-for="f_company_location" class="form-control" />
                            <span asp-validation-for="f_company_location" class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label asp-for="f_country" class="control-label"></label>
                            <input asp-for="f_country" class="form-control" />
                            <span asp-validation-for="f_country" class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label asp-for="f_glassdoor_rating" class="control-label"></label>
                            <input asp-for="f_glassdoor_rating" readonly class="form-control counter" />
                            <br />
                            <div id="rateYo"></div>
                            <br />
                            <span asp-validation-for="f_glassdoor_rating" class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <input type="submit" value="Save" class="btn btn-primary btn-md rounded-0" />
                            <a asp-action="Index" class="btn btn-primary btn-md rounded-0"><i class="fa-solid fa-backward"></i>Back to List </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
    <script>
        $(function () {
            $("#rateYo").rateYo({
                rating: @Model.f_glassdoor_rating,
                onChange: function (rating, rateYoInstance) {
                    $("#f_glassdoor_rating").val(rating);
                }
            });
        });
    </script>
}


Delete.cshtml
@model RatingSystem_Demo.Models.CompanyModel

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

<div class="container">
    <div class="card">
        <div class="card-header">
            <h4>Compnay</h4>
        </div>
        <div class="card-body">
            <h5 class="alert alert-danger" role="alert">Are you sure you want to delete this?</h5>
            <dl class="row">
                <dt class="col-sm-2">
                    @Html.DisplayNameFor(model => model.f_iid)
                </dt>
                <dd class="col-sm-10">
                    @Html.DisplayFor(model => model.f_iid)
                </dd>
                <dt class="col-sm-2">
                    @Html.DisplayNameFor(model => model.f_company_name)
                </dt>
                <dd class="col-sm-10">
                    @Html.DisplayFor(model => model.f_company_name)
                </dd>
                <dt class="col-sm-2">
                    @Html.DisplayNameFor(model => model.f_company_location)
                </dt>
                <dd class="col-sm-10">
                    @Html.DisplayFor(model => model.f_company_location)
                </dd>
                <dt class="col-sm-2">
                    @Html.DisplayNameFor(model => model.f_country)
                </dt>
                <dd class="col-sm-10">
                    @Html.DisplayFor(model => model.f_country)
                </dd>
                <dt class="col-sm-2">
                    @Html.DisplayNameFor(model => model.f_glassdoor_rating)
                </dt>
                <dd class="col-sm-10">
                    <div id="rateYo"></div>
                </dd>
            </dl>
        </div>
        <div class="card-footer">
            <form asp-action="Delete">
                <button type="submit" class="btn btn-danger btn-sm rounded-0"><i class="fa-solid fa-trash"></i></button>
                <a asp-action="Index" class="btn btn-primary btn-sm rounded-0"><i class="fa-solid fa-backward"></i></a>
            </form>
        </div>
    </div>
</div>
@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
    <script>
        $(function () {
            $("#rateYo").rateYo({
                rating: @Model.f_glassdoor_rating,
                readOnly: true
            });
        });
    </script>
}


Add repository services to the Program.cs
The object get method handles for example the task of connecting to the database and mapping Speaker objects to database records.
The database context get method is registered with the Dependency Injection container using the C# method, for example, the Program.cs file.
builder.Services.AddTransient<ICompany, CompanyRepository>();
builder.Services.AddTransient<IUnitOfWork, UnitOfWork>()

C#
Add Connection String

The ASP.NET Core Configuration system reads the DefaultConnection key. For local development, it gets the connection string from the appsettings.json file.

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=farhan1086\\SQLEXPRESS;Initial Catalog=Sample-DB;Integrated Security=True;MultipleActiveResultSets=True;Encrypt=False;TrustServerCertificate=False;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Run the Application
Select Ctrl+F5 to run the app without the debugger. Visual Studio runs the ASP.NET app and opens the default browser.




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