European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Charts In ASP.NET MVC Using Chart.js

clock August 10, 2018 11:36 by author Peter

This article demonstrates how to create charts in ASP.NET MVC using Chart.js and C#. This article starts with how to use Chart.js in your MVC project. After that, it demonstrates how to add charts to a View.

Using Chart.js in your ASP.NET MVC project (C#)

Chart.js is a JavaScript charting tool for web developers. The latest version can be downloaded from GitHub or can use CDN.

In this article, Chart.js CDN (v2.6.0) is used for demonstration purposes.
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js" type="text/javascript"></script> 

In the View (*.cshtml), add the Chart.js CDN along with jQuery CDN (recommended) in the head section if you haven’t mentioned those in layout pages.
@section head 

    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js" type="text/javascript"></script> 
    <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> 


Adding chart to a View
In the following example, the <canvas> tag is used to hold the chart in View’s <body> section.
<div Style="font-family: Corbel; font-size: small ;text-align:center " class="row"> 
    <div  style="width:100%;height:100%"> 
            <canvas id="myChart" style="padding: 0;margin: auto;display: block; "> </canvas> 
    </div> 
</div> 

Now, in the Controller class, let’s add a method to return the data for the chart that we added in the View. In this example, we are using JSON format for the source data.
[HttpPost] 
public JsonResult NewChart() 

    List<object> iData = new List<object>(); 
    //Creating sample data 
    DataTable dt = new DataTable() ; 
    dt.Columns.Add("Employee",System.Type.GetType("System.String")); 
    dt.Columns.Add("Credit",System.Type.GetType("System.Int32")); 
 
    DataRow dr = dt.NewRow(); 
    dr["Employee"] = "Sam"; 
    dr["Credit"] = 123; 
    dt.Rows.Add(dr); 
 
    dr = dt.NewRow(); 
    dr["Employee"] = "Alex"; 
    dr["Credit"] = 456; 
    dt.Rows.Add(dr); 
 
    dr = dt.NewRow(); 
    dr["Employee"] = "Michael"; 
    dr["Credit"] = 587; 
    dt.Rows.Add(dr); 
    //Looping and extracting each DataColumn to List<Object> 
    foreach (DataColumn dc in dt.Columns) 
    { 
        List<object> x = new List<object>(); 
        x = (from DataRow drr in dt.Rows select drr[dc.ColumnName]).ToList(); 
        iData.Add(x); 
    } 
    //Source data returned as JSON 
    return Json(iData, JsonRequestBehavior.AllowGet); 


The data from the source table is processed in such a way that each column in the result table is made to separate list. The first column is expected to have the X-axis data of the chart, whereas the consequent columns hold the data for Y-axis. (Chart.js expects the Axis labels in separate list. Please check the AJAX call section.)

The data for axises is combined to a single List<Object>, and returned from the method as JSON.

AJAX calls are used in the <script> section of View to call the method in Controller to get the chart data.
<script> 
    $.ajax({ 
        type: "POST", 
        url: "/Chart/NewChart", 
        contentType: "application/json; charset=utf-8", 
        dataType: "json", 
        success: function (chData) { 
        var aData = chData; 
        var aLabels = aData[0]; 
        var aDatasets1 = aData[1]; 
        var dataT = { 
            labels: aLabels, 
            datasets: [{ 
                label: "Test Data", 
                data: aDatasets1, 
                fill: false, 
                backgroundColor: ["rgba(54, 162, 235, 0.2)", "rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(201, 203, 207, 0.2)"], 
                borderColor: ["rgb(54, 162, 235)", "rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(153, 102, 255)", "rgb(201, 203, 207)"], 
                borderWidth: 1 
                }] 
            }; 
        var ctx = $("#myChart").get(0).getContext("2d"); 
        var myNewChart = new Chart(ctx, { 
            type: 'bar', 
            data: dataT, 
            options: { 
                responsive: true, 
                title: { display: true, text: 'CHART.JS DEMO CHART' }, 
                legend: { position: 'bottom' }, 
                scales: { 
                xAxes: [{ gridLines: { display: false }, display: true, scaleLabel: { display: false, labelString: '' } }], 
                yAxes: [{ gridLines: { display: false }, display: true, scaleLabel: { display: false, labelString: '' }, ticks: { stepSize: 50, beginAtZero: true } }] 
            }, 
        } 
        }); 
    } 
}); 
</script> 


aData[0] has the data for X-Axis labels and aData[1] has the data for Y-Axis correspondingly.

As in the code, the AJAX call is made to the Controller method ’/Chart/NewChart’ where ‘Chart’ is the name of the Controller class and ‘NewChart’ is the method which returns the source data for the chart in JSON format.

AJAX call, when returned successfully, processes the returned JSON data.
The JSON data is processed to extract the labels and axis data for the chart preparation. The 2D context of the canvas ‘myChart’ is created using ‘getContext("2d")’ method, and then the context is used to create the chart object in ‘new Chart()’ method inside the script.

 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: ASP.NET Core 2.0 MVC View Components

clock August 7, 2018 09:51 by author Peter

How to reuse parts of web pages using View Components in ASP.NET Core MVC.

Solution
In an empty project, update Startup class to add services and middleware for MVC.
public void ConfigureServices( 
IServiceCollection services) 

services.AddScoped<IAddressFormatter, AddressFormatter>(); 
services.AddMvc(); 


public void Configure( 
IApplicationBuilder app, 
IHostingEnvironment env) 

app.UseMvc(routes => 

routes.MapRoute( 
    name: "default", 
    template: "{controller=Home}/{action=Index}/{id?}"); 
}); 


