Friday, May 19, 2017

Exceptions In MVC


(7 methods explained)
 
Method 1:- Simple way

Method 2:- Override "OnException" method

Method 3:- Using "HandleError" Attribute

Method 4:- Inheriting from "HandleErrorAttribute"

Method 5:- Handling HTTP errors

Method 6:- Global Error handling in MVC

Method 7 : Should create a log file in the system

 

Method 1:- Simple way
But if we use this method then we will not be utilizing MVC exception mechanismproperly and completely.
public ActionResult SomeError() { try {} catch(Exception ex) {return View("Error");} } 


Controller.



 View


Output:


Method 2:- Override “OnException” method

This approach is used when we want to handle all the exceptions across the Action methods at the controller level.
Controller
 public ActionResult Test()
        {
            int x = 1, y = 0;
            int z = x % y;
            return View();
        }

        protected override void OnException(ExceptionContext filterContext)
        {
            Exception ex = filterContext.Exception;
            filterContext.ExceptionHandled = true;

            var model = new HandleErrorInfo(filterContext.Exception, "Controller", "Action");
            filterContext.Result = new ViewResult()
            {
                ViewName = "Error",
                ViewData = new ViewDataDictionary(model.Exception.Message)
            };
        }

        public ActionResult Error()
        {
            return View();
        }
        // GET: Home
        public ActionResult Index()
        {
                int x = 1, y = 0;
                int z = x % y;
                return View();
        }

 


Output:

Second Example:

protected override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            {
                //return;
            }

            if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500)
            {
                //return;
            }

            // if the request is AJAX return JSON else view.
            if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                filterContext.Result = new JsonResult
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new
                    {
                        error = true,
                        message = filterContext.Exception.Message
                    }
                };
            }
            else
            {
                var controllerName = (string)filterContext.RouteData.Values["controller"];
                var actionName = (string)filterContext.RouteData.Values["action"];
                var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
                filterContext.Result = new ViewResult
                {
                    ViewName = "Error",
                    ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                    TempData = filterContext.Controller.TempData
                };
            }

            // log the error using log4net.
            //_logger.Error(filterContext.Exception.Message, filterContext.Exception);

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;

            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }


In the View write the following code


Output:


The problem with this approach is we cannot reuse the error handling logic across multiple controllers.





The other way of handling error is my using “HandleError” attribute. Implementing “HandleError” attribute is a two-step process:-

Step 1 :- We need to first decorate the action method with “HandleError” attribute as shown in the below code

public class HomeController : Controller
 {
        [HandleError()]
        public ActionResult SomeError()
        {
            throw new Exception("test");
        }
}



Step 2:- In the “Web.config” file you need to add the “customErrors” tag and point to the “Error” view as shown in the below “Web.config” code snippet.
Hide  


<system.web>
<customErrors defaultRedirect="Error.cshtml" mode="On">
</customErrors>
</system.web>












In case you want different error views for different exception types you can decorate action method with multiple “HandleError” attribute point to multiple views as per exception types.

public class HomeController : Controller
{
        [HandleError(ExceptionType=typeof(ArithmeticException),View="Arthimetic")]
[HandleError(ExceptionType = typeof(NotImplementedException),View ="Error1")]


public ActionResult SomeError()
{
   
}


}




Still working on it..............................

Wednesday, May 17, 2017

Partial Views Example 4

Create a Controller A & B

























 


public class BController : Controller
    {
        // GET: B
        public ActionResult Index()
        {
            List<B> objlist = new List<B>();
            B objB = new B();
            objB.EmpID = 5;
            objB.EmpName = "Ramkee Gurrala";
            objB.Companyname = "Avent IT Solution";
            objlist.Add(objB);
            objB.ListEmpB = objlist;
            return View(objB);
           
        }
    }


public class AController : Controller
    {
        // GET: A
        public ActionResult Index()
        {
            List<A> objlist = new List<A>();
            A objA = new A();
            objA.PersonAid = 523;
            objA.PaersonAname = "Rajakonda Ashok";
            objA.PersonAage = 0;
            objlist.Add(objA);
            objA.ListPersonA = objlist;
            return View(objA);
        }

    }


Partial Controller.cs

