Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Monday

MVC Custom Error: How to implement custom error pages using MVC

Introduction

Custom Error pages can make your MVC application more elegant and informative. I often see many developers more struggles for hours to implement this functionality in ASP.Net MVC application. I’ll throw full light on all aspects how to implement MVC custom error pages. I have here demonstrated very common errors of MVC application as listed below:
  • Not Found: Whenever page is not founmd (MVC 404 Page).
  • Access Denied: Whenever we are trying to access folder (CAS Code Access Security) permissions or someone like same.
  • Internal Server Error: This error is related to internal server error. 
  • Error Occurred: If any other error occurred in our MVC application.
MVC custom error page
MVC custom error page
You may conquers this example very easily, if once you go through also this example because it is extended from the earlier example. If you are already regular reader of Technology Crowds then it is OK.
You may also track Exception code and refer to custom page error in your ASP.Net MVC application.
Namespace Used:

using System.Web.Routing;

Add below code into Global.asax

You are required to add below code into Global.asax page on Application_Error page in your MVC application to get working custom error page.
protected void Application_Error(object sender, EventArgs e)
{
    var httpContext = ((MvcApplication)sender).Context;
    var currentController = " ";
    var currentAction = " ";
    var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));

    if (currentRouteData != null)
    {
    if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
        {
            currentController = currentRouteData.Values["controller"].ToString();
        }

        if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
        {
            currentAction = currentRouteData.Values["action"].ToString();
        }
    }

    var ex = Server.GetLastError();
    var controller = new ErrorController();
    var routeData = new RouteData();
    var action = "Index";

    if (ex is HttpException)
    {
        var httpEx = ex as HttpException;

        switch (httpEx.GetHttpCode())
        {
            case 404:
                action = "NotFound";
                break;

            case 401:
                action = "AccessDenied";
                break;

            case 500:
                action = "InternalServerError";
                break;
        }
    }

    httpContext.ClearError();
    httpContext.Response.Clear();
    httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500;
    httpContext.Response.TrySkipIisCustomErrors = true;

    routeData.Values["controller"] = "Error";
    routeData.Values["action"] = action;

    controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction);
    ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
}

Error Controller Actions

Here are written controller actions list like Index, NotFound, AccessDenied, InternalServerError etc.
public class ErrorController : Controller
{
    ///     /// Track Common Page Error
    ///     /// 
    [HttpGet]
    public ActionResult Index()
    {
        TempData["error"] = "Error Occurred!";
    return View();
    }
    ///     /// Track Page Not Found Error
    /// 
    /// 
    [HttpGet]
    public ActionResult NotFound()
    {
        TempData["error"] = "Page not Found";
        return View();
    }
    /// 
    /// Track Access Denied
    ///     /// 
    [HttpGet]
    public ActionResult AccessDenied()
    {
        TempData["error"] = "Access Denied";
        return View("Index");
    }

    ///     /// Track Internal Server Error
    ///     /// 
    [HttpGet]
    public ActionResult InternalServerError()
    {
        TempData["error"] = "Internal Server Error";
        return View("Index");
    }
}

Custom Error Razor Views

Below is completely provided code snippet of Razor view engine to display custom error pages to end user. Razor views will remain same to all custom error pages like IndexNotFoundAccessDeniedInternalServerError etc.

@{
    ViewBag.Title = @TempData["error"];
    Layout = null;
}

Error:

@TempData["error"]

Error Description:

@Model.Exception.Message.ToString() @Html.Raw(" ") @Model.ControllerName @Html.Raw(" ") @Model.ActionName

MVC custom error pages

Conclusion

To standardise your ASP.net MVC application, we are all required to customise error pages and show on a particular page with detailed error to make more trustworthy your website in to your online audience. Here, I have lined up all aspects of how to implement custom error pages using MVC application with attached working sample project to setup on your machine to see how it happen in really.

Download Complete Project (visual studio source files)
Download

Saturday

MVC: Sorting Filter in AngularJS using MVC

Introduction

I am here fully explaining how to sorting filtering in AngularJS using MVC application. In my recent article, I have already demonstrated Live Character Count using AngularJS

Sorting Filter in AngularJS using MVC

Thursday

URL Access: How to Prevent Direct URL Access In MVC

Introduction

Here is writing another article to make more secure of your MVC application. I’ll explore all aspects here, how to prevent direct URL access in MVC application. Before to go through this article, you are required to detail about these articles as given below.
  1. Asp.net mvc session management example
  2. Prevent Cross-Site Request Forgery using AntiForgeryToken() in MVC