Add a Model to display in the View.
public class EmployeeViewModel 

public int Id { get; set; } 
public string Firstname { get; set; } 
public string Surname { get; set; } 


Add a Controller with action method returning ViewResult.
public IActionResult Index() 

var model = new EmployeeViewModel 

   Id = 1, 
   Firstname = "James", 
   Surname = "Bond" 
}; 
return View(model); 


Add a parent View named Index.cshtml.
@using Fiver.Mvc.ViewComponents.Models.Home 
@model EmployeeViewModel 

<div style="border: 1px solid black; margin: 5px"> 
<strong>Employee Details (view)</strong> 

<p>Id: @Model.Id</p> 
<p>Firstname: @Model.Firstname</p> 
<p>Surname: @Model.Surname</p> 

@await Component.InvokeAsync("Address", new { employeeId = Model.Id }) 
</div> 

@await Component.InvokeAsync("UserInfo") 

Add a View Component’s Model.

public class AddressViewModel 

public int EmployeeId { get; set; } 
public string Line1 { get; set; } 
public string Line2 { get; set; } 
public string Line3 { get; set; } 
public string FormattedValue { get; set; } 


Add a View Component’s class.
[ViewComponent(Name = "Address")] 
public class AddressComponent : ViewComponent 

private readonly IAddressFormatter formatter; 

public AddressComponent(IAddressFormatter formatter) 

  this.formatter = formatter; 


public async Task InvokeAsync(int employeeId) 

  var model = new AddressViewModel 
  { 
      EmployeeId = employeeId, 
      Line1 = "Secret Location", 
      Line2 = "London", 
      Line3 = "UK" 
  }; 
  model.FormattedValue =  
      this.formatter.Format(model.Line1, model.Line2, model.Line3); 
  return View(model); 



Add a View Component’s View named as Default.cshtml.
@using Fiver.Mvc.ViewComponents.Models.Home 
@model AddressViewModel 

<div style="border: 1px dashed red; margin: 5px"> 
<strong>Address Details (view component in Views/Home)</strong> 

<p>Employee: @Model.EmployeeId</p> 
<p>Line1: @Model.Line1</p> 
<p>Line2: @Model.Line2</p> 
<p>Line3: @Model.Line3</p> 
<p>Full Address: @Model.FormattedValue</p> 
</div>

Discussion
View Components are special type of Views rendered inside other Views. They are useful for reusing parts of a View or splitting a large View into smaller components. Unlike Partial Views, View Components do not rely on Controllers. They have their own class to implement the logic to build component’s model and Razor View page to display HTML/CSS.

I like to think of them as mini-controllers, although this is not strictly correct but helps conceptualize their usage. Unlike Controllers, they do not handle HTTP requests or have Controller lifecycle, which means they can’t rely on filters or model binding.

View Components can utilize dependency injection, which makes them powerful and testable.

Creating
There are a few ways to create View Components. I’ll discuss the most commonly used (and best in my view) option.
1. Create a class (anywhere in your project) and inherit from ViewComponent abstract class.

  • Name of the class, by convention, ends with ViewComponent.

2. Create a method called InvokedAsync() that returns Task<IViewComponentResult>.

  • This method can take any number of parameters, which will be passed when invoking the component (see Invoking section below).

3. Create Model e.g. via database etc.
4. Call IViewComponentResult by calling the View() method of base ViewComponent. You could pass your model to this method.

  • Optionally you could specify the name of razor page (see Discovery section below).

The base ViewComponent class gives access to useful details (via properties) like HttpContext, RouteData, IUrlHelper, IPrincipal, and ViewData.

Invoking
View Components can be invoked by either,

  1. Calling @await Component.InvokeAsync(component, parameters) from the razor view.
  2. Returning ViewComponent(component, parameters) from a controller.

Here, “component” is a string value refereeing to the component class.
InvokeAsync() method can take any number of parameters and is passed using an anonymous object when invoking the View Component.

Below is an example of second option above. Notice that the second action method doesn’t work because the Razor page for the component is not under Controller’s Views folder,
public class ComponentsController : Controller 

public IActionResult UserInfo() 

 // works: this component's view is in Views/Shared 
 return ViewComponent("UserInfo"); 


public IActionResult Address() 

 // doesn't works: this component's view is NOT in Views/ 
 return ViewComponent("Address", new { employeeId = 5 }); 

}

Discovery
MVC will search for the razor page for View Component in the following sequence,
Views/[controller]/Components/[component]/[view].cshtml
Views/Shared/Components/[component]/[view].cshtml

