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 5 Hosting - HostForLIFE.eu :: What is And Why We Do State Management In ASP.NET MVC

clock October 17, 2019 11:58 by author Peter

If your website consists of multiple pages and you want to share the data appearing on the 2nd page to the 4th page, then you will have to use State Management feature of ASP.NET. Since our whole communication through the internet is done using HTTP Protocol and when a client(Browser) sends request to the server then it establishes a connection using HTTP and server gives the response, after that, connection will be disconnected. Actually each time a connection is created for a request and after the response it will be disconnected, which means if you have some data on first page and want to get it on the 10th, then it will be impossible to do it without state management feature. If you don’t use this feature then you will have to go the database for each single request(if you require data) which creates huge network traffic with increasing number of users.

You can manage the state by the following ways,

    Client Side State Management

        Cookie
        QueryString
        Hidden Form Field

    Server Side State Management

        Session
        TempData

Note
Client Side Management means nothing will be stored on server side but on client side and reverse will happen on server side. (i.e. all data will be on server side)
 
Client Side State Management
 
Cookie
 
Cookie is a text file with some information in it, generated by the most websites that you visit and then saved it in your browser(folder or subfolder) if you have enabled the cookie option.
 
Advantages

    All information is stored on client side.
    With cookie you can use the remember me option, some websites that you visit first time which then asks you or you can choose a language of your choice and then the information on website appears in that particular language every time you visit(depends upon expiry date). Also, you have seen some time, that this kind of option will work on your machine(laptop) not on your other devices, so behind the scenario there is a cookie.

Disadvantages

    You can disable cookies in your browser settings. This is a major drawback and if you have use cookies in your site for some features then it will cost you badly.
    Less secure since you can view the data in cookies by opening DevTools(in chrome)

Cookie types

    Persistent (Can specify expiry time)
    Non Persistent(Use for sessions and will expire as the browser or tab is closed in which the web app is opened)

The recommended Data limit: 4096bytes(4kb). Size should not exceed this value as you send data (>4KB) using cookie on every request, then more broadband is used because in some scenarios uploading speed can be lesser.
 
QueryString
 
With QueryString, you can specify the data in the URL tab.

    Starts with a question mark(?)
    If there are two values that you are sending, then it will be separated with &.

    There is no limit on length of queryString but the most recommended length for query string is 1024 characters. Try your queryString to be in that range because some web servers will through 413 error(Entity too long to respond)

Advantages

    Can’t be disabled by client
    Can be used to share information between pages and most suitable where the information is static(remains static for whole website)

    e.g.You request to go the specific page but the login is required and you fill the form successfully and then redirected to page where you were before login.

Disadvantages

    You require information on 4th page which is present on 1st page, then you will have to fetch the info again from the database and then send it(if the data is dynamic or changed in recent activity)
    The information that we send using QueryString gets visible to all users so it can’t be used to send sensitive data but if require then encrypt it then send.(an extra effort)

Hidden Field

    Share information between multiple requests on same page.
    If there is Single page application(SAP) or there is a page like login page where you given three attempts to user for entering right username and password then you can use it as a counter.

 
Advantages
 
Can’t be disabled by client.
 
Disadvantages
 
Need Encryption because the value can be seen by using DevTools of browser.



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: Bootstrap Tab Strip in ASP.NET MVC

clock September 18, 2019 12:47 by author Peter

In this post, we will see how to render given below bootstrap Tab script in Asp.net MVC 5 view.

Here the number of tabs displayed in view would depend on count of members in the list.

1. Create ASP.NET MVC 5 project.
 
2. Define Member class as follows in “Member.cs” file
    public class Member 
    { 
    public int Id { get; set; } 
    public string Name { get; set; } 
    } 

3. Add view to create action method and pass a list of members from controller Action method to razor view file. i.e. “create.cshtml”
    public ActionResult Create() 
    { 
    List<Member> members = new List<Member>(); 
    members = GetMemberList(); 
    return View(members); 
    } 
    private List<Member> GetMemberList() 
    { 
    List<Member> members = new List<Member>(); 
    members.Add(new Member{ Name = "member1" }); 
    members.Add(new Member { Name = "member2" }); 
    members.Add(new Member { Name = "member3" }); 
    members.Add(new Member { Name = "member4" }); 
    members.Add(new Member { Name = "member5" }); 
    return members; 
    } 


4. Using CSS classes, we can create a tabscript in our “create.cshtml” as shown below:
    @model IEnumerable<Member> 
    <div class="container"> 
    @if (Model.ToList().Count > 0) 
    { 
    <ul class="nav nav-tabs" role="tablist"> 
    @{int i = 0; 
    foreach (var item in Model) 
    { 
    if (i == 0) 
    { 
    <li class="nav-item"> 
    <a class="nav-link active" data-toggle="tab" href="#@item.Name">@item.Name</a> 
    </li> 
    } 
    else 
    { 
    <li class="nav-item"> 
    <a class="nav-link" data-toggle="tab" href="#@item.Name">@item.Name</a> 
    </li> 
    } 
    i++; 
    } 
    } 
    </ul> 
    <div class="tab-content"> 
    @foreach (var item in Model) 
    { 
    <div id="@item.Name" class="container tab-pane active"> 
    <br> 
    <h3>@item.Name 's Tab Area </h3> 
    </div> 
    } 
    </div> 
    } 
    </div> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> 



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: Limit Upload File Type Extensions Via Custom Data Annotation/Attribute

clock December 21, 2018 08:15 by author Peter

Restricting or limiting the file type extensions is a key business requirement. It is not necessary that a business allows all file types to be uploaded via their web application. Sometimes, only image files are accepted by the web application, sometimes only documents, and sometimes the combination of image, documents, and compressed file types are accepted by the web system.

Today, I shall be demonstrating the process of limiting/restricting the desired upload file type extensions by implementing custom data annotation/attribute component on ASP.NET MVC5 platform. This article is not specific to image files only, you can use the provided solution with any type of file format as well.

Following are some prerequisites before you proceed any further in this tutorial.

  • Knowledge of ASP.NET MVC5.
  • Knowledge of HTML.
  • Knowledge of Bootstrap.
  • Knowledge of C# Programming.

You can download the complete source code for this tutorial or you can follow the step by step discussion below. The sample code is being developed in Microsoft Visual Studio 2015 Enterprise.

Let's begin now.

Step 1

Create a new MVC web project and name it as "ImgExtLimit".

Step 2

You need to add/update the "executionTimeout", "maxRequestLength", and "maxAllowedContentLength" property values if not already added in the "Web.config" file, as shown below.
<system.web> 
  <authentication mode="None" /> 
  <compilation debug="true" targetFramework="4.5.2" /> 
  <!-- executionTimeout = 30hrs (the value is in seconds) and maxRequestLength = 1GB (the value is in Bytes) --> 
  <httpRuntime targetFramework="4.5.2" executionTimeout="108000" maxRequestLength="1073741824" /> 