Namespace Used

To apply this feature into your MVC application is used System.Web.Routing namespace to prevent direct URL access in MVC.
How to Prevent Direct URL Access In MVC

using System.Web.Routing

Apply this feature in FilterConfig.cs file

We have to call this feature under OnActionExecuting of Action filter. We have to apply filter as below written lines to prevent direct URL access in MVC. If we are tempering URL in browser then it will forcibly throw you to Logout action of Home Controller lying under Main area.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class NoDirectAccessAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.UrlReferrer == null ||
 filterContext.HttpContext.Request.Url.Host != filterContext.HttpContext.Request.UrlReferrer.Host)
        {
     filterContext.Result = new RedirectToRouteResult(new
                               RouteValueDictionary(new { controller = "Home", action = "Logout", area = "Main" }));
        }
    }
}

Prevent Direct Access to Class (Apply on Controller Class)

We can apply NoDirectAccess Attribute to Class and it will follow to all containing methods, if any methods accessed directly under the whole controller. It will throw you specified action (here’s throwing Logout action) like MyWebsiteURL.com/Main/PersonalDetail/Index

[NoDirectAccess]
public class PersonalDetailController : Controller
{
      //
      // GET: /Main/PersonalDetail/
      public ActionResult Index()
      {
          return View();
      }
}

Apply NoDirectAccess Attribute to Action

Alternatively, we can apply NoDirectAccess Attribute to specific Action rather than to whole Controller class. Suppose, we are accessing directly like MyWebsiteURL.com/Main/Home/login

[NoDirectAccess]
public ActionResult Login()
{
   return View();
}

Conclusion

I have here demonstrated all necessary steps to prevent direct URL access in MVC to make our MVC application more secured and robust over internet. These are the healthy features to make our MVC application more reliable across the internet.

Tuesday

MVC Session: Asp.net mvc session management example

Introduction

In this example, showing how to use and validate session (HttpContext.Current.Session) in MVC application. In my earlier article, one of more secured feature to keep up your website healthy cross-site request forgery explained. MVC application has provided us facility to apply filter like
  1.  Authorization 
  2.  Action Filter 
  3.  Result Filter 
  4.  On Error Filter
I am here applying OnActionExecuting filter helps us to manage ASP.net MVC session management whether session is preserving or not, if session is expired, it will not let you access your authorised area and throw away to login area or someone page.
Asp.net mvc session management example

Add below code in FilterConfig.cs under App_Start folder

This code is written under OnActionExecuting in FilterConfig.cs file
public class UserSessionActionFilter : ActionFilterAttribute, IActionFilter
{
    public override void OnActionExecuting(ActionExecutingContext filterContextORG)
    {
        HttpContext ctx = HttpContext.Current;
        if (HttpContext.Current.Session["User"] == null)
        {
            /// this handles session when data is requested through Ajax json
            if (filterContextORG.HttpContext.Request.IsAjaxRequest())
            {
                JsonResult result = new JsonResult { Data = "Session Timeout!" };
                filterContextORG.Result = result;
            }
            else
            {
                /// If session is expired then redirected to logout page which further redirect to login page. 
            filterContextORG.Result = new RedirectResult("~/Main/Home/Logout");
                return;
            }
        }
}

In Global.asax Should register FilterConfig.cs

protected void Application_Start()
{
 AreaRegistration.RegisterAllAreas();
 WebApiConfig.Register(GlobalConfiguration.Configuration);
 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
 RouteConfig.RegisterRoutes(RouteTable.Routes);
}

Checking Session is expired or not

We have to call action attribute [UserSessionActionFilter] in MVC controller to check whether session is preserving or not. If session is expired it will throw to other page.
[UserSessionActionFilter]
public ActionResult ContactDetail()
{
 return View();
}

Conclusion

This example is showing how to handle session in ASP.net MVC application. This example helps us to asp.net MVC session management example with all required steps.

Suggested Reading

Thursday

MVC Areas: Organizing an Application using Areas

Introduction

MVC architecture is inherently separated into three separate layers like Model (database), Presentation (UI, View), and Controller (Business layer). Releasing of MVC 2 introduces new feature of Area which provide solid capability to further separate files of file structure. Using with Area, we can define same controller in different areas to make our application more modular, manageable and robust. In this demonstration, I have used two areas Main (Public website) and blog area. In my earlier article, how to stop cross-site request forgery. I am explaining all steps how to organizing an application using areas in MVC.
mvc area

Why We Need MVC Areas

When we need multiple departments to maintain with different controllers even having with the same name in different areas. It makes our application more manageable, easy and maintainable to make our development faster.

Create a New MVC Project

First of all, create a new fresh project of MVC

create new project mvc area

New Project Crated

New project created for playing MVC feature of Area.

new project created

Create a New Area

Let’s now start to create a new area. Right click on project then move to Add >>> Area then provide a new relevant name of area.
Create mvc area

Creating Blog Area

Here typing relevant new area name like “Blog”.
type blog area name

Blog Area Created

Now you can see new created area “Blog” under the project.
Area Blog Created

Blog Area File Registration

You can see a new file crated of Blog Area Registration (BlogAreaRegistration.cs) under blog area.

public override string AreaName
{
    get
    {
 return "Blog";
    }
}

public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute("Blog_default",
        "Blog/{controller}/{action}/{id}",
 new { action = "Index", id = UrlParameter.Optional }
    );
}

