How to handle page not found exception message in asp.net MVC 5.0 in user friendly ways


WordPress.com

If we have asp.net mvc 5.0 application and we are searching some different page on browser then we will get the exception message.

“The resource cannot be found” I.e HTTP 404 status code.

To display this error message as user friendly we can install the “NotFoundMVC” Nuget package in Visual studio like this

NotFound

Now go to the web config file and delete the this line of code. This is the problem in this NuGet package, which is creating some invalid code in web config file.

WebConfig

Now this package will create the Not found page for you.

This will also add the required code in web config file like this

Now run the application with wrong controller/Action name. It will give user friendly error message like this

Limitation of Control
This control does not handle the other error message. It will handle on status code 404. For other error we have to implement separate error handle approach.

Summary:
I hope this post will help to implement the user friendly error message for http status code 404.

WordPress.com

Advertisement

How to implement Structure Map in Asp.net MVC application?


Recently while working on one of client web based project, I got a chance to explore the structure map, so I have created small note on this topic

What is structure map ?

Structure map is the open source tool for creating the dependency in C#. As we know that using dependency injection we can create the loosely couple application. Which is one of the best practice for do architecture of any project.

There are so many open source tool available in community, but this is one of the famous IOC tool. Some of these are

Unity, Autofac, Ninject, StructureMap, etc

I have already written one post on Unity

https://chandradev819.wordpress.com/2018/06/05/how-to-implement-the-dependency-injection-in-asp-net-mvc/

In this small demo we are going to create simple MVC application where we will use this tool.
Step 1: Create the MVC application like this

Step 2: Add the structure map IOC by nuget package manager like this

You can also install the package manger using nuget console like this
PM> install-package StructureMap.MVC5

Step 3:
Structure Map tool will create the required file for application as given below image

Note: In the above all files the important file is DefaultRegistry we are going to configure the structuremap container

There are two approaches to configure the container

1. By using Auto registration (which will be there by default)
2. By using the explicit registration


Example for explicit registration

public DefaultRegistry()
{
Scan(
scan =>
{
scan.TheCallingAssembly();
//Approach 1
// scan.WithDefaultConventions();
scan.With(new ControllerConvention());
});

//Approach 2
For().Use();
}

Example for Auto registration

public DefaultRegistry()
{
Scan(
scan =>
{
scan.TheCallingAssembly();
//Approach 1
scan.WithDefaultConventions();
scan.With(new ControllerConvention());
});

//Approach 2
// For().Use();
}

Step 4: Create the Emp Model class in Models folder like this

namespace StructureMap_InMvc_Demo.Models.EmpRepo
{
    public class Emp
    {
        public int Id { get; set; }
        public string EmpName { get; set; }
        public string EmpAddress { get; set; }

    }

}

Step 5: Create the interface like this

using System.Collections.Generic;

namespace StructureMap_InMvc_Demo.Models.EmpRepo
{
    public interface IEmpRepository
    {
        IEnumerable<Emp> GetEmps();
    }
}

Step 6: Create the EmpRepository like this

using System.Collections.Generic;

namespace StructureMap_InMvc_Demo.Models.EmpRepo
{
    public class EmpRepository : IEmpRepository
    {
        public IEnumerable<Emp> GetEmps()
        {
            var empData = new List<Emp>()
            {
              new Emp{Id=1,EmpName="Chandradev", EmpAddress="Bangalore"},
              new Emp{Id=2,EmpName="Anvi", EmpAddress="Bangalore"},
              new Emp{Id=3,EmpName="Mohan", EmpAddress="Bangalore"}
            };
            return empData;
        }

    }
}

Step 7: Create the EmpController and write the code like this

using StructureMap_InMvc_Demo.Models.EmpRepo;
using System.Web.Mvc;

namespace StructureMap_InMvc_Demo.Controllers
{
    public class EmpController : Controller
    {
        private readonly IEmpRepository _empRepository;
        public EmpController(IEmpRepository empRepository)
        {
            _empRepository = empRepository;
        }
        // GET: Emp
        public ActionResult Index()
        {
            var emps = _empRepository.GetEmps();
            return View(emps);
        }
    }
}

Step 8: Create the view like this

@model IEnumerable<StructureMap_InMvc_Demo.Models.EmpRepo.Emp>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.EmpName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.EmpAddress)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.EmpName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.EmpAddress)
        </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>

Step 9: Run the application and navigate to emp controller, you will get out put like this

How to Implement the dependency injection in asp.net MVC ?


what is the dependency injection ?

Dependency Injection is a software design pattern that allow us to develop loosely coupled application.

What is the Inversion of Control (IoC) ?

Inversion of Control (IoC) refers to a programming style where a framework controls the program flow with the help of Dependency Injection.

How to Implement the Dependency Injection in Asp.net MVC application ?

We can implement the dependency injection in the following ways

Step 1: Create the MVC application.
Step 2: Go to Solution explorer and click on Manage Nuget Packages and search for Unity.mvc5. Click to install Unity.mvc5 package in ASP.NET MVC application.

Step 3: Create the Service folder in asp.net MVC application and write some simple service using interface like this

namespace Dependency_Injection_Sample.Service
{
    /// <summary>
    /// Defines the <see cref="ICompanyService" />
    /// </summary>
    public interface ICompanyService
    {
        /// <summary>
        /// This is the interface
        /// </summary>
        /// <returns>string</returns>
        string getCompany();
    }
}