</system.web>    
<system.webServer> 
  <!-- maxAllowedContentLength = 1GB (the value is in Bytes) -->     
  <security> 
    <requestFiltering> 
      <requestLimits maxAllowedContentLength="1073741824" /> 
    </requestFiltering> 
  </security>         
 
</system.webServer> 

 
executionTimeout -> Amount of time required to process your request on the web server. The value is provided in seconds.
maxRequestLength -> Maximum size which your request can capture and send to the web server. The value is provided in bytes.
maxAllowedContentLength -> Maximum allowed size of your content (e.g. file, text data etc.) that is sent to the web server. The value is provided in bytes.

Step 3
Open the "Views->Shared->_Layout.cshtml" file and replace the code with the following.
<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8" /> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <title>@ViewBag.Title</title> 
    @Styles.Render("~/Content/css") 
    @Scripts.Render("~/bundles/modernizr") 
 
    <!-- Font Awesome --> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" /> 
 
</head> 
<body> 
    <div class="navbar navbar-inverse navbar-fixed-top"> 
        <div class="container"> 
            <div class="navbar-header"> 
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> 
                    <span class="icon-bar"></span> 
                    <span class="icon-bar"></span> 
                    <span class="icon-bar"></span> 
                </button> 
            </div> 
        </div> 
    </div> 
    <div class="container body-content"> 
        @RenderBody() 
        <hr /> 
        <footer> 
            <center> 
                <p><strong>Copyright © @DateTime.Now.Year - <a href="http://wwww.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p> 
            </center> 
        </footer> 
    </div> 
 
    @*Scripts*@ 
    @Scripts.Render("~/bundles/jquery") 
 
    @Scripts.Render("~/bundles/jqueryval") 
    @Scripts.Render("~/bundles/bootstrap") 
 
    @RenderSection("scripts", required: false) 
</body> 
</html>

In the above code, I have simply created a basic default layout page and linked the require libraries into it.

Step 4
Create a new "Helper_Code\Common\AllowExtensionsAttribute.cs" file and add the following code.
//----------------------------------------------------------------------- 
// <copyright file="AllowExtensionsAttribute.cs" company="None"> 
//     Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose. 
// </copyright> 
// <author>Asma Khalid</author> 
//----------------------------------------------------------------------- 
 
namespace ImgExtLimit.Helper_Code.Common 

    using System; 
    using System.Collections.Generic; 
    using System.ComponentModel.DataAnnotations; 
    using System.Linq; 
    using System.Web; 
 
    /// <summary> 
    /// File extensions attribute class 
    /// </summary> 
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 
    public class AllowExtensionsAttribute : ValidationAttribute 
    { 
        #region Public / Protected Properties 
 
        /// <summary> 
        /// Gets or sets extensions property. 
        /// </summary> 
        public string Extensions { get; set; } = "png,jpg,jpeg,gif"; 
 
        #endregion 
 
        #region Is valid method 
 
        /// <summary> 
        /// Is valid method. 
        /// </summary> 
        /// <param name="value">Value parameter</param> 
        /// <returns>Returns - true is specify extension matches.</returns> 
        public override bool IsValid(object value) 
        { 
            // Initialization 
            HttpPostedFileBase file = value as HttpPostedFileBase; 
            bool isValid = true; 
 
            // Settings. 
            List<string> allowedExtensions = this.Extensions.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); 
 
            // Verification. 
            if (file != null) 
            { 
                // Initialization. 
                var fileName = file.FileName; 
 
                // Settings. 
                isValid = allowedExtensions.Any(y => fileName.EndsWith(y)); 
            } 
 
            // Info 
            return isValid; 
        } 
 
        #endregion 
    } 
}


In ASP.NET MVC 5, creating customized data annotations/attributes is one of the cool features. The ASP.NET MVC 5 platform already contains a default FileExtensions attribute, but, the issue with this pre-built data annotation/attribute is that it is applicable only on string type view model properties and in my case, I am uploading the files via "HttpPostedFileBase" data type view model property. This means that the pre-built data annotation/attribute does not have any means to know the data type of the file(s) that I am uploading which will have  no effect on the limitation that is considered to be applied on the uploaded file type extensions. Of course, there are many other tricks or workarounds to go through while working with the pre-built FileExtensions attribute, but, I prefer the custom data annotation/attribute mechanism, which is much simpler.

So, in the above code, I have created a new class "AllowExtensionsAttribute" (by following the naming convention of custom attribute class) and inherited the ValidationAttribute class. Then, I have created a public property "Extensions" and set the default value with image file type extensions, which means that my custom attribute will accept only image file type to be uploaded. So, in order to allow the required file type extensions, this property will be updated at the time of my custom attribute utilization accordingly. Finally, I have overridden the "IsValid(....)" method which will receive my uploaded file as "HttpPostedFileBase" data type and from this, I will extract the file type extension of the uploaded file and then validate whether it is according to either default file type extension restriction or according to my provided file type extensions.

Step 5
Now, create a new "Models\ImgViewModel.cs" file and replace the following code in it i.e.
//----------------------------------------------------------------------- 
// <copyright file="ImgViewModel.cs" company="None"> 
//     Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose. 
// </copyright> 
// <author>Asma Khalid</author> 
//----------------------------------------------------------------------- 
 
namespace ImgExtLimit.Models 

    using System.Collections.Generic; 
    using System.ComponentModel.DataAnnotations; 
    using System.Web; 
    using Helper_Code.Common; 
 
    /// <summary> 
    /// Image view model class. 
    /// </summary> 
    public class ImgViewModel 
    { 
        #region Properties 
 
        /// <summary> 
        /// Gets or sets Image file property. 
        /// </summary> 
        [Required] 
        [Display(Name = "Supported Files .png | .jpg")] 
        [AllowExtensions(Extensions = "png,jpg", ErrorMessage = "Please select only Supported Files .png | .jpg")] 
        public HttpPostedFileBase FileAttach { get; set; } 
 
        /// <summary> 
        /// Gets or sets message property. 
        /// </summary> 
        public string Message { get; set; } 
 
        /// <summary> 
        /// Gets or sets is valid propertty. 
        /// </summary> 
        public bool isValid { get; set; } 
 
        #endregion 
    } 
}

In the above code, I have created my view model which I will attach with my view. Here, I have created HttpPostedFileBase type file attachment property which will capture uploaded image/file data from the end-user, then I have also applied my custom "AllowExtensions" attribute to the FileAttach property and provide the list of file type extensions separated by a comma (,) that I have allowed my system to accept. Then, I have created two more properties; i.e., Message of data type string and isValid of data type Boolean for processing purpose.

Step 6