Area Registration in Global.asax

Area registration is also done in Global.asax file.
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
    AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
} 

Main Area Creation

Next one new main area is crating in this section.
Main blog area created
Area Registration File Created
In the same way, as in blog area a registration file (MainAreaRegistration.cs) is also created.

public class MainAreaRegistration : AreaRegistration
{
 public override string AreaName
        {
        get
        {
            return "Main";
        }
    }

public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Main_default",
            "Main/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }

Create Home Controller for Main Area

Creating home controller under main area.
Home controller for main area

Create Home Controller For Blog

Alike main area, Home controller is also creating under blog area. Area feature let allow us to create same controller name to make our development more lucrative.
Home controller for blog area

Create View for Both Home controllers of Main & Blog

Here is creating view for Blog and main area.

@{
ViewBag.Title = "Index";
}
<h2>Welcome to Blog Area</h2>
<div> @Html.ActionLink("Back to Main", "Index", "Home", new { area = "Main" }, new { }) </div>
 Main Area View
@{ ViewBag.Title = "Index"; }
<h2>Welcome to Main Area</h2>
<div>
    @Html.ActionLink("Go to Blog", "Index", "Home", new { area = "Blog" }, new { })
</div>

Set Default Area/Controller/Action

Here, you can set your default area, controller and method to launch your application (landing page of your application). Before to set, you need to right click on project and click on properties to navigate on Web tab to set application default page (Area/controller/action).

Area Default Page

or Alternatively can set in RouteConfig.cs

Routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                namespaces: new[] { "slnMvcArea.Areas.Main.Controllers" }
            ).DataTokens.Add("area","Main");

Now Run your MVC area application

Finally run your MVC app to see how works MVC area feature.

welcome to main area

Navigate to Blog Area

Click on “Go to Blog” to navigate blog area.

welcome to blog area
Now you are on blog area, here is also a link to navigate “Back to Main”.

Conclusion

MVC areas helps us to make more manageable our MVC application to further divides into different files. In each area, we can define same controller like Main area contain “Home” Controller then also other areas can contain same area name “Home”, this code will compile perfectly even we have same controller name in different areas. Thus, it will help us to make large volume of applications with multiple departments so that can build awesome MVC apps with area feature. I tried here to demonstrates all necessary steps to organize an application using areas in MVC app.

Video: This video also demonostrates about Organizing an Application using Areas.

Wednesday

How To Own ASP.Net MVC Page Life Cycle For Free

Introduction

Before to start over to know about MVC complete Life Cycle, it is mandatory to add required namespaces in web.config which are automatically added when we add MVC package in our MVC application. We all know the basic behaviour of MVC is based on HTTP requests. In my recent article, I have already explained how to create amazing charts using MVC.

I have provided all necessary MVC life cycle steps here.
<namespaces> 
<add namespace="System.Web.Helpers">
<add namespace="System.Web.Mvc">
<add namespace="System.Web.Mvc.Ajax">
<add namespace="System.Web.Mvc.Html">
<add namespace="System.Web.Optimization">
<add namespace="System.Web.Routing">
<add namespace="System.Web.WebPages">
</namespaces>

1) We send our request through HTTP to our server.
2) Then request goes through our MVC routing.
3) Our web request sends through Global.asax file where all routes are registered under this file, according to our MVC request then request is forwarded according to matching route.
ASP.Net MVC Page Life Cycle

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    AuthConfig.RegisterAuth();
    //ModelBinders.Binders.DefaultBinder = new Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder();
    AreaRegistration.RegisterAllAreas();
}
4) Route is filled in Route.Config file where our controller, view and parameter (optional) are given to complete our request.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
    name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}