Here matches either,
Name of the component class, minus the ViewComponent suffix if used.
Value specified in [ViewComponent] attribute applied to component class.

Also, [view] by default is Default.cshtml, however, it can be overwritten by returning a different name from the component class. Below the component returns a view named Info.cshtml,
public class UserInfoViewComponent : ViewComponent 

public async Task InvokeAsync() 

 var model = new UserInfoViewModel 
 { 
     Username = "[email protected]", 
     LastLogin = DateTime.Now.ToString() 
 }; 
 return View("info", model); 

}


jQuery
You could access View Components via jQuery as well. To do so enable the use of Static Files in Startup,
public void Configure( 
IApplicationBuilder app, 
IHostingEnvironment env) 

app.UseStaticFiles(); 
app.UseMvc(routes => 

  routes.MapRoute( 
      name: "default", 
      template: "{controller=Home}/{action=Index}/{id?}"); 
}); 


Add jQuery script file to wwwroot and use it in a page
<html> 
<head> 
<meta name="viewport" content="width=device-width" /> 
<title>ASP.NET Core View Components</title> 

<script src="~/js/jquery.min.js"></script> 

</head> 
<body> 
<div> 
<strong>ASP.NET Core View Components</strong> 

<input type="button" id="GetViewComponent" value="Get View Component" /> 

<div id="result"></div> 
</div> 
<script> 
$(function () { 
    $("#GetViewComponent").click(function () { 

        $.ajax({ 
            method: 'GET', 
            url: '@Url.Action("UserInfo", "Components")' 
        }).done(function (data, statusText, xhdr) { 
            $("#result").html(data); 
        }).fail(function (xhdr, statusText, errorText) { 
            $("#result").text(JSON.stringify(xhdr)); 
        }); 

    }); 
}); 
</script> 
</body> 
</html>



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Check Your ASP.NET MVC Version Installed In Your System Using Code During Runtime

clock August 3, 2018 11:17 by author Peter

Create an Application named MVC version

Look at an example for better reference i.e. RouteConfig.cs

Create A Controller named “Home” .

Add the code given below in HomeController.cs for better results, as expected.using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
namespace Mvc_Version.Controllers { 
    public class HomeController: Controller { 
        // 
        // GET: /Home/ 
        public string Version() { 
            return "<h2>The Installed Mvc Version In your System Is : " + typeof(Controller).Assembly.GetName().Version.ToString() + "</h2>"; 
        } 
    } 
}   

We mentioned the controller action method version In HomeController.Cs

For this, we should change the action method name in RouteConfig.cs for better loading of the page. For the first time, we will make it a start page.

Add the highlighted code in your file of RouteConfig.Cs. 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using System.Web.Routing; 
namespace Mvc_Version { 
    public class RouteConfig { 
        public static void RegisterRoutes(RouteCollection routes) { 
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
            routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new { 
                controller = "Home", action = "Version", id = UrlParameter.Optional 
            }); 
        } 
    } 
}  

Output

The expected output is shown below.

http://localhost:49952/Home/Version

Home - Controller name
Version - Controller action method



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Understanding Produces And Consumes Attribute In MVC 6

clock July 31, 2018 11:41 by author Peter

Produces and Consumes Attributes are newly introduced in MVC 6 (ASP.NET Core) to control the content negotiation.

What is Content Negotiation?
The process of picking the correct output format is known as Content Negotiation. Generally, Frameworks will accept two types of input/output formats those are JSON and XML. Nowadays, every framework by default accepts and returns in JSON format because of its advantages. If the user wants to control this default behavior, he should send an Accept Header with an appropriate format in GET or POST request from a client such that Framework will make sure to use the given format.

If a user doesn’t provide any Accept-Header, then the framework will decide which format it should use based on its settings. Some of the most popular browsers such as Chrome and Firefox will by default add Accept Header as application/xml and that is the reason when we call the web API from the browser will display the output in XML format if we don’t explicitly set the output format as JSON. Below are the sample requests generated from Chrome and IE where can observe the Accept Headers for these two browsers.

Chrome
GET / HTTP/1.1
Host: localhost:8080
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