Create a new "Controllers\ImgController.cs" file and add the following code to it.
//----------------------------------------------------------------------- 
// <copyright file="ImgController.cs" company="None"> 
//     Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose. 
// </copyright> 
// <author>Asma Khalid</author> 
//----------------------------------------------------------------------- 
 
namespace ImgExtLimit.Controllers 

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
    using System.Web.Mvc; 
    using Models; 
 
    /// <summary> 
    /// Image controller class. 
    /// </summary> 
    public class ImgController : Controller 
    { 
        #region Index view method. 
 
        #region Get: /Img/Index method. 
 
        /// <summary> 
        /// Get: /Img/Index method. 
        /// </summary>         
        /// <returns>Return index view</returns> 
        public ActionResult Index() 
        { 
            // Initialization/ 
            ImgViewModel model = new ImgViewModel() { FileAttach = null, Message = string.Empty, isValid = false }; 
 
            try 
            { 
            } 
            catch (Exception ex) 
            { 
                // Info 
                Console.Write(ex); 
            } 
 
            // Info. 
            return this.View(model); 
        } 
 
        #endregion 
 
        #region POST: /Img/Index 
 
        /// <summary> 
        /// POST: /Img/Index 
        /// </summary> 
        /// <param name="model">Model parameter</param> 
        /// <returns>Return - Response information</returns> 
        [HttpPost] 
        [AllowAnonymous] 
        [ValidateAntiForgeryToken] 
        public ActionResult Index(ImgViewModel model) 
        { 
            try 
            { 
                // Verification 
                if (ModelState.IsValid) 
                { 
                    // Settings. 
                    model.Message = "'" + model.FileAttach.FileName + "' file has been successfuly!! uploaded"; 
                    model.isValid = true; 
                } 
                else 
                { 
                    // Settings. 
                    model.Message = "'" + model.FileAttach.FileName + "' file is not supported. "; 
                    model.isValid = false; 
                } 
            } 
            catch (Exception ex) 
            { 
                // Info 
                Console.Write(ex); 
            } 
 
            // Info 
            return this.View(model); 
        } 
 
        #endregion 
 
        #endregion 
    } 
}

In the above code, I have created a GET "Index(...)" method which will initialize the view model with default values and send it to the view page. Finally, I have created a POST "Index(...)" method which will receive an input image file from the end-user, then validate the view model for allowed file type extensions and then send the response message accordingly.

Step 7
Now, create a view "Views\Img\Index.cshtml" file and add the following code to it.
@using ImgExtLimit.Models 
 
@model ImgExtLimit.Models.ImgViewModel 
 
@{ 
    ViewBag.Title = "ASP.NET MVC5: Limit Upload File Extension"; 

 
 
<div class="row"> 
    <div class="panel-heading"> 
        <div class="col-md-8"> 
            <h3> 
                <i class="fa fa-file-text-o"></i> 
                <span>ASP.NET MVC5: Limit Upload File Extension</span> 
            </h3> 
        </div> 
    </div> 
</div> 
 
<br /> 
 
<div class="row"> 
    <div class="col-md-6 col-md-push-2"> 
        <section> 
            @using (Html.BeginForm("Index", "Img", FormMethod.Post, new { enctype = "multipart/form-data", @class = "form-horizontal", role = "form" })) 
            { 
                @Html.AntiForgeryToken() 
 
                <div class="well bs-component"> 
                    <br /> 
 
                    <div class="row"> 
                        <div class="col-md-12"> 
                            <div class="col-md-8 col-md-push-2"> 
                                <div class="input-group"> 
                                    <span class="input-group-btn"> 
                                        <span class="btn btn-default btn-file"> 
                                            Browse… 
                                            @Html.TextBoxFor(m => m.FileAttach, new { type = "file", placeholder = Html.DisplayNameFor(m => m.FileAttach), @class = "form-control" }) 
                                        </span> 
                                    </span> 
                                    <input type="text" class="form-control" readonly> 
                                </div> 
                                @if (Model.isValid && !string.IsNullOrEmpty(Model.Message)) 
                                { 
                                    <span class="text-success">@Model.Message</span> 
                                } 
                                else 
                                { 
                                    <span class="text-danger">@Model.Message</span>@Html.ValidationMessageFor(m => m.FileAttach, "", new { @class = "text-danger" }) 
                                } 
                            </div> 
                        </div> 
                    </div> 
 
                    <div class="form-group"> 
                        <div class="col-md-12"> 
                        </div> 
                    </div> 
 
                    <div class="form-group"> 
                        <div class="col-md-offset-5 col-md-10"> 
                            <input type="submit" class="btn btn-danger" value="Upload" /> 
                        </div> 
                    </div> 
                </div> 
            } 
        </section> 
    </div> 
</div> 
 
@section Scripts 

    @*Scripts*@ 
    @Scripts.Render("~/bundles/bootstrap-file") 
 
    @*Styles*@ 
    @Styles.Render("~/Content/Bootstrap-file/css") 
}


In the above code, I have created a simple view for uploading the image file to the server which will validate the allowed file type extensions at the server side.

Step 8
Now, execute the project



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: AngularJS Login Page in ASP.NET MVC 5

clock May 17, 2016 23:45 by author Anthony

In this tutorial i am going to explain about how to create a login page using Angular js in MVC 5 application. In this tutorial i used Simple form validation using angular(we will discuss about angular validation in detail in future post).And also a $http angular built in service.

$http: It is a angular JS built in service for communicating with remote servers.In Angular all communications (Request and response) between server and client are handled by services like $http.

Step 1: Create a Data table in Database

1.Here i used Local Database for Table creation (Sql Express).
2.Right click server explorer --> expand Database --> Right click on tables --> Click Add new table.
3.Create a table with  following columns if you want you can add more columns.
4.Here i created following table.

Step 2: Add ADO.NET Entity Data Model

1.Right click on Models --> Add --> New Item -->Select ADO.NET Entity Data Model(Under Data) --> name it -->Add --> select Add from Database (In Entity Data Model wizard) --> Next
2.Select Database --> give name for web.config.
3.Choose your Database objects(tables) and click finish.


Step 3: Add a Model Class to Solution

1.Right click Models --> Add --> Class and name it (I named it as UserModel.cs).
2.These Model objects are useful while we sending data from View to Controller.
3.We bind this Model properties with angular ngModel.(you will see in index.cshtml).
4.replace code with following code

namespace LoginUsingAngular.Models
{
    public class UserModel
    {
        public string Email { get; set; }
        public string Password { get; set; }
    }
}

Step 4: Add New Action Method in HomeController to Check User Data

1.This Action Method gets data from database based on user entered data in form.and returns that data in Json format to angular Controller.
2.Add code in HomeController
getLoginData():