5) After filling the route through Route.config, now request is redirected to our controller.

  public ActionResult Index()
  {
   return View();
  }
6) At the end, Result is shown in a view of MVC controller attribute where all desired information is displayed over here.

@{ ViewBag.Title = "Home"; } 
<!DOCTYPE html> 
<html lang="en"> 
<head> <meta charset="utf-8" /> 
<title>@ViewBag.Title</title> 
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" /> 
<meta name="viewport" content="width=device-width" /> 
</head>
 <body> <div> Welcome to Technology Crowds </div> </body> 
</html>

Conclusion

In this article has shown how works MVC life cycle when we request through HTTP in our web browser. Requests, Routing, controller, view, MVC handler (Razor etc) are key components of MVC.

Suggested Reading

Saturday

CSRF: Prevent Cross-Site Request Forgery using AntiForgeryToken() in MVC

Introduction

At whatever point we chip away at our application we constrained to our undertaking extension and its business rationales to accomplish our task time conveyance. We couldn't concentrate such a great amount to our security reasons and later after sending of our venture is hacked through cross-site demand imitation. .Net Framework has introduced a new security feature to protect our MVC projects data using anti forgery token whenever we submit data through our MVC application data. Cross-site scripting (XSS) is most dangerous issue on web (internet application). I have already explained a MVC very known error Unexpected if keyword after @ character.
Prevent Cross-Site Request Forgery using AntiForgeryToken() in MVC

MVC Charts: How to create charts using MVC

Introduction

Already explained how to send SMS using C# in my previous article, here explaining about MVC Charts. Chart Helper is an outstanding option to show your data in graphical representation. The Chart Helper shows data in image in different chart types like Funnel, Bar Chart, Pie, Column, Candlestick, Doughnut, StackedBar100, BoxPlot, Pyramid, Polar, Radar, RangeBar etc. Chart Helper can show more than 30 chart types in MVC C#. Here, I are explaining main properties of Charts like Height, Weight, Title, Series and then finally write charts into output bmp file. In this sample, I will show how to create charts using MVC.

Database Script

CREATE TABLE [dbo].[tblMVCCharts](
 [ChartID] [int] IDENTITY(1,1) NOT NULL,
 [Growth_Year] [int] NULL,
 [Growth_Value] [float] NULL
) ON [PRIMARY]


insert into [dbo].[tblMVCCharts] (Growth_Year, Growth_Value) values (2008,50)
insert into [dbo].[tblMVCCharts] (Growth_Year, Growth_Value) values (2009,70)
insert into [dbo].[tblMVCCharts] (Growth_Year, Growth_Value) values (2010,80)
insert into [dbo].[tblMVCCharts] (Growth_Year, Growth_Value) values (2011,90)
insert into [dbo].[tblMVCCharts] (Growth_Year, Growth_Value) values (2012,120)
insert into [dbo].[tblMVCCharts] (Growth_Year, Growth_Value) values (2013,150)
insert into [dbo].[tblMVCCharts] (Growth_Year, Growth_Value) values (2014,100)
insert into [dbo].[tblMVCCharts] (Growth_Year, Growth_Value) values (2015,300)

Namespace

using System.Web.Helpers;

Height-Weight

We can increase-decrease chart height and weight as per your customisation requirements

Title

Here we can put title of the chart.

Series

In series property, Series is very required property to provide data (X & Y series) to generate into graphical form. We need to provide data for X (Horizontal) and Y (Vertical) series to show data in graphical representation, that is what we need to extract from our data into chart in MVC.

Write

Write properties is finally convert our data into image form to output in to BMP file.
Every chart necessarily requires values for x and y for similar collection of information. Here are showing growth overs years values for X and Y.

Controller Action Column Chart

public ActionResult CharterColumn()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Vanilla3D)
    .AddTitle("Chart for Growth [Column Chart]")
   .AddSeries("Default", chartType: "column", xValue: xValue, yValues: yValue)
          .Write("bmp");

    return null;
}

Razor View Column Chart

<img src="@Url.Action("CharterColumn")" alt="Chart" />

Column Chart Output

Column Chart

Controller Action Bar Chart