public class PartialController : Controller
    {
        // GET: Partial
        public ActionResult Index()
        {
            List<Partial> objlistcar = new List<Partial>();
            Partial objcar = new Partial();
            objcar.CarID = 1;
            objcar.CarColor = "Rajakonda Uday";
            objcar.CarPrice = 20000;
            objcar.CarType = "sporty";
            objlistcar.Add(objcar);
            // add item in lists
            Partial objcar1 = new Partial();
            objcar1.CarID = 2;
            objcar1.CarColor = "Rajakonda Devaansh";
            objcar1.CarPrice = 20000;
            objcar1.CarType = "Snajsb";


            objlistcar.Add(objcar1);  // add item in list
            objcar.Listcar = objlistcar; // assigning value to CarModel object
            return View(objcar);
            return View();
        }

   


Output:






Partial View Example 3

Create a Controller A  & B




 public class AController : Controller
    {
        // GET: A
        public ActionResult Index(A currentpage)
        {
            return View();
        }
    }

public class BController : Controller
    {
        // GET: B
        public ActionResult Index(B Currentpage)
        {
            return View();
        }
    
        

    }

Create a Model with Name Partial.cs in Model Folder

namespace PartialView2.Models
{
    public class Partial
    {
        public int CarID { get; set; }
        public string CarType { get; set; }
        public int CarPrice { get; set; }
        public string CarColor { get; set; }
        public List<Partial> Listcar { get; set; }

    }

}

Image is shown below:




Go to A controller Index , and write the below code as shown below


@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h1>This Is A Page</h1>
    <div> 
        @{
            Html.RenderAction("Index", "Partial");
        }
    </div>
</body>

</html>


Image as shown Below


B Controller Index 





Partial Controller.cs


Partial Controller Index




Code 

@model PartialView2.Models.Partial
<table style="background-color: rosybrown; border:dashed;">
    <tr>
        <td colspan="3"><h2>Child View</h2></td>
    </tr>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.CarID)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.CarType)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.CarPrice)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.CarColor)
        </th>
    </tr>
    @foreach (var item in Model.Listcar)
    {<tr>
            <td>
                @Html.DisplayFor(modelItem => item.CarID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CarType)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CarPrice)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CarColor)
            </td>
        </tr>
    }

</table>              



Output:

  

Tuesday, May 16, 2017

Render Partial View Example 2

Creating Model


public class CarModel
{
public int CarID { getset; }
public string CarType { getset; }
public int CarPrice { getset; }
public string CarColor { getset; }

public List<CarModel> Listcar { getset; } // List of Car
}
}

Creating Controller

public class CarController : Controller
{
public ActionResult Index()
{
List<CarModel> objlistcar = new List<CarModel>();
            CarModel objcar = new CarModel();
            objcar.CarID = 1;
            objcar.CarColor = "Red";
            objcar.CarPrice = 20000;
            objcar.CarType = "Uday";
            objlistcar.Add(objcar);
            // add item in list
            CarModel objcar1 = new CarModel();
            objcar1.CarID = 2;
            objcar1.CarColor = "Blue";
            objcar1.CarPrice = 20000;
            objcar1.CarType = "Rajakonda Uday Kumar";

            objlistcar.Add(objcar1);  // add item in list
            objcar.Listcar = objlistcar; // assigning value to CarModel object
            return View(objcar); // Returning model
}
}
}

Creating Partial View

@model IEnumerable<WebApplication1.Models.CarModel>
<table style="background-colorrosybrownborder:dashed;">
<tr>
<td colspan="3"><h2>Child View</h2></td>
</tr>
<tr>
<th>
@Html.DisplayNameFor(model => model.CarID)
</th>
<th>
@Html.DisplayNameFor(model => model.CarType)
</th>
<th>
@Html.DisplayNameFor(model => model.CarPrice)
</th>
<th>
@Html.DisplayNameFor(model => model.CarColor)
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.CarID)
</td>
<td>
@Html.DisplayFor(modelItem => item.CarType)
</td>
<td>
@Html.DisplayFor(modelItem => item.CarPrice)
</td>
<td>
@Html.DisplayFor(modelItem => item.CarColor)
</td>
</tr>
}
</table>



Creating View for Rendering Partial view

Now we have to render partial view inside Index view. For rendering view we are going to use Html Helper class that will be like as shown below

@Html.Partial("Partial View Name" , "Model which is required")
Once we add partial view inside of view that will be like as shown below 


@model  WebApplication1.Models.CarModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>View</title>
</head>
<body>
    <div>
        @Html.Partial("View", Model.Listcar)
    </div>
</body>
</html>

Output:

Finally just run application and check output that will be like as shown below. The outer most view is Parent view and the view with Brown color is Partial view (Child view).


Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...