public ActionResult getLoginData(UserModel obj)
        {
            DatabaseEntities db = new DatabaseEntities();
            var user = db.Users.Where(x => x.Email.Equals(obj.Email) && x.Password.Equals(obj.Password)).FirstOrDefault();
            return new JsonResult {Data=user,JsonRequestBehavior=JsonRequestBehavior.AllowGet };
        }

Step 5: Add angular controller for checking Login Form

1.Create angular module in  Module.js file.
(function () {
    var myApp = angular.module("myApp",[]);
})();

2.Now add another script file for angular controller and Factory method.
3.Right click on Scripts folder --> add LoginController.js
4.Replace code in LoginController.js file.

angular.module('myApp').controller('LoginController', function ($scope, LoginService) {
 
        //initilize user data object
        $scope.LoginData = {
            Email: '',
            Password:''
        }
        $scope.msg = "";
        $scope.Submited = false;
        $scope.IsLoggedIn = false;
        $scope.IsFormValid = false;
 
        //Check whether the form is valid or not using $watch
        $scope.$watch("myForm.$valid", function (TrueOrFalse) {
            $scope.IsFormValid = TrueOrFalse;   //returns true if form valid
        });
 
        $scope.LoginForm = function () {
            $scope.Submited = true;
            if ($scope.IsFormValid) {
                LoginService.getUserDetails($scope.UserModel).then(function (d) {
                    debugger;
                    if (d.data.Email != null) {
                        debugger;
                        $scope.IsLoggedIn = true;
                        $scope.msg = "You successfully Loggedin Mr/Ms " +d.data.FullName;
                    }
                    else {
                        alert("Invalid credentials buddy! try again");
                    }
                });
            }
        }
    })
    .factory("LoginService", function ($http) {
        //initilize factory object.
        var fact = {};
        fact.getUserDetails = function (d) {
            debugger;
            return $http({
                url: '/Home/getLoginData',
                method: 'POST',
                data:JSON.stringify(d),
                headers: { 'content-type': 'application/json' }
            });
        };
        return fact;
    });


4.Here,I validated form using $watch in above code.
5.I created a angular service LoginService that gets data from server controller (from HomeController.getLoginData() action).
6.LoginForm() method is initiated when user submits form using ngSubmit as angular attribute.


Step 6: Add View to display Login Form

1.Right click on Index action --> Add View --> add
2.Replace Index.cshtml view code with following code

@{
    ViewBag.Title = "Login Using Angular";
}
<h2>Login Using Angular</h2>

<div ng-controller="LoginController">
    <form name="myForm" novalidate ng-submit="LoginForm()">
        <div style="color:green">{{msg}}</div>
        <table ng-show="!IsLoggedIn" class="table table-horizontal">
            <tr>
                <td>Email/UserName :</td>
                <td>
                    <input type="email" ng-model="UserModel.Email" name="UserEmail" ng-class="Submited?'ng-dirty':''" required autofocus class="form-control"/>
                    <span style="color:red" ng-show="(myForm.UserEmail.$dirty || Submited ) && myForm.UserEmail.$error.required">Please enter Email</span>
                    <span style="color:red" ng-show="myForm.UserEmail.$error.email">Email is not valid</span>
                </td>
            </tr>
            <tr>
                <td>Password :</td>
                <td>
                    <input type="password" ng-model="UserModel.Password" name="UserPassword" ng-class="Submited?'ng-dirty':''" required autofocus class="form-control"/>
                    <span style="color:red" ng-show="(myForm.UserPassword.$dirty || Submited) && myForm.UserPassword.$error.required">Password Required</span>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="submit" value="submit" class="btn btn-success" />
                </td>
            </tr>
        </table>
    </form>
</div>
@section scripts{
    <script src="~/Scripts/LoginController.js"></script>
}

Add script reference at the end of Index.cshtml page.
Take a look at following things i used in above Index.cshtml view.

ng-Model: ngModel is a angular directive.it is used for two way binding data from view to controller and controller to view.In above example i used it to bind from data to angular controller.

ng-show: ngShow allows to display or hide elements based on the expression provided to ngShow attribute.

ng-submit:  ng-submit prevents the default action of form and binds angular function to onsubmit events. This is invoked when form is submitted.

$dirty: It is angular built in property. It will be true if user interacted with form other wise false.This is one of the angular validation property i used in above example.There are many validation properties in angular like $invalid,$submitted,$pristine,$valid and $error.We will learn about all these these properties in later tutorials.

 




ASP.NET MVC 5 Hosting - HostForLIFE.eu :: How To Create Area?

clock April 28, 2016 20:59 by author Anthony

Today, you will learn how to create Area in MVC 5. In MVC 5 (Visual Studio 2013), Area option can be found under ‘Add Scaffold’ dialog. In this post, I will take you through step by step to setup and running Area in MVC 5.


As you know MVC Architecture separates all the logics: model logic, business logic and presentation logic and provides a very clean and light weight application in total. One more good thing that I love is, it provides logical separation physically also. In physical logic separation controllers, models and views are kept in another folder on root with the help of Area. Areas provide a way to separate a large MVC Web Application into smaller functional groupings inside MVC Application and each group contains MVC Structure (Ex. Model, View and Controller folders). Area was introduced with MVC 2 release.

Assume, you are working on a MVC Project where you have a requirement  to develop various sections like account section, administrative section, support section, billing section and so on. Area is the best choice here, it will provide a strong physical structure as well as better code manageability. See how it looks like.

 


You can see every section has MVC Architecture Controller, Model, View (view will have a Shared folder where you can place your layouts, partial views etc) and an AreaRegistration (which contains RegisterArea method very similar to RegisterRoutes).

How to Create It

We are going to create CRUD views for Employee inside Area. We will take the advantage of EF Code First. Let’s walk through the simple steps. In Visual Studio 2012 IDE (MVC 4), we just right click on Project | Add | Area to create Area.

 

Step 1


Right click on Project and then select Add | Scaffold | MVC 5 Area.

Step 2

When we click on ‘Scaffold’ it opens a dialog where we need to select MVC 5 Area and hit on Add button, it will ask to enter area name, type ‘Admin’ and hit Add.
Do the same to add Area for Billing and Support, at the end we will have following structure.



 

Now once we are done with adding areas, go to next step.

Step 3


In above step we added three Areas, in each area we will find a class file areanameAreaRegistration.cs file, open this file, we will find following RegisterArea method inside class which inherits AreaRegistration class.

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


Look at this root closely, we will find this route begins with Admin and then controller, action and id (which is marked as optional).


We will find same thing in other Area also.

In total we have three areanameAreaRegistration.cs classes all inherits AreaRegistration class, and also a route defined for the Area. These routes should be registered inside Application_Start() method of Global.asax file, here is the code.

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}


Now, let’s go in next step where we will create CRUD views and see how it opens in browser.


Step 4