public ActionResult ChartBar()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Vanilla3D)
    .AddTitle("Chart for Growth [Bar Chart]")
            .AddSeries("Default", chartType: "Bar", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View Bar Chart

<img src="@Url.Action("ChartBar")" alt="Chart" />

Bar Chart Output

Bar Chart

Controller Action Pie Chart

public ActionResult ChartPie()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Vanilla3D)
    .AddTitle("Chart for Growth [Pie Chart]")
            .AddLegend("Summary")
            .AddSeries("Default", chartType: "Pie", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View Pie Chart

<img src="@Url.Action("ChartPie")" alt="Chart" />

Pie Chart Output

Pie Chart

Controller Action Three Line Break Chart

public ActionResult ChartThreelinebreak()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    /// SeriesChartType.Candlestick
    new Chart(width: 600, height: 400, theme: ChartTheme.Vanilla3D)
    .AddTitle("Chart for Growth [Three Line Break Chart]")
            .AddSeries("Default", chartType: "Candlestick", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View Three Line Break Chart

<img src="@Url.Action("ChartThreelinebreak")" alt="Chart" />

Three Line Break Chart Output

Three Line Break Chart

Controller Action Bubble Chart

public ActionResult Bubblebreak()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Green)

    /// SeriesChartType.Bubble
    .AddTitle("Chart for Growth [Bubble Chart]")
            .AddLegend("Summary")
            .AddSeries("Default", chartType: "Bubble", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View Bubble Chart

<img src="@Url.Action("Bubblebreak")" alt="Chart" />

Bubble Chart Output

Bubble Chart

Controller Action Doughnut Chart

public ActionResult DoughnutGraph()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Green)

    /// SeriesChartType.Doughnut
    .AddTitle("Chart for Growth [Doughnut Chart]")
            .AddLegend("Summary")
            .AddSeries("Default", chartType: "Doughnut", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View Doughnut Chart

<img src="@Url.Action("DoughnutGraph")" alt="Chart" />

Doughnut Chart Output

Doughnut Chart

Controller Action StackedBar100 Chart

public ActionResult ChartStackedBar100()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Green)

    /// SeriesChartType.StackedBar100
    .AddTitle("Chart for Growth [StackedBar100 Chart]")
            .AddSeries("Default", chartType: "StackedBar100", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View StackedBar100 Chart

<img src="@Url.Action("ChartStackedBar100")" alt="Chart" />

StackedBar100 Chart Output

StackedBar100 Chart

Controller Action BoxPlot Chart


public ActionResult ChartBoxPlot()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Green)

    /// SeriesChartType.BoxPlot
    .AddTitle("Chart for Growth [BoxPlot Chart]")
            .AddSeries("Default", chartType: "BoxPlot", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View BoxPlot Chart

<img src="@Url.Action("ChartBoxPlot")" alt="Chart" />

BoxPlot Chart Output

BoxPlot Chart

Controller Action Pyramid Chart


public ActionResult ChartPyramid()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Green)

    /// SeriesChartType.Pyramid
    .AddTitle("Chart for Growth [Pyramid Chart]")
            .AddLegend("Summary")
            .AddSeries("Default", chartType: "Pyramid", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View Polar Chart

<img src="@Url.Action("ChartPyramid")" alt="Chart" />

Pyramid Chart Output

ChartPyramid

Controller Action Polar Chart

public ActionResult ChartPolar()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Green)

    /// SeriesChartType.Polar
    .AddTitle("Chart for Growth [Polar Chart]")
            .AddSeries("Default", chartType: "Polar", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View Polar Chart

 <img src="@Url.Action("ChartPolar")" alt="Chart" />

Radar Chart Output

Polar Chart

Controller Action Radar Chart

public ActionResult RadarChart()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Green)

    /// SeriesChartType.Radar
    .AddTitle("Chart for Growth [Radar Chart]")
            .AddSeries("Default", chartType: "Radar", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View Radar Chart

<img src="@Url.Action("RadarChart")" alt="Chart" />

Radar Chart Output

Radar Chart

Controller Action RangeBar Chart

public ActionResult ChartRangeBar()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Green)
            
    /// SeriesChartType.RangeBar
    .AddTitle("Chart for Growth [RangeBar Chart]")
            .AddSeries("Default", chartType: "RangeBar", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View RangeBar Chart

<img src="@Url.Action("ChartRangeBar")" alt="Chart" />

RangeBar Chart Output

RangeBar Chart

Controller Action Funnel Chart

public ActionResult ChartFunnel()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Green)

    /// SeriesChartType.Funnel
    .AddTitle("Chart for Growth [Funnel Chart]")
    .AddLegend("Summary")
            .AddSeries("Default", chartType: "Funnel", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View Funnel Chart

<img alt="Chart" chartfunnel="" src="@Url.Action("ChartFunnel") />

Funnel Chart Output

Funnel Chart

Conclusion

Charts help us to represent data into graphical form from tabular data. MVC charts have been provided facility to represent data into different charts. We can analyse data minutely with the help of MVC charts to take up comparative decisions. Hopefully, above all charts will help everyone to represent data in to many ways in your web app. I tried here how to create charts using MVC with detailed example and also attached a working sample with database.

Download Working Sample

Download
Note: Change Connection String in web.config before to run this working sample of MVC Charts.

Video: How to create charts using MVC

Suggested Reading

SMS API: How to send SMS using C#

Introduction

SMS stands for Short Message Service is widely used to communicate to another mobile devices. Earlier, provided resolution to resolve issue Authentication the Server Response was 5.5.1 Authentication required in gmail, now today explaining how to send SMS using C#. We can send SMS up to 160 characters through our mobile devices. Long message can split up into small multiple parts automatically. On mobile device can send text message only. Here, I am exposing how to send text SMS (Short Message Service) using c# code.
  1. First of all. We need to create an URL to send text message on mobile device.
  2. We require web or IP address with parameters like username, password, recipient, senderid, text message and response etc.
  3. Parameters can vary depend on SMS provider service. Providers provide complete information to send SMS.
  4. Now we need to create web request to send SMS using C# code.
  5. We can also track response after sending text message on mobile device.
SMS API
Fig: SMS API

Code Snippet


public ActionResult SendSMSInCsharp()
{
    //we creating the necessary URL string:
    string _URL = "192.168.1"; //where the SMS Gateway is running
    string _senderid = "TESTTC";   // here assigning sender id 
            
    string _user = HttpUtility.UrlEncode("TestSMS"); // API user name to send SMS
    string _pass = HttpUtility.UrlEncode("123456");     // API password to send SMS
    string _recipient = HttpUtility.UrlEncode("9999999999");  // who will receive message
    string _messageText = HttpUtility.UrlEncode("testing sms..."); // text message

    // Creating URL to send sms
    string _createURL = _URL + 
    "username =" + _user +
       "&pass=" + _pass +
       "&senderid=" + _senderid +
       "&dest_mobileno=" + _recipient +
       "&message=" + _messageText;

    try
    {
        // creating web request to send sms 
        HttpWebRequest _createRequest = (HttpWebRequest)WebRequest.Create(_createURL);
        // getting response of sms
        HttpWebResponse myResp = (HttpWebResponse)_createRequest.GetResponse();
        System.IO.StreamReader _responseStreamReader = new System.IO.StreamReader(myResp.GetResponseStream());
        string responseString = _responseStreamReader.ReadToEnd();
        _responseStreamReader.Close();
        myResp.Close();
    }
    catch
    {
        //
    }
    return View();
}

Conclusion

SMS (Short Message Service) is now used across the world through mobile devices to instant communication medium. In this article, demonstrated explained all steps to send SMS using C# code. You can send SMS through this code in ASP.Net, MVC using C# code.

Suggested Reading

Jquery Magnifier: How to develop image magnifier using mvc

Introduction

Jquery Image Magnifier is widely used in our web/Mobile app to view product images in all angles. Jquery Image Magnifier is used often in eCommerce website where end use can view minutely product image before to place order online. Here, Jquery magnifier is using in ASP.Net MVC App.

Include Two Style sheets files

CSS files are very important to enable Jquery magnifier using MVC application (Need to add stylesheet (demo.css, jQuery.MagnifierRentgen.min.css)).


Include Three JS File to Client Side Magnifier Effect

Here adding three java script file reference (online Jquery reference (jquery-1.11.3.min.js) & other two offline (jQuery.MagnifierRentgen.min.js, demo.js))
    
    
    

Razor View (CSHTML Page)

Razor View (CSHTML Page)
@{
    ViewBag.Title = "Magnifier";

    
    
}


    

JQuery Magnifier

_Layout Razor View (App Layout default settings)

Here showing Layout Master Razor view code


    
    
    @ViewBag.Title
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")


    @RenderBody()

    @RenderSection("scripts", required: false)


Image Magnifier Output View First

Image Magnifier using MVC

Image Magnifier Output View Second

Image Magnifier using MVC

Conclusion

Jquery Image Magnifier can trust and motivated to buy product online through eCommerce website (marketplace). In this article, I have explained all steps to how can we zoom in, zoom out the image to give a very close look of the product image. This is very brilliant feature (Jquery Magnifier) in our eCommerce website.

Download Example

Download

Relevant Reading

Monday

Fix Error: Could not load file or assembly 'Antlr3.Runtime (1)' or one of its dependencies

Introduction

Today, I am going to explain a MVC application error while our application is interrupted or closed properly. This might be arise a major issue in our build causes delay to deploy our MVC app.

Error Description

Could not load file or assembly 'Antlr3.Runtime (1)' or one of its dependencies

Reasons

This issue comes when our power failure and resulted into our application is not closed down properly.
Could not load file or assembly 'Antlr3.Runtime (1)' or one of its dependencies

Figure: Could not load file or assembly

Step 1

Press Windows + Run and then type %temp%

Step 2

Now delete all temporaries files located at your machine C:\Users\user1\AppData\Local\Temp,

Using with above 2 steps helped me to resolve issue Could not load file or assembly 'Antlr3.Runtime (1)' or one of its dependencies while working on MVC application.

Conclusion

I have explained MVC error Could not load file or assembly 'Antlr3.Runtime (1)' or one of its dependencies, how it comes, reasons behind it and provided all necessary steps to resolve issue Could not load file or assembly 'Antlr3.Runtime (1)' or one of its dependencies. Relevant MVC Fixes

Suggested Reading

Saturday

MVC Razor View: Unexpected if keyword after @ character in MVC Razor View

Introduction

I am going to explain a very popular error i.e Unexpected "if" keyword after "@" character while working with ASP.Net MVC Razor View, I am sharing all aspects of this error Unexpected "if" keyword after "@" character.

Error Detail:

Unexpected "if" keyword after "@" character.  Once inside code, you do not need to prefix constructs like "if" with "@".
When Error "Unexpected "if" keyword after "@" character" comes off
Working on MVC project and working on MVC Razor view, meanwhile a problem faced me whenever using foreach statement in MVC Razor View Engine. I was using nested statement to write some logic. I have been shared my both preview of code 1) Wrong statement and 2) corrected statement which is showing below.