Step 4: Create the CompanyService class using interface like this

namespace Dependency_Injection_Sample.Service
{
    /// <summary>
    /// This is the CompanyService class
    /// </summary>
    public class CompanyService : ICompanyService
    {
        /// <summary>
        /// Defines the Name
        /// </summary>
        private const string Name = "Chandradev Software Pvt Ltd.";

        /// <summary>
        /// This will return the company Name
        /// </summary>
        /// <returns>string</returns>
        public string getCompany()
        {
            return Name;
        }
    }
}


Step 5: Go to the UnityConfig file and register the components like this

Step 6: Now go to the home controller and create the dependency injection using private constructor like this

Step 7: In index page, you call the Viewbag like this

@ViewBag.CompanyName

Step 7: Now run the application, you will see the output like this

How to do CRUD operations in Asp.net Web API ? (Part 2)


Hi

We can do CRUD(Create Read Update and Delete) operations in Web API as given below

Step 1: Create the new project from visual studio like this

Step 2: Create the tblEmp with Id, EmpName and EmpAddress in database as given below

Step 3: Go to the model folder and add the data model as given below

Step 4: Right click on controller folder and Add the Web API controller like this

Add the suitable Model class and data context class as per as your application

Step 5: Now your Web API controller is ready to use in any application

using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web.Http.Description;
using WebApi_Sample.Models;

namespace WebApi_Sample.Controllers.Web_Api
{
    public class Emps_API_Controller : ApiController
    {
        private Database1Entities db = new Database1Entities();

        // GET: api/Emps_API_
        public IQueryable<tblEmp> GettblEmps()
        {
            return db.tblEmps;
        }

        // GET: api/Emps_API_/5
        [ResponseType(typeof(tblEmp))]
        public IHttpActionResult GettblEmp(int id)
        {
            tblEmp tblEmp = db.tblEmps.Find(id);
            if (tblEmp == null)
            {
                return NotFound();
            }

            return Ok(tblEmp);
        }

        // PUT: api/Emps_API_/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PuttblEmp(int id, tblEmp tblEmp)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != tblEmp.Id)
            {
                return BadRequest();
            }

            db.Entry(tblEmp).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!tblEmpExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/Emps_API_
        [ResponseType(typeof(tblEmp))]
        public IHttpActionResult PosttblEmp(tblEmp tblEmp)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.tblEmps.Add(tblEmp);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = tblEmp.Id }, tblEmp);
        }

        // DELETE: api/Emps_API_/5
        [ResponseType(typeof(tblEmp))]
        public IHttpActionResult DeletetblEmp(int id)
        {
            tblEmp tblEmp = db.tblEmps.Find(id);
            if (tblEmp == null)
            {
                return NotFound();
            }

            db.tblEmps.Remove(tblEmp);
            db.SaveChanges();

            return Ok(tblEmp);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool tblEmpExists(int id)
        {
            return db.tblEmps.Count(e => e.Id == id) > 0;
        }
    }
}

Step 6: Now test on browser for get method. you will get the output as given below

Summary:

In this post we learnt that how to create the CRUD operation using Entity Framework with asp.net web api. We also observed that in Asp.net Web API, we cannot give any method name similar to Asp.net MVC controller.
Method Name should always start with HTTP Verbs i.e (GET,PUT, POST and DELETE)

  • Create -> POST
  • Read -> GET
  • Update -> PUT
  • Delete -> DELETE
  • Different ways of doing serialization and deserialization in .Net (Asp.net/Asp.net MVC) (Part 3)


    Method1

    Method 1: Using System.Runtime.Serialization.Json Namespace

    Method 2: Using System.Web.Script.Serialization Namespace

    Method 3:

    In this method we will use the Newtonsoft.Json dll

    This is one of the most popular open source dll, we install it from Nuget package manager or from google download it and add to our project

    We can write code as given below

    
    using Newtonsoft.Json;
    using System;
    
    namespace WebApplication1
    {
        public partial class Demo3 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                EmpDemo objEmp = new EmpDemo
                {
                    Id = 1021,
                    EmpName = "Chandradev",
                    EmpAddress = "Bangalore"
                };
    
                string jsonData = JsonConvert.SerializeObject(objEmp);
                Response.Write("<b>Converting to Json </b> " + "</br>");
                Response.Write("</br>");
                Response.Write(jsonData);
                Response.Write("</br>");
    
                var objEmp1 = JsonConvert.DeserializeObject<EmpDemo>(jsonData);
                Response.Write("</br>");
                Response.Write("Converting Json to .Net Object:");
                Response.Write("</br>");
                Response.Write("Id: " + objEmp1.Id + "</br>");
                Response.Write("EmpName: " + objEmp1.EmpName + "</br>");
                Response.Write("EmpAddress: " + objEmp1.EmpAddress + "</br>");
            }
    
            public class EmpDemo
            {
                public int Id { get; set; }
                public string EmpName { get; set; }
                public string EmpAddress { get; set; }
            }
        }
    }
    
    

    Note: donot forget to include the Newtonsoft.Json namespace in your code. This approach can be used in Asp.net or asp.net mvc application.