Once we have done with previous steps, just go ahead and add model, controller and views to see how area opens in browser. We could and anything we want but just to keep things simple I am going to create a CRUD in Admin Area for Employee, here is the model I will be using.

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}

Now, create CRUD views and browse it.

Look at the URL in above image you will see the first segment ‘Admin’ is area name, second segment ‘Employee’ is controller, third segment ‘Details’ is action result and fourth segment ‘1’ is ID.


So, you can see how Area is working in MVC 5. There is no difference in ‘Area in MVC 4’ and ‘Area in MVC 5’, things are still same, the only change is the way Area added, that’s it.

 

HostForLIFE.eu ASP.NET MVC 5 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.

http://aspnetmvceuropeanhosting.hostforlife.eu/image.axd?picture=2015%2f10%2fhostforlifebanner.png



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: How to Handle ASP.NET MVC 5 Errors?

clock April 27, 2016 23:38 by author Anthony

Custom error pages and global error logging are two elementary and yet very confusing topics in ASP.NET MVC 5.

There are numerous ways of implementing error pages in ASP.NET MVC 5 and when you search for advice you will find a dozen different StackOverflow threads, each suggesting a different implementation.

Overview

What is the goal?


Typically good error handling consists of:

  • Human friendly error pages
    • Custom error page per error code (e.g.: 404, 403, 500, etc.)
    • Preserving the HTTP error code in the response to avoid search engine indexing
  • Global error logging for unhandled exceptions

Error pages and logging in ASP.NET MVC 5


There are many ways of implementing error handling in ASP.NET MVC 5. Usually you will find solutions which involve at least one or a combination of these methods:

  • HandleErrorAttribute
  • Controller.OnException Method
  • Application_Error event
  • CustomErrors element in web.config
  • httpErrors element in web.config
  • Custom HttpModule

All these methods have a historical reason and a justifyable use case. There is no golden solution which works for every application. It is good to know the differences in order to better understand which one is applied best.

Before going through each method in more detail I would like to explain some basic fundamentals which will hopefully help in understanding the topic a lot easier.

ASP.NET MVC Fundamentals


The MVC framework is only a HttpHandler plugged into the ASP.NET pipeline. The easiest way to illustrate this is by opening the Global.asax.cs:

public class MvcApplication : System.Web.HttpApplication
Navigating to the implementation of HttpApplication will reveal the underlying IHttpHandler and IHttpAsyncHandler interfaces:

public class HttpApplication : IComponent, IDisposable, IHttpAsyncHandler, IHttpHandler
ASP.NET itself is a larger framework to process incoming requests. Even though it could handle incoming requests from different sources, it is almost exclusively used with IIS. It can be extended with HttpModules and HttpHandlers.

HttpModules are plugged into the pipeline to process a request at any point of the ASP.NET life cycle. A HttpHandler is responsible for producing a response/output for a request.

IIS (Microsoft's web server technology) will create an incoming request for ASP.NET, which subsequently will start processing the request and eventually initialize the HttpApplication (which is the default handler) and create a response:

IIS, ASP.NET and MVC architecture

The key thing to know is that ASP.NET can only handle requests which IIS forwards to it. This is determined by the registered HttpHandlers (e.g. by default a request to a .htm file is not handled by ASP.NET).

And finally, MVC is only one of potentially many registered handlers in the ASP.NET pipeline.

This is crucial to understand the impact of different error handling methods.

Breaking down the options


HandleErrorAttribute

The HandleErrorAttribute is an MVC FilterAttribute, which can be applied to a class or a method:

namespace System.Web.Mvc
{
    [AttributeUsage(
        AttributeTargets.Class | AttributeTargets.Method,
        Inherited = true,
        AllowMultiple = true)]
    public class HandleErrorAttribute : FilterAttribute, IExceptionFilter
    {
        // ...
    }
}

It's error handling scope is limited to action methods within the MVC framework. This means it won't be able to catch and process exceptions raised from outside the ASP.NET MVC handler (e.g. exceptions at an earlier stage in the life cycle or errors in other handlers). It will equally not catch an exception if the action method is not part of the call stack (e.g. routing errors).

Additionally the HandleErrorAttribute only handles 500 internal server errors. For instance this will not be caught by the attribute:

[HandleError]
public ActionResult Index()
{
    throw new HttpException(404, "Not found");
}

You can use the attribute to decorate a controller class or a particular action method. It supports custom error pages per exception type out of the box:

[HandleError(ExceptionType = typeof(SqlException), View = "DatabaseError")]]
In order to get the HandleErrorAttribute working you also need to turn customErrors mode on in your web.config:

<system.web>
    <customErrors mode="On" />
</system.web>

Use case

The HandleErrorAttribute is the most limited in scope. Many application errors will bypass this filter and therefore it is not ideal for global application error handling.

It is a great tool for action specific error handling like additional fault tolerance for a critical action method though.

Controller.OnException Method


The OnException method gets invoked if an action method from the controller throws an exception. Unlike the HandleErrorAttribute it will also catch 404 and other HTTP error codes and it doesn't require customErrors to be turned on.

It is implemented by overriding the OnException method in a controller:

protected override void OnException(ExceptionContext filterContext)
{
    filterContext.ExceptionHandled = true;
           
    // Redirect on error:
    filterContext.Result = RedirectToAction("Index", "Error");

    // OR set the result without redirection:
    filterContext.Result = new ViewResult
    {
        ViewName = "~/Views/Error/Index.cshtml"
    };
}

With the filterContext.ExceptionHandled property you can check if an exception has been handled at an earlier stage (e.g. the HandleErrorAttribute):

if (filterContext.ExceptionHandled)
    return;

Many solutions on the internet suggest to create a base controller class and implement the OnException method in one place to get a global error handler.

However, this is not ideal because the OnException method is almost as limited as the HandleErrorAttribute in its scope. You will end up duplicating your work in at least one other place.

Use case


The Controller.OnException method gives you a little bit more flexibility than the HandleErrorAttribute, but it is still tied to the MVC framework. It is useful when you need to distinguish your error handling between regular and AJAX requests on a controller level.

Application_Error event


The Application_Error method is far more generic than the previous two options. It is not limited to the MVC scope any longer and needs to be implemented in the Global.asax.cs file:

protected void Application_Error(Object sender, EventArgs e)
{
    var raisedException = Server.GetLastError();

    // Process exception
}

If you've noticed it doesn't come from an interface, an abstract class or an overriden method. It is purely convention based, similar like the Page_Load event in ASP.NET Web Forms applications.

Any unhandeled exception within ASP.NET will bubble up to this event. There is also no concept of routes anymore (because it is outside the MVC scope). If you want to redirect to a specific error page you have to know the exact URL or configure it to co-exist with "customErrors" or "httpErrors" in the web.config.

Use case