Unexpected if keyword after character in MVC Razor View

Wrong Statement

@foreach (var item in Model)
{
    @if (item.isCorrect)
    {
           // do something
    }
}

Correct Statement

@foreach (var item in Model)
{
    if (item.isCorrect)
    {
           // do something
    }
}

Conclusion 

Explained above, how can we use nested loop in Razor view, in this article, fully explained how can we remove issue of nested loop Unexpected if keyword after @ character.

Suggested Reading

Friday

Jquery MVC: Upload Image using jquery MVC

Introduction

Image Upload is very important work in our web application. It is most orderly needed whereas registering profile somebody with profile image, making album etc. I have explained during this article, how to upload image in MVC application (Razor Engine) using Jquery and preview image instantly. Image Uploading is gorgeous task of your application whenever search somebody image, if profile image is blur or heavy image then it'll increase your process time, blur image will lead to dangerous impact in visitor's mind means that cut traffic towards website or user profile. I have bring up a dashing working example.

Saturday

MVC ModelState: ModelState Return always false using MVC

Introduction

I am today explaining one more very nasty error about ModelState Error. We daily work on MVC Apps using Model, sometime we get ModelState returning always false at that time, it is more required to diagnose our errors in shot period and take immediately action to remove our ModelState errors.

Tuesday