IE
GET / HTTP/1.1
Accept: text/html, application/xhtml+xml, */*


If you want to see the output in JSON format, it's preferred to use any tools like fiddler, browser dev tools etc.
To control this and let the user be given full control of how to receive and sent the data format, Produces and Consumes Attribute is introduced in new ASP.NET MVC Core.

Produces Attribute
This attribute helps the user to inform the framework to generate and send the output result always in given content type as follows.
[Produces("application/json")]  

The above line is saying to the framework to use JSON as output format. This attribute can be decorated at controller level as well as Action level. Action level will be taken as the first priority if it is declared at both controller level as well as Action level.

Consumes Attribute
An Attribute helps the user to inform the framework to accept the input always in given content type as follows.
[Consumes("application/json")]  

The above line is saying to the framework to use JSON as input format. This attribute can be decorated at controller level as well as Action level. Action level will be taken as the first priority if it is declared at both controller level as well as Action level.

If you want to control it globally, you can set this while configuring MVC in ConfigureServices method as follows.
Configure<MvcOptions>(options =>  
   Filters.Add(newProducesAttribute(“application/json”))  
); 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Call A C# Function With jQuery AJAX In ASP.NET MVC?

clock July 27, 2018 11:42 by author Peter

jQuery AJAX method is a very powerful function for doing asynchronous operations from the Web pages. It helps to update parts of a Web page without reloading the whole page. This increases the Website's speed and reduces the load. It can be used with any Web technology like HTML, ASP.NET, ASP.NET MVC, PHP, Ruby or any other. With jQuery AJAX method, you can create high performance features in our Website. Let me show you how to use this method in  ASP.NET MVC page.

ASP.NET MVC Page
To understand the working of jQuery AJAX, I will create a login feature in ASP.NET MVC page. The page will have 2 input controls to enter the username and the password. There will also be a button to submit the two values for checking from the database.
When the username and password are correct, the secured information of the user is shown, else the “wrong username and password” is shown.
The main attraction here is that I will use jQuery AJAX method to check the username and the password. There will be no page reloading during checking.
To start learning jQuery AJAX method, I would suggest you check – jQuery AJAX. Also, look for the syntax and the key-value pairs that can be passed to this method.

The Controller Code
Start with creating a “Controller” in your ASP.NET MVC Application. Now, add a C# function “GetSecuredData” into the controller.
[HttpPost] 
public string GetSecuredData(string userName, string password) 

    string securedInfo = ""; 
    if ((userName == "admin") && (password == "admin")) 
        securedInfo = "Hello admin, your secured information is ......."; 
    else 
        securedInfo = "Wrong username or password, please retry."; 
    return securedInfo; 
}
 

The C# function given above will be called by jQuery AJAX method. As you can see, this function has 2 parameters, “username” and “password”. In these 2 parameters, it receives the username and the password values. It then checks them and shows the secured information, if they are the correct ones.

You can also change the code given above to include the database operation, where the username and the password are checked against the ones stored in the database.

The View code
Now, create a view for the Controller. This view will contain the two input controls for the username and password. There will be a button, which when clicked will call jQuery AJAX function.
<h3>Enter the Username and Password:</h3> 
(enter "admin" for both username and password) 
<input type="text" id="usernameInput" placeholder="Username" /> 
<input type="text" id="passwordInput" placeholder="Password" /> 
<button id="submit">Submit</button> 
<div id="dataDiv"></div> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> 
<script> 
    $(document).ready(function () { 
        $("#submit").click(function (e) { 
            if ($("#usernameInput").val() == "") 
                alert("Username cannot be empty"); 
            else if ($("#passwordInput").val() == "") 
                alert("Password cannot be empty"); 
            else { 
                $.ajax({ 
                    type: "POST", 
                    url: "/Home/GetSecuredData", 
                    contentType: "application/json; charset=utf-8", 
                    data: '{"userName":"' + $("#usernameInput").val() + '","password":"' + $("#passwordInput").val() + '"}', 
                    dataType: "html", 
                    success: function (result, status, xhr) { 
                        $("#dataDiv").html(result); 
                    }, 
                    error: function (xhr, status, error) { 
                        $("#dataDiv").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText) 
                    } 
                }); 
            } 
            return false; 
        }); 
    }); 
</script> 


The button click event will call jQuery AJAX event. We pass the “controller name/function name” to the URL field. The jQuery AJAX event will call the C# function which gets the username and password values in its parameters.

Finally in the success function we will show the returned value from the C# function.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How To Open PDF File In New Tab In MVC Using C# ?

clock July 24, 2018 07:46 by author Peter

In this post, we will learn about how to open PDF or other files in a new tab using C#. For this example, first we need to return a file from MVC Controller then open the file in a new tab from view. For this, I will set return type "FileResult" from MVC controller and return "File" with a byte Array of the file and its content type. Let's start coding.

Step 1
First, create a new project of MVC from File -> New -> Project.

Step 2
Select ASP.NET Web Application (.Net Framework) for creating an MVC application and set Name and Location of Project.

Step 3
After setting the name and location of the project, open another dialog. From this dialog select MVC project and click OK.

After creating a project create one controller method inside the home controller and name that "GetReport". and write the below code in this method.

Controller
public FileResult GetReport() 

    string ReportURL = "{Your File Path}"; 
    byte[] FileBytes = System.IO.File.ReadAllBytes(ReportURL); 
    return File(FileBytes, "application/pdf"); 
}


Above method returns FileBytes, and Content type is "application/pdf".

View
Create one function for an open PDF file in a new tab.
function GetClientReport() { 
    window.open('/{ControllerName}/GetReport, "_blank"); 
};


The above function will open a new tab in the browser and call controller GetReport() method and this method returns file ,and browser is displayed in an opened tab.



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: Friendly Errors In MVC 5

clock July 20, 2018 08:51 by author Peter

In this article, I will be explaining 3 different ways to handle exceptions and display a friendly error page to the end user. Friendly Error Pages are the pages that you design to show the end user when any kind of not handled exception happens in your application and your expected result is not achieved. So, instead of presenting your end user with technical information regarding the exception, you show him a friend page. Also, presenting your end user with technical information is not a security best practice.

So, let's see the three ways.

Method 1: Custom Exception Filter
Custom Exception Filter

It is a filter that is called every time an exception occurs in the applied methods.

Why would I use a custom exception filter?


Because with a custom exception filter, you can handle in a generic way every kind of exception thrown by your actions and/or controllers. You may use custom exception filters to log your exceptions.

Steps to achieve this:
Step 1

Create a new class named CustomExceptionFilter.
public class CustomExceptionFilter : FilterAttribute, IExceptionFilter   
{   
    public void OnException( ExceptionContext filterContext )   
    {   
        filterContext.Result = new RedirectResult( "Home/About" );   
        filterContext.ExceptionHandled = true;   
    }   
}   

What this custom exception does is to redirect to your About action in your Home Controller. Do not forget to set the ExceptionHandled equal to true; otherwise it will not take effect.

Step 2
Apply your custom exception filter to your controller/action.
public class HomeController : Controller 

    [CustomExceptionFilter] 
    public ActionResult Index() 
    { 
        throw new Exception(); 
        return View(); 
    } 
 
    public ActionResult About() 
    { 
        ViewBag.Message = "Your application thrown an exception"; 
 
        return View(); 
    } 
 
    public ActionResult Contact() 
    { 
        ViewBag.Message = "Your contact page."; 
        throw new Exception(); 
        return View(); 
    } 


You can see that the exception filter is applied only to your Index Action so if you access your Contact action, you will be able to see the non-handled exception page.

Method 2: Web.Config configuration
Why would I handle an exception by web.config configuration?

It is easy to configure and useful when you do not need to log or work on the exception.

Steps to achieve this:

Step 1
Include this in your web.config inside the system.web tag.
<customErrors defaultRedirect="Error.cshtml" mode="On"></customErrors> 

Step 2
Update your Controller.
public class HomeController : Controller 

    [HandleError] 
    public ActionResult Index() 
    { 
        throw new Exception(); 
        return View(); 
    } 
 
    public ActionResult About() 
    { 
        ViewBag.Message = "Your application description page."; 
 
        return View(); 
    } 
 
    public ActionResult Contact() 
    { 
        ViewBag.Message = "Your contact page."; 
        throw new Exception();
        return View(); 
    } 


Observation - Like the custom exception filter, you may choose if you want to handle the exceptions at the Controller or Action level. Also, here, the handled exception is applied only to your Index action, you may see the non-handled error in the Contact View.

Method 3: Global.Asax Application_error
What is the Application_error?

It is to override the global exception handler of the application.

Why would I handle an exception by global.asax Application_error?
You do not need to set the places that you would like to handle the errors like before where you had to set the actions and controllers to be handled. Here, every exception will hit and be handled.

Steps to Achieve this:

Step 1
Update  your global.asax.
protected void Application_Error( object sender, EventArgs e ) 
  { 
      Exception exception = Server.GetLastError(); 
      Server.ClearError(); 
      Response.Redirect( "/Home/About" ); 
  } 


Like the custom exception handlers, it is very important to ClearError() in the Server. What is done here is the redirection of non-handled exceptions to the About action in the Home Controller. Congratulation, you just learned three good ways of handling exceptions in your application and presenting friendly error pages to your end users.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Use Log4net In ASP.NET MVC Application

clock July 17, 2018 08:30 by author Peter

You may have read several articles on how to use log4net; however,  this article explains how you can use it without having to initialize several times. Log4Net is a framework for implementing logging mechanisms. It is an open source framework. Log4net provides a simple mechanism for logging information to a variety of sources. Information is logged via one or more loggers. These loggers are provided at the below levels of logging:

  • Debug
  • Information
  • Warnings
  • Error
  • Fatal

Now let’s begin with implementation.

Add log4net Package

For this, you need to install log4net from NuGet Package Manager  to your ASP.NET MVC project as per the below screen.

Add Global.asax for loading log4net  configuration
Once installation is done, you need to add the below code in Application_Start() of  Global.asax
log4net.Config.XmlConfigurator.Configure(); 

Add log4net in config file
Now open web.config and enter the following details.
<configSections> 
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /> 
</configSections> 

<log4net> 
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender"> 
<file value="C:\Temp\nSightsLog.log" /> 
<appendToFile value="true" /> 
<maximumFileSize value="500KB" /> 
<maxSizeRollBackups value="2" /> 
<layout type="log4net.Layout.PatternLayout"> 
  <conversionPattern value="%date %level %logger - %message%newline" /> 
</layout> 
</appender> 
<root> 
<level value="All" /> 
<appender-ref ref="RollingFile" /> 
</root> 
</log4net> 


Implementing in specific file for accessing throughout application
Add a class Log.cs in the Utilities folder.
Now, in the constructor of this class, instantiate logs for monitoring and debugger loggers.
private Log() 

 monitoringLogger = LogManager.GetLogger("MonitoringLogger"); 
 debugLogger = LogManager.GetLogger("DebugLogger"); 


Here, you need to create Debug(), Error(), Info(), Warn(), Fatal() methods which will call respective methods from Log4 net.

Below is a sample.

public class Log 

    private static readonly Log _instance = new Log(); 
    protected ILog monitoringLogger; 
    protected static ILog debugLogger; 

    private Log() 
    { 
        monitoringLogger = LogManager.GetLogger("MonitoringLogger"); 
        debugLogger = LogManager.GetLogger("DebugLogger"); 
    } 



    /// <summary> 
    /// Used to log Debug messages in an explicit Debug Logger 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    public static void Debug(string message) 
    { 
        debugLogger.Debug(message); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    /// <param name="exception">The exception to log, including its stack trace </param> 
    public static void Debug(string message, System.Exception exception) 
    { 
        debugLogger.Debug(message, exception); 
    } 


    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    public static void Info(string message) 
    { 
        _instance.monitoringLogger.Info(message); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    /// <param name="exception">The exception to log, including its stack trace </param> 
    public static void Info(string message, System.Exception exception) 
    { 
        _instance.monitoringLogger.Info(message, exception); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    public static void Warn(string message) 
    { 
        _instance.monitoringLogger.Warn(message); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    /// <param name="exception">The exception to log, including its stack trace </param> 
    public static void Warn(string message, System.Exception exception) 
    { 
        _instance.monitoringLogger.Warn(message, exception); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    public static void Error(string message) 
    { 
        _instance.monitoringLogger.Error(message); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    /// <param name="exception">The exception to log, including its stack trace </param> 
    public static void Error(string message, System.Exception exception) 
    { 
        _instance.monitoringLogger.Error(message, exception); 
    } 


    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    public static void Fatal(string message) 
    { 
        _instance.monitoringLogger.Fatal(message); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    /// <param name="exception">The exception to log, including its stack trace </param> 
    public static void Fatal(string message, System.Exception exception) 
    { 
        _instance.monitoringLogger.Fatal(message, exception); 
    } 

     


Now, you need to call the logger class that logs directly into your action method.

public ActionResult Login() 
  { 
      //This is for example , we need to remove this code later 
      Log.Info("Login-page started..."); 

      // Boolean msg = CheckSetupType(); 
      return View(); 
  }  

 



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: List Of Users With Roles In ASP.NET MVC Identity

clock July 13, 2018 11:21 by author Peter

In this article, we will learn how to list all users with Associated Roles in ASP.NET MVC 5 using Identity. ASP.NET MVC 5 does not come with an inbuilt feature to list users with associated roles by default. However ASP.NET MVC have inbuilt UserManager, SignManager and RoleManager to assist this.

We need this feature in each of our applications as users are to be maintained along with their associated roles. We can apply a number of ideas to do this. In this article, we will learn a very simple way to list users with their associated RoleName as in the figure below.

Step 1
Create a View Model as Users-in-Role_ViewModel
public class Users_in_Role_ViewModel 
    { 
        public string UserId { get; set; } 
        public string Username { get; set; } 
        public string Email { get; set; } 
        public string Role { get; set; } 
    } 


Step 2
Add a new method called UsersWithRoles inside ManageUsersController and add the following codes.
public ActionResult UsersWithRoles() 
        { 
            var usersWithRoles = (from user in context.Users 
                                  select new 
                                  { 
                                      UserId = user.Id,                                       
                                      Username = user.UserName, 
                                      Email = user.Email, 
                                      RoleNames = (from userRole in user.Roles 
                                                   join role in context.Roles on userRole.RoleId  
                                                   equals role.Id 
                                                   select role.Name).ToList() 
                                  }).ToList().Select(p => new Users_in_Role_ViewModel() 
  
                                  { 
                                      UserId = p.UserId, 
                                      Username = p.Username, 
                                      Email = p.Email, 
                                      Role = string.Join(",", p.RoleNames) 
                                  }); 
  
  
            return View(usersWithRoles); 
        } 


Note - context.Users represents the table AspNetUsers which has navigation property roles which represent the AspNetUserInRoles table.

Step 3
Now, let’s add a View of UsersWithRoles method of ManageUsersController.
@model IEnumerable<MVC5Demo.UI.ViewModels.Users_in_Role_ViewModel> 
@{ 
    ViewBag.Title = "Users With Roles"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 

  
<div class="panel panel-primary"> 
    <div class="panel-heading"> 
        <h3 class="box-title"> 
            <b>Users with Roles</b> 
        </h3> 
    </div> 
    <!-- /.box-header --> 
    <div class="panel-body"> 
        <table class="table table-hover table-bordered table-condensed" id="UsersWithRoles"> 
            <thead> 
                <tr> 
                    <td><b>Username</b></td> 
                    <td><b>Email</b></td> 
                    <td><b>Roles</b></td> 
                </tr> 
            </thead> 
            @foreach (var user in Model) 
            { 
                <tr> 
                    <td>@user.Username</td> 
                    <td>@user.Email</td> 
                    <td>@user.Role</td> 
                     
                </tr> 
            } 
        </table> 
    </div> 
  
    <div class="panel-footer"> 
        <p class="box-title"><b>Total Users till @String.Format("{0 : dddd, MMMM d, yyyy}", DateTime.Now)  : </b><span class="label label-primary">@Model.Count()</span></p> 
    </div> 
</div> 
  
  
@section scripts{ 
    <script> 
        $(function () { 
            $('#UsersWithRoles').DataTable({ 
                "paging": true, 
                "lengthChange": true, 
                "searching": true, 
                "ordering": true, 
                "info": true, 
                "autoWidth": true 
            }); 
        }); 
    </script> 


Now, the above method and View will return the users to their roles.

n



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Project Modules In Treeview Using Angular And MVC

clock July 10, 2018 08:58 by author Peter

AngularJS is an MVC based framework. Google developed AngularJS. AngularJS is an open source project, which can be used freely, modified and shared by others.
Top features Of AngularJS

  • Two Way Data-Binding
    This means that any changes to the model update the view and any changes to the view updates the model.
  • Dependency Injection
    AngularJS has a built-in Dependency Injection, which makes application easier to develop, maintain and debug in addition to the test.
  • Testing
    Angular will test any of its code through both unit testing and end-to-end testing.
  • Model View Controller
    Split your application into MVC components. Maintaining these components and connecting them together means setting up Angular.
Prerequisites
  • Visual Studio 2017 Version 15.7.3
  • Microsoft .NET Framework Version 4.7
  • Microsoft SQL Server 2016
  • SQL Server Management Studio v17.7
In this project, the description is about the steps to create treeview structure of File and SubFile using AngularJS in MVC and This procedure can be implemented in case of Modules and related pages under each module in ERP type of project. So, here I show you a  project  which you can implement in a real-time scenario for better understanding of how many pages there are under respective Modules and the relation between Module and its corresponding pages.
Steps To Be Followed:
Step 1
Create a table named "Treeviewtbl".
Here I have a general script of Table creation with some dummy records inserted. You can find this SQL file inside the project folder named
"Treeviewtbl.sql"
Step 2
Then I have created an MVC application named "FileStructureAngular".
Step 3
Here I have added Entity Data Model named "SatyaModel.edmx" . Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add. A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.
Step 4
Inside HomeController I've added the following code.

Code Ref

 

    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
    using System.Web.Mvc; 
     
    namespace FileStructureAngular.Controllers 
    { 
        public class HomeController : Controller 
        { 
            // 
            // GET: /Home/ 
            public ActionResult Index() 
            { 
                return View(); 
            } 
     
            public JsonResult GetFileStructure() 
            { 
                List<Treeviewtbl> list = new List<Treeviewtbl>(); 
                using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities()) 
                { 
                    list = dc.Treeviewtbls.OrderBy(a => a.FileName).ToList(); 
                } 
     
                List<Treeviewtbl> treelist = new List<Treeviewtbl>(); 
                if (list.Count > 0) 
                { 
                    treelist = BuildTree(list); 
                } 
     
                return new JsonResult { Data = new { treeList = treelist }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; 
            } 
      
            public void GetTreeview(List<Treeviewtbl> list, Treeviewtbl current, ref List<Treeviewtbl> returnList) 
            { 
                var childs = list.Where(a => a.ParentID == current.ID).ToList(); 
                current.Childrens = new List<Treeviewtbl>(); 
                current.Childrens.AddRange(childs); 
                foreach (var i in childs) 
                { 
                    GetTreeview(list, i, ref returnList); 
                } 
            } 
     
            public List<Treeviewtbl> BuildTree(List<Treeviewtbl> list) 
            { 
                List<Treeviewtbl> returnList = new List<Treeviewtbl>();   
                var topLevels = list.Where(a => a.ParentID == list.OrderBy(b => b.ParentID).FirstOrDefault().ParentID); 
                returnList.AddRange(topLevels); 
                foreach (var i in topLevels) 
                { 
                    GetTreeview(list, i, ref returnList); 
                } 
                return returnList; 
            } 
        } 
    } 

 

Code Description
Fetch data from the database and return it as a JSON result. 

    public JsonResult GetFileStructure()  
            {  
                List<Treeviewtbl> list = new List<Treeviewtbl>();  
                using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())  
                {  
                    list = dc.Treeviewtbls.OrderBy(a => a.FileName).ToList();  
                }  
      
                List<Treeviewtbl> treelist = new List<Treeviewtbl>();  
                if (list.Count > 0)  
                {  
                    treelist = BuildTree(list);  
                }  
      
                return new JsonResult { Data = new { treeList = treelist }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };  
            }  

I used a recursion method required for angularTreeview directive. Recursion method for recursively getting all child nodes and getting a child of the current item:
public void GetTreeview(List<Treeviewtbl> list, Treeviewtbl current, ref List<Treeviewtbl> returnList) 
        { 
            var childs = list.Where(a => a.ParentID == current.ID).ToList(); 
            current.Childrens = new List<Treeviewtbl>(); 
            current.Childrens.AddRange(childs); 
            foreach (var i in childs) 
            { 
                GetTreeview(list, i, ref returnList); 
            } 
        } 

To find top levels items:

    public List<Treeviewtbl> BuildTree(List<Treeviewtbl> list) 
            { 
                List<Treeviewtbl> returnList = new List<Treeviewtbl>(); 
                var topLevels = list.Where(a => a.ParentID == list.OrderBy(b => b.ParentID).FirstOrDefault().ParentID); 
                returnList.AddRange(topLevels); 
                foreach (var i in topLevels) 
                { 
                    GetTreeview(list, i, ref returnList); 
                } 
                return returnList; 
            } 

Step 5

Add a partial class of "Treeviewtbl" class for adding an additional field for holding child items. 
Code Ref

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
 
namespace FileStructureAngular 

    public partial class Treeviewtbl 
    { 
        public List<Treeviewtbl> Childrens { get; set; } 
    } 

Here is a field property "children" for identifying child nodes. So we need to add an additional field in our Model. So, I will add a partial class to add an additional field to hold child items. 

Step 6

Add required files into our project. In this article, I am going to use angularTreeview directive. This a very popular directive to render treeview from hierarchical data in AngularJS application.

  • angular.treeview.css
  • angular.treeview.js
  • image folder
The angular.treeview.css file is present in the Contents Folder. The angular.treeview.js file is present in Scripts Folder. I have added 3 png files for folder closed, folder opened, and files inside folders.

Here folders are the Modules and files are the pages under respective modules.

Step 7

I have added a Javascript file, where we will write AngularJS code for creating an Angular module and an Angular controller. 
In our application, I will add a Javascript file into the Scripts folder. Go to Solution Explorer > Right click on "Scripts" folder > Add > New Item > Select Javascript file under Scripts > Enter file name (here in my application it is "myApp.js") > and then click on Add button.

var app = angular.module('myApp', ['angularTreeview']); 
app.controller('myController', ['$scope', '$http', function ($scope, $http) { 
    $http.get('/home/GetFileStructure').then(function (response) { 
        $scope.List = response.data.treeList; 
    }) 
}]) 

Add a dependency to your application module.
var app = angular.module('myApp', ['angularTreeview']);   

Here I created a module named myApp and registered a controller named myController and then added GetFileStructure controller action method of HomeController for fetching data from the database and it returned as a JSON result.
$http.get('/home/GetFileStructure').then(function (response) {  
        $scope.List = response.data.treeList;  
    })  
Step 8
Add view for that (here index action) named "Index.cshtml".


    ViewBag.Title = "Satyaprakash - Website Modules In Treeview"; 

 
@*<h2>Website Modules In Treeview</h2>*@ 
 
<fieldset> 
    <legend style="font-family:Arial Black;color:blue">Website Modules In Treeview File Structure</legend> 
    <div ng-app="myApp" ng-controller="myController"> 
        <span style="font-family:Arial Black;color:forestgreen">Selected Node : <span style="font-family:Arial Black;color:red">{{mytree.currentNode.FileName}}</span> </span> 
        <br/> 
        <br/> 
        <div data-angular-treeview="true" 
             data-tree-id="mytree" 
             data-tree-model="List" 
             data-node-id="ID" 
             data-node-label="FileName" 
             data-node-children="Childrens"> 
        </div> 
    </div> 
 
    <link href="~/Content/angular.treeview.css" rel="stylesheet" /> 
    @section Scripts{ 
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script> 
        <script src="~/Scripts/angular.treeview.js"></script> 
        <script src="~/Scripts/myApp.js"></script> 
    } 
</fieldset> 

Here I have created a module name and registered a controller name under this module.

<div ng-app="myApp" ng-controller="myController">  

Copy the script and css into your project and add a script and link tag to your page.

<link href="~/Content/angular.treeview.css" rel="stylesheet" />  
  @section Scripts{  
      <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>  
      <script src="~/Scripts/angular.treeview.js"></script>  
      <script src="~/Scripts/myApp.js"></script>  
  }  

Attributes of angular treeview are below.

  • angular-treeview: the treeview directive.
  • tree-id : each tree's unique id.
  • tree-model : the tree model on $scope.
  • node-id : each node's id.
  • node-label : each node's label.
  • node-children: each node's children.
<div data-angular-treeview="true" 
    data-tree-id="mytree" 
    data-tree-model="List" 
    data-node-id="ID" 
    data-node-label="FileName" 
    data-node-children="Childrens"> 
</div> 

Then I mentioned a span tag for showing the text of selected folder and file name inside treeview.

<span style="font-family:Arial Black;color:forestgreen">Selected Node : <span style="font-family:Arial Black;color:red">{{mytree.currentNode.FileName}}</span> </span>  
TREE attribute

  • angular-treeview: the treeview directive
  • tree-id : each tree's unique id.
  • tree-model : the tree model on $scope.
  • node-id : each node's id
  • node-label : each node's label
  • node-children: each node's children



About HostForLIFE.eu

HostForLIFE.eu 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 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in