In terms of global error logging this is a great place to start with! It will capture all exceptions which haven't been handled at an earlier stage. But be careful, if you have set filterContext.ExceptionHandled = true in one of the previous methods then the exception will not bubble up to Application_Error.

However, for custom error pages it is still not perfect. This event will trigger for all ASP.NET errors, but what if someone navigates to a URL which isn't handled by ASP.NET? For example try navigating to http://{your-website}/a/b/c/d/e/f/g. The route is not mapped to ASP.NET and therefore the Application_Error event will not be raised.

customErrors in web.config


The "customErrors" setting in the web.config allows to define custom error pages, as well as a catch-all error page for specific HTTP error codes:

<system.web>
    <customErrors mode="On" defaultRedirect="~/Error/Index">
        <error statusCode="404" redirect="~/Error/NotFound"/>
        <error statusCode="403" redirect="~/Error/BadRequest"/>
    </customErrors>
<system.web/>

By default "customErrors" will redirect a user to the defined error page with a HTTP 302 Redirect response. This is really bad practise because the browser will not receive the appropriate HTTP error code and redirect the user to the error page as if it was a legitimate page. The URL in the browser will change and the 302 HTTP code will be followed by a 200 OK, as if there was no error. This is not only confusing but has also other negative side effects like Google will start indexing those error pages.

You can change this behaviour by setting the redirectMode to "ResponseRewrite":

<customErrors mode="On" redirectMode="ResponseRewrite">

This fixes the initial problem, but will give a runtime error when redirecting to an error page now:

Runtime Error

An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page for the first exception. The request has been terminated.
This happens because "ResponseRewrite" mode uses Server.Transfer under the covers, which looks for a file on the file system. As a result you need to change the redirect path to a static file, for example to an .aspx or .html file:

<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/Error.aspx"/>
Now there is only one issue remaining with this configuration. The HTTP response code for the error page is still "200 OK". The only way to fix this is to manually set the correct error code in the .aspx error page:

<% Response.StatusCode = 404; %>
This is already pretty good in terms of custom error pages, but we can do better!

Noticed how the customErrors section goes into the system.web section? This means we are still in the scope of ASP.NET.

Files and routes which are not handled by your ASP.NET application will render a default 404 page from IIS (e.g. try http://{your-website}/not/existing/image.gif).

Another downside of customErrors is that if you use a HttpStatusCodeResult instead of throwing an actual exception then it will bypass the ASP.NET customErrors mode and go straight to IIS again:

public ActionResult Index()
{
    return HttpNotFound();
    //throw new HttpException(404, "Not found");
}

In this case there is no hack which can be applied to display a friendly error page which comes from customErrors.

Use case


The customErrors setting was for a long time the best solution, but still had its limits. You can think of it as a legacy version of httpErrors, which has been only introduced with IIS 7.0.

The only time when customErrors still makes sense is if you can't use httpErrors, because you are running on IIS 6.0 or lower.

httpErrors in web.config

The httpErrors section is similar to customErrors, but with the main difference that it is an IIS level setting rather than an ASP.NET setting and therefore needs to go into the system.webserver section in the web.config:

<system.webServer>
    <httpErrors errorMode="Custom" existingResponse="Replace">
      <clear/>
      <error
        statusCode="404"
        path="/WebForms/Index.aspx"
        responseMode="ExecuteURL"/>
    </httpErrors>
<system.webServer/>

It allows more configuration than customErrors but has its own little caveats. I'll try to explain the most important settings in a nutshell:

httpErrors can be inherited from a higher level (e.g. set in the machine.config)
Use the <remove/> tag to remove an inherited setting for a specific error code.
Use the <clear/> tag to remove all inherited settings.
Use the <error/> tag to configure the behaviour for one error code.
responseMode "ExecuteURL" will render a dynamic page with status code 200.
The workaround to set the correct error code in the .aspx page works here as well.
responseMode "Redirect" will redirect with HTTP 302 to a URL.
responseMode "File" will preserve the original error code and output a static file.
.aspx files will get output in plain text.
.html files will render as expected.
The main advantage of httpErrors is that it is handled on an IIS level. It will literally pick up all error codes and redirect to a friendly error page. If you want to benefit from master pages I would recommend to go with the ExecuteURL approach and status code fix. If you want to have rock solid error pages which IIS can serve even when everything else burns, then I'd recommend to go with the static file approach (preferably .html files).

Use case


This is currently the best place to configure friendly error pages in one location and to catch them all. The only reason not to use httpErrors is if you are still running on an older version of IIS (< 7.0).

Custom HttpModule


Last but not least I would like to quickly touch on custom HttpModules in ASP.NET. A custom HttpModule is not very useful for friendly error pages, but it is a great location to put global error logging in one place.

With a HttpModule you can subscribe to the OnError event of the HttpApplication object and this event behaves same way as the Application_Error event from the Global.asax.cs file. However, if you have both implemented then the one from the HttpModule gets called first.

The benefit of the HttpModule is that it is reusable in other ASP.NET applications. Adding/Removing a HttpModule is as simple as adding or removing one line in your web.config:

<system.webServer>
    <modules>
        <add name="CustomModule" type="SampleApp.CustomModule, SampleApp"/>
    </modules>
</system.webSe
rver>

 

 


HostForLIFE.eu ASP.NET MVC 5 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.

 



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: How to Add a Video in ASP.NET MVC 5?

clock April 15, 2016 21:45 by author Anthony

In this tutorial, you’re going to learn how to add video using Entity Framework. We will be building a form for adding a new video to the database.Step 1: Creating a Page to Add a Video

Before we get started, let’s take a closer look at routing.

Earlier I told you that the routing engine determines the name of the controller and the action from the URL of the request. The default rule (or the default convention) targets a URL with the pattern /controller/action/id. Here both action and id are optional. If action is not specified, Index is assumed as the action name.

For the purpose of this section, we need a new page for the user to add a new video. To do this, we’re going to create a new action that responds to a URL like /videos/new. Inside this action, we’ll return a view which will include a data entry form for adding a video.

First, go to VideosController and create a new action like this:
public ActionResult New()
{
    return View();
}

All we do here is simply return a view. Let’s create the corresponding view. In Solution Explorer, expand the Views folder, right-click the Videos folder, and go to Add > View…. Set the name of the view to New and make sure _Layout.cshtml is selected as the layout (similar to the last section).

image09

Next, set the model behind this view on the top:

@model Beaver.Models.Video

We set the model to the Video because we’re going to capture a Video object in this form.
@using (Html.BeginForm("Add", "Videos", FormMethod.Post, new { @class = "form" }))
{

}



Here we are using Razor syntax (note the @) to write C# code. Html.BeginForm is a helper method, which we use to render an HTML form element. It returns an instance of MvcForm, which is a disposable object. By wrapping it inside a using block, we can ensure that it will be properly disposed.

The first and second arguments specify the name of the action and controller that will be called when we post this form. In this case, we expect an action named Add in our VideosController to be called. We haven’t created this action yet, but we’ll do so soon.

The third argument specifies the form method. In HTML forms, we have two methods: GET and POST. When sending data for modification to the server, we should always use the POST method.

The last argument is an anonymous object ( new {} ) that specifies any additional attributes to add to the HTML markup. So, when this code is executed, the view engine will render something like this:

<form action=”/videos/add” method=”post” class=”form”>
</form>

We use the form CSS class to give a nice, modern look to our forms. This CSS class is defined in Bootstrap, which is a CSS framework for building modern and responsive (mobile- and tablet-friendly) web applications. When you create an ASP.NET MVC project in Visual Studio, Bootstrap is automatically added for you.

We added the form. Now, we need to add three input fields in this form: Title, Description and Genre. Write this code inside the using block:Now, write the following code in the view to create an HTML form element:
 <div class="form-group">
        @Html.LabelFor(m => m.Title)
        @Html.TextBoxFor(m => m.Title, new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Description)
        @Html.TextAreaFor(m => m.Description, new { @class = "form-control", rows = 4 })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Genre)
        @Html.EnumDropDownListFor(m => m.Genre, new { @class = "form-control" })
    </div>