MVC Caching: How to Disable Automatic Caching in ASP.Net MVC

Introduction

Today, I am explaining very important part of MVC application, just explaining about how to disable automatic caching in ASP.Net MVC application. It is very important in our MVC app while we don't allow end user to navigate browser cache (next, previous button etc.). MVC has provided feature to disable caching in ASP.Net MVC application.

Sunday

Count Down Timer: Jquery Timer Countdown in MVC Application

Introduction

Timer countdown is very important in our web apps while we are restricting to end user within specified time frame for example apps online Quiz, online survey etc. Here, in this article I am explain in full depth, how to implement Jquery/JavaScript timer count down in our web apps.

Step 1:First of all add following time to start count down while open our MVC web app, here I am adding 2 minutes of time count down.

public ActionResult Index()
{
  if (Session["Rem_Time"] == null)
  {
     Session["Rem_Time"] = DateTime.Now.AddMinutes(2).ToString("dd-MM-yyyy h:mm:ss tt");
   }
   ViewBag.Rem_Time = Session["Rem_Time"];

   ViewBag.Message = "Modify this template to jump-start your MVC application.";
   return View();
}
Step 2: Add following div in Index page of our MVC apps _layout.cshtml page.

id timecountdown

Step 3: Add following script in our MVC web app which will display time (hour, minutes, secs).

Interval Time Count Down

Populating JavaScript Timer Count Down in MVC Web Application