Here we have three sections, each wrapped with a div with a form-group class. Again, this is one of the classes that is defined in Bootstrap. If you follow Botostrap’s markup, you always get a nice, clean form that renders well both on the desktop and on mobile devices.

Inside each form-group, we have a label and an input field. Look at the first form-group.

<div class="form-group">
    @Html.LabelFor(m => m.Title)
    @Html.TextBoxFor(m => m.Title, new { @class = "form-control" })
</div>

We’re using Html.LabelFor to render a label for the Title property of the Video class.

@Html.LabelFor(m => m.Title)

The expression m => m.Title is a lambda expression that we use to access a property in the model of this view. If you’re not familiar with lambda expressions, check out my C# Advanced course on Udemy. When this line is executed by the view engine, we’ll get an HTML markup like this:

<label for=”Title”>Title</label>
Next, we use Html.TextBoxFor helper method to render a text box.

@Html.TextBoxFor(m => m.Title, new { @class = "form-control" })
Again, we use a lambda expression to specify the target property. Also, note that the second argument to this method is an anonymous object that specifies any additional attributes to add to the markup, in this case form-control CSS class. This is another Bootstrap class that gives our text boxes a bit of padding, round corners and a nice effect when the input is in focus. The result will be HTML markup like this:

<input type=”text” id=”Title” name=”Title” class=”form-control”></input>
Now you read the second form-group.

<div class="form-group">
        @Html.LabelFor(m => m.Description)
        @Html.TextAreaFor(m => m.Description, new { @class = "form-control", rows = 4 })
    </div>

It’s very similar to the first one, except that here we use the Html.TextAreaFor helper method to render a textarea input element instead of a text box. This allows the user to write a description that is more than one line.

And finally, in the third form-group, we use a different helper method (Html.EnumDropDownListFor) to render a drop-down list for the Genre property, which is an enum:

<div class="form-group">
        @Html.LabelFor(m => m.Genre)
        @Html.EnumDropDownListFor(m => m.Genre, new { @class = "form-control" })
    </div>

For the last step, we need a button to submit the form. Add this markup inside the using block, after all form groups:

<input type="submit" class="btn btn-primary" value="Save" />
Here, btn and btn-primary are both Bootstrap classes that make our buttons look cool and modern.

Your entire using block should look like this:

@using (Html.BeginForm("Add", "Videos", FormMethod.Post, new { @class = "form" }))
{
    <div class="form-group">
        @Html.LabelFor(m => m.Title)
        @Html.TextBoxFor(m => m.Title, new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Description)
        @Html.TextAreaFor(m => m.Description, new { @class = "form-control", rows = 4 })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Genre)
        @Html.EnumDropDownListFor(m => m.Genre, new { @class = "form-control" })
    </div>

    <input type="submit" class="btn btn-primary" value="Save" />
}

Now it’s time to review what we have done. Run the application with Ctrl+F5 and look at the form we’ve built:

Note how the input fields and the button look. This is all because of the beautiful styles defined in Bootstrap.
In this step, we added a new action to our controller that returned a view. We created a view with a form to add a video.

 


HostForLIFE.eu ASP.NET MVC 5 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: ASP.NET MVC 5 Scaffolding

clock April 14, 2016 20:19 by author Anthony

ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. It makes it easy to add boilerplate code to your project that interacts with a data model.

In previous versions of Visual Studio, scaffolding was limited to ASP.NET MVC projects. With Visual Studio 2013, you can now use scaffolding for any ASP.NET project, including Web Forms. Visual Studio 2013 does not currently support generating pages for a Web Forms project, but you can still use scaffolding with Web Forms by adding MVC dependencies to the project. Support for generating pages for Web Forms will be added in a future update.

When using scaffolding, we ensure that all required dependencies are installed in the project. For example, if you start with an ASP.NET Web Forms project and then use scaffolding to add a Web API Controller, the required NuGet packages and references are added to your project automatically. To add MVC scaffolding to a Web Forms project, add a New Scaffolded Item and select MVC 5 Dependencies in the dialog window. There are two options for scaffolding MVC; Minimal and Full. If you select Minimal, only the NuGet packages and references for ASP.NET MVC are added to your project. If you select the Full option, the Minimal dependencies are added, as well as the required content files for an MVC project.

Support for scaffolding async controllers uses the new async features from Entity Framework 6.This Article shows how to use Scaffolding With your ASP.net MVC 5 Application.

Step 1 :

  • Let's create an ASP.net MVC 5 web application in Visual Studio 2013 and name it as ScaffoldingMVC5.

Scaffolding With ASP.net MVC 5

Step 2 :

  • Right click your Controllers folder and Add New Scaffolded Item is as below.

  • Scaffolding With ASP.net MVC 5


Step 3 :

  • From the Add Scaffold window, select the MVC 5 Controller with views,using Entity Framework scaffold template.

  • Scaffolding With ASP.net MVC 5

Step 4 :

  • The Add Controller window,you can give the name of your Controller (e.g. PetController),select your model class (e.g. Pet) and also you can create the Data context class (e.g. DataContext) as below. 
  • All other options are put as default.
  • After that click Add button.
  • When you click the New data context.. button  on Add Controller box above,it will pop up the below New Data Context box.
  • From there you can give a name for your Data context is as below.
  • e.g. DataContext

Scaffolding With ASP.net MVC 5


Step 5 :

  • The solution tree shows the relevant classes and pages were created for above example.
  • For example, the following image shows the MVC controller (i.e. PetController) and Views (i.e. Inside the Pet folder) that were created through scaffolding for a Model class named Pet.
  • Scaffolding With ASP.net MVC 5

 

HostForLIFE.eu ASP.NET MVC 5 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: ASP.NET MVC 5 Custom Filter

clock April 1, 2016 21:37 by author Anthony

UNDERSTANDING ASP.NET MVC

ASP.NET MVC is the implementation of the MVC architecture to the programming framework. ASP.NET physically is library consisting of some assembly that can be installed on top .NET Framework 3.5. ASP.NET MVC was created as an option for developers who like MVC architecture. ASP.NET MVC did not replace Web Forms architecture that has been known and used by developers ASP.NET. The main components of ASP.NET MVC still the same as the basic architecture of MVC, the Model, View, and Controller. Some of the additional component is a web server, Routing, and dispatchers. Web server always bridging the interaction between the user with a web program. We can use the IIS web server, or a personal web server as long as the program is still in the development phase. IIS versions that can be used vary from version 5 to version 7.

ASP.NET MVC 5 Provides five different kinds of Filters. They are :

  • Authentication
  • Authorization
  • Action
  • Result
  • Exception

Filters are used to inject logic at the different levels of request processing. Let us understand where at the various stages of request processing different filters get applied. Authentication Authorization filter runs after the filter and before any other filter or action method. Action filter runs before and after any action method. Result filter runs before and after execution of any action result. Exception filter runs only if action methods, filters or action results throw an exception.

An action filter consists of codes that run either before or after an action runs. It can be used for tasks like logging, privileged based authorization, authentication, caching etc. Creating a custom action filter is very easy. It can be created in four simple steps:

  • Create a class
  • Inherit ActionFilterAttribute class
  • Override the OnActionExecuting method to run logic before the action method
  • Override the OnActionExecuted method to run logic after the action method

The purpose of the action filter is to find whether a logged in user belongs to a particular privileges or not. On the basis of the result, a user will access a particular action or navigate to the login action. To do this, I have created a class and extended the ActionFilterAttribute class.

using PrivilegeDemo.Services;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using System.Web.Routing;
 
namespace PrivilegeDemo.Filters
{
    public class AuthorizationPrivilegeFilter : ActionFilterAttribute
    {
      
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
         
            AuthorizationService _authorizeService = new AuthorizationService();
            string userId = HttpContext.Current.User.Identity.GetUserId();
            if (userId != null)
            {
                var result = _authorizeService.CanManageUser(userId);
                if (!result)
                {
 
                    filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary{{ "controller", "Account" },
                                          { "action", "Login" }
 
                                         });
                }
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary{{ "controller", "Account" },
                                          { "action", "Login" }
 
                                         });
 
            }
            base.OnActionExecuting(filterContext);
        }
 
 
    }
}

 

The OnActionExecuting method is overridden because we want the code to execute before the action method gets executed. Once the action filter is created, it can be used in three ways:

  • As Global filter
  • As Controller
  • As Action

By adding a filter to the global filter in App_Start\FilterConfig it will be available globally to the entire application.

public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
           filters.Add(new AuthorizationPrivilegeFilter());
        }
    }

By adding a filter to a particular Controller it will also be available to the all actions of that particular controller.

[AuthorizationPrivilegeFilter]
    public class HomeController : Controller
    {

Adding a filter to a particular action it will be available to the particular action.

[AuthorizationPrivilegeFilter]
        public ActionResult About()
        {

 

 

HostForLIFE.eu ASP.NET MVC 5 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: How to Make ASP.NET MVC 5 Run in Ubuntu?

clock March 31, 2016 18:04 by author Anthony

ASP.NET is a programming framework to create web application server side. ASP.NET using C # code is well structured so it is easy to understand and repair. C # also provides a variety of code hint, hint error before the code is executed. C # is executed using JIT system, so it may be able to run faster than interpreted languages like PHP.

But until a few years ago ASP.NET can only run on windows platform. Because there are some who still is Microsoft's patents, these projects difficult to run optimally and tend to be limited compatibility, even dotGNU project to a halt in 2012. So today I will discuss about how to run ASP.NET MVC 5 on Ubuntu Linux.

Before that some things need to be prepared, such as:

  • Computers with 14:04 LTS Ubuntu operating system.
  • ASP.NET MVC 5 that has been published.
  • Internet connection.

How to Make ASP.NET MVC 5 Run in Ubuntu?

  • Make sure that your operating system has been updated by running the following command:
    sudo apt-get update && sudo apt-get dist-upgrade
  • Install apache2 package by running the command:
    sudo apt-get install apache2
  • Input Mono into the system package list, this needs to be done so that the mono version that will be installed up to date. make sure you run the code below line by line.
    sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
    sudo echo "deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list
    sudo echo "deb http://download.mono-project.com/repo/debian wheezy-apache24-compat main" | sudo tee -a /etc/apt/sources.list.d/mono-xamarin.list
    sudo echo "deb http://download.mono-project.com/repo/debian alpha main" | sudo tee /etc/apt/sources.list.d/mono-xamarin-alpha.list
    sudo apt-get update && sudo apt-get dist-upgrade
  • Install mono-complete package
    sudo apt-get install mono-complete
  • Install libapache2-mod-mono package
    sudo apt-get install libapache2-mod-mono
    sudo a2enmod mod_mono_auto
  • Set apache2, so that the apache2 folder using mono. This procedure must be repeated for each new application
    sudo nano /etc/apache2/sites-available/testasp.conf
  • Copy-paste the following lines into the console, adjust the path and name if necessary. click ctrl + o, enter the ctrl + x to save the file.
    Alias /testasp "/var/www/html/testasp"
    MonoServerPath inventory "/usr/bin/mod-mono-server4"
    MonoDebug inventory true
    MonoSetEnv inventory MONO_IOMAP=all
    MonoApplications inventory "/testasp:/var/www/html/testasp"
    <Location "/testasp">
    Allow from all
    Order allow,deny
    MonoSetServerAlias inventory
    SetHandler mono
    SetOutputFilter DEFLATE
    SetEnvIfNoCase Request_URI "\.(?:gif|jpe?g|png)$" no-gzip dont-vary
    </Location>
    <IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/javascript
    </IfModule>

  • Create a new folder in the / var / www / html / testasp, adjust permissions folder if necessary. Asp.net files will be stored here.
    sudo mkdir /var/www/html/testasp
  • Enable configuration site that have been created.
    sudo a2ensite testasp
    sudo service apache2 restart
  • Upload or copy the files you want to run ASP.NET MVC into the folder / var / www / html / testasp.
  • Test sites in the browser, adjust your url with IP engine.
  • Done. You have been successfully run ASP.NET MVC 5 on the Linux operating system.

 

HostForLIFE.eu ASP.NET MVC 5 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



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