Finally, you can see how populating JavaScript Timer Count Down in MVC Web Application. I hope it will help you all. 
MVC Timer Count Down

Conclusion

I have explained fully with step to step, how we can implement Jquery timer count down in our MVC web apps. If any queries then let me know, I am very happy to reply all of your queries.

Download Complete Project

Download

Suggested Reading

Thursday

Dropdown List: Cascading Dropdown list in MVC

Introduction

Today, I am explaining about cascading drop down list in MVC, while we are working on CRM, ERP, Web Apps or other web apps then we often require to populate cascading dropdown list e.g. First populate Country then select country from list then corresponding state will be populated in other dropdown. This is the way that how we need cascading dropdown list in our MVC applications. Here I am taking example, first populating drop down list of classes, on the click of classes, the other drop down list will be populated of Subjects and then while we click on Subjects then chapter will be populated correspondingly.

Add Entity Framework Model in MVC Project

First of all, you have to add entities in our project to populate cascading drop down in our project. I am providing a video link (Add Entities) which explains all steps how to add entities in our project using entity framework.

namespace MvcApplication1.Context
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    
    public partial class MVC_AppEntities1 : DbContext
    {
        public MVC_AppEntities1()
            : base("name=MVC_AppEntities1")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public virtual DbSet tblChapterMasters { get; set; }
        public virtual DbSet tblClassMasters { get; set; }
        public virtual DbSet tblSubjectMasters { get; set; }
    }
}

Populate First Dropdown List (Subjects)

Here I have written an action method in controller as below:
[HttpGet]
public ActionResult My_MVC_App(string ddlClasses, string ddlSubjects, string ddlChapters)
{
    var _context = new MVC_AppEntities1();
    List _classlst = GetClasses();

   // Clases
   List li = new List();
   foreach (var item in _classlst)
   {
   li.Add(new SelectListItem { Text = item.ClassName, Value = item.ClassIDPK.ToString() });
   }
   ViewData["Classes"] = li;

   return View();
}

Populate Second Dropdown List (Subjects)

Next step is to write action method to populate second dropdown list of subject while we click on classes drop down list.
[HttpGet]
public JsonResult GetSubjectsNew(Int16 ClassID)
{
    List _lstSubjects = GetSubjectsID(ClassID);
    List _liSubj = new List();
    /// 
    var _context = new MVC_AppEntities1();
foreach (var _itemsubject in _lstSubjects)
{
  _liSubj.Add(new SelectListItem { Text = _itemsubject.SubjectName, Value = _itemsubject.SubjectIDPK.ToString() });
}

return Json(new SelectList(_liSubj, "Value", "Text"), JsonRequestBehavior.AllowGet);
  

Populate Third Dropdown List (Chapter)

Now next step is to populate third dropdown list of chapters while we click on subjects correspondingly.

 [HttpGet]
 public JsonResult GetChapterList(Int16 SubjectID, Int32? ChapterID)
{
   List _lstChapters = GetChapters(SubjectID);
   List _liSubj = new List();

   foreach (var _itemsubject in _lstChapters)
   {
     _liSubj.Add(new SelectListItem { Text = _itemsubject.ChapterName, Value = _itemsubject.ChapterIDPK.ToString() });
   }
   return Json(new SelectList(_liSubj, "Value", "Text"), JsonRequestBehavior.AllowGet);
}

Helping Method to Populate All Dropdowns (Classes, Subjects, Chapters)

Helping Methods

I have explained below three helping methods to populate all drop downs correspondingly.

MVC Razor View
Now I am talking about MVC razor view where we are playing with all three drop downs interface.

Import Jquery Library in our Project (Under Head Tag)


Head Tag

MVC Razor HTML Helpers

Below is written code to provide complete interface to populate three dropdowns.

razor view

Jquery Ajax call to MVC Controller

Here is written a Ajax/Jquery method to call Controller action for for subjects

Class Jquery Ajax Call

Here is written other Ajax/Jquery method to call Controller action for the chapters as below:

Chapter Jquery Ajax Call

Conclusion

Explained above about cascading dropdown in MVC with concerned every aspect of the MVC apps. Cascading dropdown is the common requirement of our each MVC applications, if we skip few steps to cascading drop down then sometimes it waste our very precious time of development.

Development Environment

Visual Studio 2013, Entity Framework 6.0, Database script under app folder App_Data, Change web.config settings according to your machine specific, Data source, Initial Catalog, Database User ID, Password etc.

Download Complete Project

Download

Relevant Reading