ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET 4.5 HOSTING - ASPHostPortal.com :: A simple SPA with AngularJs, ASP.NET MVC, Web API and EF

clock November 14, 2014 06:41 by author Mark

Introduction

SPA stands for Single Page Application. Here I will demonstrate a simple SPA with ASP.NET MVC, Web API and Entity Framework. I will show a trainer profile and its CRUD operation using AngularJS, ASP.NET MVC, Web api and Entity Framework.

Step 1: Create a ASP.NET MVC application with empty template

  • Open visual studio, Got to File->New->Project
  • Select Template -> Visual C# -> Web -> ASP.NET MVC 4 Web application and click OK
  • Select Empty Template and Razor as view engine

Step 2: Install required packages

Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

  • PM> Install-Package jQuery
  • PM> Install-Package angularjs -Version 1.2.26
  • PM> Install-Package Newtonsoft.Json
  • PM> Install-Package MvcScaffolding

Step 3: Create Connection String

Create connection string and name DB name as SPADB
    <connectionStrings>
  <add name="SPAContext" connectionString="Data Source=.\sqlexpress;Initial Catalog=SPADB;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>

Step 4: Create model

Create Trainer model
    public class Trainer
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Venue { get; set; }
}

Step 5: Create Repository

Create repository for Trainer model.

Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to create repository. I used repository pattern for well-structured and more manageable.

PM> Scaffold Repository Trainer

After running the above command you will see SPAContext.cs and TrainerRepository.cs created in Model folder. For well manageability, I create a directory name Repository and put these two files in the Repository folder. So change the namespace as like SPA.Repository instead of SPA.Model. I also create a UnitOfWork for implement unit of work pattern.
The overall folder structure looks like following. 
SPAContext.cs
    public class SPAContext : DbContext
{
    public SPAContext()
        : base("SPAContext")
    {
    }
    // You can add custom code to this file. Changes will not be overwritten.
    //
    // If you want Entity Framework to drop and regenerate your database
    // automatically whenever you change your model schema, add the following
    // code to the Application_Start method in your Global.asax file.
    // Note: this will destroy and re-create your database with every model change.
    //
    // System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<SPA.Models.SPAContext>());
    public DbSet<SPA.Models.Trainer> Trainers { get; set; }
    public DbSet<SPA.Models.Training> Trainings { get; set; }
}

TrainerRepository.cs
    public class TrainerRepository : ITrainerRepository
{
    SPAContext context = new SPAContext();
    public TrainerRepository()
        : this(new SPAContext())
    {
    }
    public TrainerRepository(SPAContext context)
    {
        this.context = context;
    }
    public IQueryable<Trainer> All
    {
        get { return context.Trainers; }
    }
    public IQueryable<Trainer> AllIncluding(params Expression<Func<Trainer, object>>[] includeProperties)
    {
        IQueryable<Trainer> query = context.Trainers;
        foreach (var includeProperty in includeProperties)
        {
            query = query.Include(includeProperty);
        }
        return query;
    }
    public Trainer Find(long id)
    {
        return context.Trainers.Find(id);
    }
    public void InsertOrUpdate(Trainer trainer)
    {
        if (trainer.Id == default(long))
        {
            // New entity
            context.Trainers.Add(trainer);
        }
        else
        {
            // Existing entity
            context.Entry(trainer).State = System.Data.Entity.EntityState.Modified;
        }
    }
    public void Delete(long id)
    {
        var trainer = context.Trainers.Find(id);
        context.Trainers.Remove(trainer);
    }
    public void Save()
    {
        context.SaveChanges();
    }
    public void Dispose()
    {
        context.Dispose();
    }
}
public interface ITrainerRepository : IDisposable
{
    IQueryable<Trainer> All { get; }
    IQueryable<Trainer> AllIncluding(params Expression<Func<Trainer, object>>[] includeProperties);
    Trainer Find(long id);
    void InsertOrUpdate(Trainer trainer);
    void Delete(long id);
    void Save();
}

UnitOfWork.cs
public class UnitOfWork : IDisposable
{
    private SPAContext context;
    public UnitOfWork()
    {
        context = new SPAContext();
    }
    public UnitOfWork(SPAContext _context)
    {
        this.context = _context;
    }
    private TrainingRepository _trainingRepository;
 
    public TrainingRepository TrainingRepository
    {
        get
        {
            if (this._trainingRepository == null)
            {
                this._trainingRepository = new TrainingRepository(context);
            }
            return _trainingRepository;
        }
    }
    private TrainerRepository _trainerRepository;
    public TrainerRepository TrainerRepository
    {
        get
        {
            if (this._trainerRepository == null)
            {
                this._trainerRepository = new TrainerRepository(context);
            }
            return _trainerRepository;
        }
    }
    public void Dispose()
    {
        context.Dispose();
        GC.SuppressFinalize(this);
    }
}

Step 6: Add migration

  • Run the following command to add migration
  • PM> Enable-Migrations
  • PM> Add-Migration initialmigration
  • PM> Update-Database –Verbose

Step 7: Create API Controllers

Create Trainers api Controllers by clicking right button on Controller folder and scaffold as follows.

Step 8: Modify Controllers

Now modify the controllers as follows. Here I used unit of work pattern.
    public class TrainersController : ApiController
{
    private UnitOfWork unitOfWork = new UnitOfWork();
    public IEnumerable<Trainer> Get()
    {
        List<Trainer> lstTrainer = new List<Trainer>();
        lstTrainer = unitOfWork.TrainerRepository.All.ToList();
        return lstTrainer;
    }
    //// GET api/trainers/5
    public Trainer Get(int id)
    {
        Trainer objTrainer = unitOfWork.TrainerRepository.Find(id);
        return objTrainer;
    }
    public HttpResponseMessage Post(Trainer trainer)
    {
        if (ModelState.IsValid)
        {
            unitOfWork.TrainerRepository.InsertOrUpdate(trainer);
            unitOfWork.TrainerRepository.Save();
            return new HttpResponseMessage(HttpStatusCode.OK);
        }
        return new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
    private IEnumerable<string> GetErrorMessages()
    {
        return ModelState.Values.SelectMany(x => x.Errors.Select(e => e.ErrorMessage));
    }
    // PUT api/trainers/5
    public HttpResponseMessage Put(int Id, Trainer trainer)
    {
        if (ModelState.IsValid)
        {
            unitOfWork.TrainerRepository.InsertOrUpdate(trainer);
            unitOfWork.TrainerRepository.Save();
            return new HttpResponseMessage(HttpStatusCode.OK);
        }
        else
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
    // DELETE api/trainers/5
    public HttpResponseMessage Delete(int id)
    {
        Trainer objTrainer = unitOfWork.TrainerRepository.Find(id);
        if (objTrainer == null)
        {
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }
        unitOfWork.TrainerRepository.Delete(id);
        unitOfWork.TrainerRepository.Save();
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

Step 9: Create Layout and Home Controller

Create _Layout.cshtml in Views->Shared folder and create HomeController and create inext view of Home controller by right click on index action and add view. You will see index.cshtml is created in Views->Home
Home Controller
    public class HomeController : Controller
{
    //
    // GET: /Home/
 
    public ActionResult Index()
    {
        return View();
    }
}

_Layout.cshtml
    <html ng-app="registrationModule">
<head>
    <title>Training Registration</title>
</head>
<body>
    @RenderBody()
</body>
</html>
Index.cshtml
    @{
    ViewBag.Title = "Home";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Home</h2>
<div>
    <ul>     
        <li><a href="/Registration/Trainers">Trainer Details</a></li>
        <li><a href="/Registration/Trainers/add">Add New Trainer</a></li>
    </ul>
</div>
<div ng-view></div>

Step 10: Create registrationModule

Create registrationModule.js in Scripts->Application. This is for angularjs routing.
    var registrationModule = angular.module("registrationModule", ['ngRoute', 'ngResource'])
    .config(function ($routeProvider, $locationProvider) {
        $routeProvider.when('/Registration/Trainers', {
            templateUrl: '/templates/trainers/all.html',
            controller: 'listTrainersController'
        });
        $routeProvider.when('/Registration/Trainers/:id', {
            templateUrl: '/templates/trainers/edit.html',
            controller: 'editTrainersController'
        });
        $routeProvider.when('/Registration/Trainers/add', {
            templateUrl: '/templates/trainers/add.html',
            controller: 'addTrainersController'
        });
        $routeProvider.when("/Registration/Trainers/delete/:id", {
            controller: "deleteTrainersController",
            templateUrl: "/templates/trainers/delete.html"
        });
        $locationProvider.html5Mode(true);
    });

Step 11: Create trainerRepository

Create trainerRepository.js in Scripts->Application->Repository. This increase manageability for large application.
    'use strict';
//Repository for trainer information
registrationModule.factory('trainerRepository', function ($resource) {
    return {
        get: function () {
            return $resource('/api/Trainers').query();
        },
        getById: function (id) {
            return $resource('/api/Trainers/:Id', { Id: id }).get();
        },
        save: function (trainer) {
            return $resource('/api/Trainers').save(trainer);
        },
        put: function (trainer) {
            return $resource('/api/Trainers', { Id: trainer.id },
                {
                    update: { method: 'PUT' }
                }).update(trainer);
        },
        remove: function (id) {
            return $resource('/api/Trainers').remove({ Id: id });
        }
    };
});

Step 12: Create trainerController

Create trainerController.js in Scripts->Application->Controllers
    'use strict';
//Controller to get list of trainers informaion
registrationModule.controller("listTrainersController", function ($scope, trainerRepository, $location) {
    $scope.trainers = trainerRepository.get();
});
//Controller to save trainer information
registrationModule.controller("addTrainersController", function ($scope, trainerRepository, $location) {
    $scope.save = function (trainer) {
        trainer.Id = 0;
        $scope.errors = [];
        trainerRepository.save(trainer).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
    };
});

//Controller to modify trainer information
registrationModule.controller("editTrainersController", function ($scope,$routeParams, trainerRepository, $location) {
    $scope.trainer = trainerRepository.getById($routeParams.id);
    $scope.update = function (trainer) {
        $scope.errors = [];
        trainerRepository.put(trainer).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
    };
});
//Controller to delete trainer information
registrationModule.controller("deleteTrainersController", function ($scope, $routeParams, trainerRepository, $location) {
        trainerRepository.remove($routeParams.id).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
});

Step 13: Create templates

Create all.html, add.html, edit.html, delete.html in templateds->trainers folder.
All.html
    <div>
    <div>
        <h2>Trainers Details</h2>
    </div>
</div>
<div>
    <div>
        <table>
            <tr>
                <th>Name </th>
                <th>Email </th>
                <th>Venue </th>
                <th>Action</th>
            </tr>
            <tr ng-repeat="trainer in trainers">
                <td>{{trainer.name}}</td>
                <td>{{trainer.email}}</td>
                <td>{{trainer.venue}}</td>
                <td>
                    <a title="Delete" ng-href="/Registration/Trainers/delete/{{trainer.id}}">Delete</a>
                    |<a title="Edit" ng-href="/Registration/Trainers/{{trainer.id}}">Edit</a>
                </td>
            </tr>
        </table>
    </div>
</div>

Add.html
    <form name="trainerForm" novalidate ng-submit="save(trainer)">
    <table>
        <tbody>
            <tr>
                <td>Trainer Name
                </td>
                <td>
                    <input name="name" type="text" ng-model="trainer.name" required ng-minlength="5" />
                </td>
            </tr>
            <tr>
                <td>Email
                </td>
                <td>
                    <input name="email" type="text" ng-model="trainer.email" />
                </td>
            </tr>
            <tr>
                <td>Venue
                </td>
                <td>
                    <input name="venue" type="text" ng-model="trainer.venue" />
                </td>
            </tr>
            <tr>
                <td class="width30"></td>
                <td>
                    <input type="submit" value="Save" ng-disabled="trainerForm.$invalid" />
                    <a href="/Registration/Trainers" class="btn btn-inverse">Cancel</a>
                </td>
            </tr>
        </tbody>
    </table>
</form>
Edit.html
    <form name="trainerFrom" novalidate abide>
    <table>
        <tbody>
            <tr>
                <td>
                    <input name="id" type="hidden" ng-model="trainer.id"/>
                </td>
            </tr>
            <tr>
                <td>Name
                </td>
                <td>
                    <input name="name" type="text" ng-model="trainer.name" />
                </td>
            </tr>
            <tr>
                <td>Email
                </td>
                <td>
                    <input name="email" type="text" ng-model="trainer.email" />
                </td>
            </tr>
            <tr>
                <td>Venue
                </td>
                <td>
                    <textarea name="venue" ng-model="trainer.venue"></textarea>
                </td>
            </tr>
            <tr>
                <td class="width30"></td>
                <td>
                    <button type="submit" class="btn btn-primary" ng-click="update(trainer)" ng-disabled="trainerFrom.$invalid">Update</button>
                </td>
            </tr>
        </tbody>
    </table>
</form>

Step 14: Add references to the Layout

Modify the _Layout.cshtml to add references
_Layout.cshtml
    <html ng-app="registrationModule">
<head>
    <title>Training Registration</title>
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Scripts/angular-resource.min.js"></script>
    <script src="~/Scripts/angular-route.min.js"></script>
    <script src="~/Scripts/jquery-2.1.1.min.js"></script>
    <script src="~/Scripts/Application/registrationModule.js"></script>
    <script src="~/Scripts/Application/Repository/trainerRepository.js"></script>
    <script src="~/Scripts/Application/Controllers/trainersController.js"></script>
</head>
<body>
    @RenderBody()
</body>
</html>

Now run you application and add, delete, modify and get all trainer information. Thanks for your patient! Laughing



ASP.NET 4.5 HOSTING - ASPHostPortal :: Design application layout by bootstrap theme

clock November 12, 2014 06:48 by author Mark

To design layout of your web site is much more cumbersome. But you can easily design your website layout by bootstrap, you can make it responsive also.

Step 1: Create a ASP.NET MVC application with empty template

  • Open visual studio, Got to File->New->Project
  • Select Template -> Visual C# -> Web -> ASP.NET MVC  Web application and click OK
  • Select Empty Template and Razor as view engine

Step 2: Install required packages

  • Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

PM> Install-Package bootstrap

Step 3: Download bootstrap theme

  • Go to http://bootswatch.com/ . Download any theme (bootstrap.css) like below and pest the content in Contents -> bootstrap-main-theme.css file

Step 4: Create a Layout page

  • Create a _Layout.cshtml in Views->Shared folder and add the following references.

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <title>Bootstrap theme test</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/bootstrap-main-theme.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
 </head>
<body>  
    <div>
        @RenderBody()
    </div>
</body>
</html>

Step 5: Create HomeController and index view

  • Create HomeController and create index view. Right click on index action of home controller you will see index.cshtml file created in Views->Home folder. Modify the index.cshtml file like following

Index.cshtml

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 <h2>Home Page</h2>

Step 6: Add Navigation bar

  • If you go the preview of the theme you will see some sample code or documentation. You can customize later. To add navigation bar to the website I modify the _Layout.cshtml like following.

_Layout.cshtml

<!DOCTYPE html>
 <html>
<head>
    <title>Bootstrap theme test</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/bootstrap-main-theme.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
 </head>
<body>
    <div class="navbar navbar-inverse">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-inverse-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>
  <div class="navbar-collapse collapse navbar-inverse-collapse">
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Active</a></li>
      <li><a href="#">Link</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li class="dropdown-header">Dropdown header</li>
          <li><a href="#">Separated link</a></li>
          <li><a href="#">One more separated link</a></li>
        </ul>
      </li>
    </ul>
    <form class="navbar-form navbar-left">
      <input type="text" class="form-control col-lg-8" placeholder="Search">
    </form>
    <ul class="nav navbar-nav navbar-right">
      <li><a href="#">Link</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li><a href="#">Separated link</a></li>
        </ul>
      </li>
    </ul>
  </div>
</div>
    <div>
        @RenderBody()
    </div>
</body>
</html>

Now run the application, you will get a nice layout. Thanks for your patient Smile



ASP.NET 4.5 Hosting - ASPHostPortal.com :: How to use Rangevalidator control in ASP.NET 4.5

clock November 7, 2014 06:26 by author Mark

If you want to understand how RangeValidator  control work in ASP.NET 4.5 Now, we will discuss about How to Use Rangevalidator control in ASP.NET 4.5. Rangevalidator control is used to check if the value is within a specified range of values. For example, Rangevalidator can be used to check if the age between 1 until 100.

In the codesnippet below, TextBox txtAge get age of the person. If User fill with any number that isn’t between 1 – 100 the validation fails. The minimum and maximum value for the age is specified by MinimumValue and MaximumValue properties. Since, Age is an integer, the Type is specified as integer. Write the code below:

&lt;asp:TextBox ID="txtAge" runat="server"&gt;&lt;/asp:TextBox&gt;
&lt;asp:RangeValidator ID="RangeValidator1" runat="server"
    ErrorMessage="Age must be between 1 &amp; 100"
    MinimumValue="1" MaximumValue="100"
    ControlToValidate="txtAge" Type="Integer" &gt;
&lt;/asp:RangeValidator&gt;

Properties for Rangevalidator control:

Type – Specifies the data type of the value to check. Data types supported include Currency, Date, Double, Integer and String.

MinimumValue – Minimum value that allowed

MaximumValue – Max value allowed in that field

The Rangevalidator only checks if the data is within the allowed range. If you wanna check for a required field, use RequiredFieldValidator. In the Age field, I am using both RequiredFieldValidator & RangeValidator. In this example I am using the Display property. If the Display property is not set, or, if it is set to static, then the error message will be rendered, with style visibility:hidden. Then the error message will always occupy the gap on the screen even if the validation passes.

<table>
    <tr>
        <td>
            <b>Age</b>
        </td>
        <td>
            :<asp:TextBox ID="txtAge" runat="server" Width="150px">
                </asp:TextBox>
            <asp:RangeValidator ID="RangeValidatorAge" runat="server"
                ErrorMessage="Age must be between 1 & 100"
                MinimumValue="1" MaximumValue="100"
                ControlToValidate="txtAge" Type="Integer"
                ForeColor="Red" Display="Dynamic">
            </asp:RangeValidator>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorAge"
            runat="server" ErrorMessage="Age is required"
            ControlToValidate="txtAge" ForeColor="Red"
            Display="Dynamic" >
            </asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            <b>Date Available</b>
        </td>
        <td>
            :<asp:TextBox ID="txtDateAvailable" runat="server" Width="150px">
            </asp:TextBox>
            <asp:RangeValidator ID="RangeValidatorDateAvailable" runat="server"
                ErrorMessage="Date must be between 01/01/2012 & 31/12/2012"
                MinimumValue="01/01/2012" MaximumValue="31/12/2012"
                ControlToValidate="txtDateAvailable" Type="Date"
                ForeColor="Red">
            </asp:RangeValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Button ID="btnSave" runat="server" Text="Save" Width="100px"
                onclick="btnSave_Click" />
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Label ID="lblStatus" runat="server" Font-Bold="true">
            </asp:Label>
        </td>
    </tr>
</table>

This pushes “Age is Required” error message to the correct. To correct this we’ve got set Display=”Dynamic”. This renders the error message with style display:none. If a tag has this style, it’ll not occupy space when not visible.
Code-Behind page code
:
protected void btnSave_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        lblStatus.ForeColor = System.Drawing.Color.Green;
        lblStatus.Text = "Data Saved successfully";
    }
    else
    {
        lblStatus.ForeColor = System.Drawing.Color.Red;
        lblStatus.Text = "Validation Failed! Data not saved";
    }
}

Display property is supported by all validation controls

None – Error message not rendered and displayed next to the control. used to show the error message only within the ValidationSummary control

Static – The error message is displayed next to the control if validation fails. space is reserved on the page for the message although validation succeeds. The span tag is rendered with style visibility:hidden

Dynamic – The error message is displayed next to the control if validation fails. space isn’t reserved on the page for the message if the validation succeeds. The span tag is rendered with style display:none.

 

 

 



ASP.NET 4.5 Hosting - ASPHostPortal.com :: Page Instrumentation in ASP.NET 4.5

clock December 27, 2013 11:03 by author Robert

 

In this article, I showed you how to use Page Instrumentation, a new  feature in ASP.NET 4.5 which might be useful for you during debugging.
ASP.NET 4.5 include a hidden gem called Page Instrumentation, very few people aware of this gem. You can use page instrumentation in ASP.NET 4.5 WebForm and MVC 5 or 4(assuming it targets 4.5). It allows you to inspect/instrument a web form or a mvc view during the rendering process. Page instrumentation are useful in scenarios when you have some performance issues regarding view engine rendering. In this article, I will show you how to use this feature in ASP.NET 4.5.

To start instrumenting a page, you need to inherit PageExecutionListener class.

The BeginContext will be called by a view engine before it renders the output for the specified context. Similarly, EndContext called by a view engine after it renders the output for the specified context. Both of these methods accept PageExecutionContext class as a parameter which have the following members.

All the properties of PageExecutionContext class are self explanatory. Let assume we have the following MVC view(for understanding how many times and when the BeginContext and EndContext will be invoke by the framework).

The Razor View Engine will emit the following C# code


Finally, here is a simple implementation of PageExecutionListener class which calculates the total time each time whenever something is written to the output response.

 



ASP.NET 4.5 Hosting :: Regex (Regular Expressions) Time Out In ASP.NET 4.5

clock November 13, 2013 07:13 by author Ben

One of new features from ASP.NET 4.5 is Regex. Lets start by the new Regex Api introduced with the framework. The improvement that has been made is minor yet handy at certain cases. The Regex class of .NET 4.5 supports Timeout. Lets take a look how to work with it.

Lets try to write a simplest RegEx validator to look into it.



Here in the code you can see I simply check a string with a Regular expression. It eventually finds success as Pattern matches the string. Now this code is little different than what we have been doing for last few years. The constructor overload of Regex now supports a Timespan seed, which indicates the timeout value after which the Regular expression validator would automatically generate a RegexMatchTimeoutException. The Match defined within the Regex class can generate timeout after a certain time exceeds.

You can specify Regex.InfiniteMatchTimeout to specify that the timeout does not occur. The value of InfiniteMatchTimeout is -1ms internally and you can also use Timespan.Frommilliseconds(-1) as value for timespan which will indicate that the Regular expression will never timeout which being the default behavior of our normal Regex class. Regex also supports AppDomain to get default value of the Timeout. You can set timeout value for "REGEX_DEFAULT_MATCH_TIMEOUT" in AppDomain to set it all the way through the Regular expressions being used in the same AppDomain. Lets take a look how it works.



Now this works exactly the same as the previous one. Here the Regex(new feature of ASP.NET 4.5) constructor automatically checks the AppDomain value and applies it as default. If it is not present, it will take -1 as default which is Infinite TImeout and also if explicitely timeout is specified after the default value from AppDomain, the Regex class is smart enough to use the explicitly set value only to itself for which it is specified. The Regex Constructor generates a TypeInitializationException if appdomain value of Timespan is invalid. Lets check the internal structure.



This is the actual code that runs in background and generates the timeouts. Infact while scanning the string with the pattern, there is a call to CheckTimeout which checks whether the time specified is elapsed for the object. The CheckTimeout throws the exception from itself.

The Constructor sets DefaultMatchTimeout when the object is created taking it from AppDomain data elements.

If the pattern is supplied from external or you are not sure about the pattern that needs to be applied to the string, it is always recommended to use Timeouts. Basically you should also specify a rational limit of AppDomain regex default to ensure no regular expression can ever hang your application.

This is a small tip on the new Regex enhancements introduced with .NET 4.5 recently.  I hope you like it. More to come shortly.



ASP.NET 4.5 Hosting :: Strongly Typed Data Controls Value Provider ASP.NET 4.5

clock July 18, 2012 10:24 by author Jervis

Microsoft introduce new librarySystem.web.Binding. There are lots of new things. One of them isQueryStringAttribute class. With the help of this class we can send directly query string value to method.

Code


Step 1:
First we will create new Web Application in VS 2011.

Step 2:
Now we'll create public method which will return list of objects.

public IQueryable<Employee> GetEmployees([QueryString("id")]int id = 0)


{

     IList<Employee> custlist = new List<Employee>();
     custlist.Add(new Employee { ID = 1, Name = "Employee 1", Salary = 1000 });
     custlist.Add(new Employee { ID = 2, Name = "Employee 2", Salary = 2000 });
     custlist.Add(new Employee { ID = 3, Name = "Employee 3", Salary = 3000 });
     custlist.Add(new Employee { ID = 4, Name = "Employee 4", Salary = 4000 });
     custlist.Add(new Employee { ID = 5, Name = "Employee 5", Salary = 5000 });
     custlist.Add(new Employee { ID = 6, Name = "Employee 6", Salary = 6000 });
     custlist.Add(new Employee { ID = 7, Name = "Employee 7", Salary = 7000 });
     return custlist.AsQueryable<Employee>().Where(c => c.ID == id);
 }
 public class Employee

{

     public int ID { get; set; }
     public string Name { get; set; }
     public int Salary { get; set; }
 }

Step 3: Now we'll add Data control in aspx page. I have added GridView Control.

  <asp:GridView ID="GridView1" SelectMethod="GetEmployees" AutoGenerateColumns="true"
         PageSize="3" AllowPaging="true" AllowSorting="true" runat="server">
     </asp:GridView>

Step 4: Now we'll run our application and see the output.



Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what
ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.

- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.

- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.

- Data Center

ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.

- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.

- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.

- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.

 



ASP.NET 4.5 Hosting - ASPHostPortal :: Writing asynchronous HTTP Module in ASP.NET 4.5

clock July 16, 2012 06:51 by author Jervis

Today, I will discuss one of new features in ASP.NET 4.5, it is Asynchronous HTTP Module . And it’s going to be very useful if used meticulously.

First Just to give a brief Idea, why Asynchronous HTTPModules are important ?


As we all know, web is stateless. A Web page is created from scratch every time whenever it is posted back to the server. In traditional web programming, all the information within the page and control gets wiped off on every postback. Every request in ASP.NET goes through a series of events.


Every request is served by am HTTP handler and it goes a series of HTTPModules (HTTPPipeline) which can be read, update the request. A lot of features of ASP.NET like Authentication, Authorization, Session etc are implemented as HTTP Module in ASP.NET. Let’s have a view on the Request Processing.




Now as you can see the request is assigned to a thread T1 from the available threads is thread pool. And the request is passed through several HTTPModules and finally served my HTTPHandler and response is send back with the same thread (T1).


During the entire processing, same thread is engaged in serving the same request and cannot be used by any another request till request processing completes. During the request processing if any HTTPModules depends on some entities like I/O based operations, web services, Databases queries etc then it takes long to complete which makes the thread busy for long which makes asp.net thread will not do anything during that duration and will be useless. In this kind of scenarios the throughput goes down rapidly.


In the above scenario, synchronous HTTPModule can degrade the site performance a lot. So if we can make HTTPModules as asynchronous that can increase the through put a lot. In asynchronous mode, ASP.NET thread get released as soon as the control get passed to another component/module, it does not wait. And the thread becomes available in thread pool and can be used to serve another request. When the component completes its assigned task then it got assigned to new ASP.NET thread which completes the request. The flow can be graphically presented as




In the above picture, An asp.net thread T1 is assigned from threadpool to server the request. When the control got passed to File System to log message, asp.net thread got released and when essage logging got completed, control passed to asp.net and it is assigned to another thread say T2 from thread pool.

In .NET Framework 4.o, there was some major enhancement made for asynchronous programming model. Any asynchronous operation is represents a Task and it comes under the namespace System.Threading.Tasks.Task.

In .NET 4.5, there are some new operator and keyword introduced that makes the life easy for implement Asynchronous feature. One is async keyword and await operator.


These two enables us to write the asynchronous code is similar fashion as we write for synchronous mode.


And these features can be easily used while writing HTTPModules and HTTPHandlers. We’ll be using these enhancements in writing our custom asynchronous HTTPModule.


In my sample as depicted in image, I am creating a module that writes some log messages in a text file for every request made.


So to create a Custom
HTTPModule, Create a class library project. And create a class say named LogModule which implements IHttpModule. For this you need to add a reference of Assembly System.Web.

LogModule
would contains the methods discussed below.

We need to implement two methods
Init and Dispose that are part of IHTTPModule interface.

Here first , I have written an asynchronous method that actually reads the information from the request and writes in the log file asynchronously . For this I have used WriteAsync of FileStream


private async Task WriteLogmessages(object sender, EventArgs e)
{
    HttpApplication app = (HttpApplication)sender;
    DateTime time = DateTime.Now;

    string line = String.Format(
    "{0,10:d} {1,11:T} {2, 32} {3}\r\n",
    time, time,
    app.Request.UserHostAddress,
    app.Request.Url);
    using (_file = new FileStream(
        HttpContext.Current.Server.MapPath(
        "~/App_Data/RequestLog.txt"),
        FileMode.OpenOrCreate, FileAccess.Write,
        FileShare.Write, 1024, true))
    {
        line = line + " ," + threaddetails;
        byte[] output = Encoding.ASCII.GetBytes(line);

        _file.Seek(_position, SeekOrigin.Begin);
        _position += output.Length;
        await _file.WriteAsync(output, 0, output.Length);
    }

}

Here you can see the await key word, what it means..


As per msdn “
An await expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it left off.“

await is used with some asynchronous method that returns task and is used suspend the execution of the method until the task completes and control is returned back to the caller to execute further. await should be used with the last expression of any code block.


And Init method would be like


Public  void Init(HttpApplication context)
{
       // It wraps the Task-based method
       EventHandlerTaskAsyncHelper asyncHelper =
       new EventHandlerTaskAsyncHelper(WriteLogmessages);

       //asyncHelper's BeginEventHandler and EndEventHandler eventhandler that is used
       //as Begin and End methods for Asynchronous HTTP modules
       context.AddOnPostAuthorizeRequestAsync(
       asyncHelper.BeginEventHandler, asyncHelper.EndEventHandler);

}


So apart from above these methods, we need to implement the dispose method.


Now compile your class library and use the reference in your ASP.NET website . Now as you must be knowing that we need to need to add the entry in the config file. So it’ll be as


<system.webServer>
<modules>
<add name="MyCustomHTTPModule" type="MyCustomHTTPModule.LogModule, MyCustomHTTPModule"/>
</modules>
</system.webServer>

Now when you run your application, you will see the logs are created in a text file in App_Data folder as

mentioned path in the code.

Hope you all have liked this new feature.

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.


You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:


-
DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.

- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.

- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.

- Data Center

ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.

- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.

- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.

- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.

 



ASP.NET 4.5 Hosting - ASPHostPortal :: Model binding in Asp.net 4.5

clock May 10, 2012 09:05 by author Jervis

Good news for all Asp.net Developer who were keen to know the new feature of asp.net 4.5. Now you can bind your model same as the features available in MVC in Asp.net 4.5.

It becomes easy to perform any CRUD operation with any of the data source such as LINQ, Ado.net or Entity framework.


Let’s do some practice, here I am going to bind my Drop Down list using this new features called “Model Binding”

Add one drop down in your page and set it’s “DataTextField” and “DataValueField” properties.
Go to Code behind file and Create one method which will return IQUERYable<type> as

/// <summary>

/// Return the City Name

/// </summary>

/// <returns></returns>


public
IQueryable  GetCityNames()
{

MyDbEntities ds = new MyDbEntities();

return
ds.City;
}


Now Goto design page and set the “
SelectMethod” Property of DropDown

<asp
:DropDownList ID="DropDownList1"
runat
="server"
Height
="17px" Width="201px"
DataTextField
="CityName"
DataValueField
="CityID"
SelectMethod
="GetCityNames"
AppendDataBoundItems
="true"
AutoPostBack
="true">
asp
:DropDownList>;

That’s It, run your program.


Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what
ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

-
DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.

- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.

- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.

- Data Center

ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.

- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.

- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.

- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET 4.5 Hosting - ASPHostPortal :: Breaking Changes Planned for .NET 4.5

clock April 10, 2012 11:37 by author Jervis

The actual version number for .NET 4.5 assemblies is 4.0.30319. If that looks familiar it is because that is also the version number for .NET 4.0 assemblies. Much to the chagrin of developers, Microsoft will be updating core assemblies “in-place”. Aside from making much harder to determine which version of .NET the user actually has installed, it creates numerous pitfalls for developers targeting .NET 4.0 with machines that have 4.5 installed.

While Visual Studio is quite capable of keeping developers from accidentally using .NET 3.0 or 3.5 assemblies in projects targeting .NET 2.0 the same cannot be said for individual methods. Within the IDE there is no warning that method in a common library such as mscorlib.dll or System.dll didn’t exist in the older version. Unless a static analysis tool is used to programmatically check for such mistakes, the error will probably not be detected until the code fails at runtime. A good example of this is EventWaitHandle.WaitOne, which has overloads that were added via a service pack that shipped with .NET 3.5.


While this is still a theoretical problem at this time, there are also several
breaking changes in .NET 4.5 that will need to be accounted for.

Unhandled, unobserved exceptions

In .NET 2.0 the semantics for unhandled exceptions changed. Prior to this version exceptions on a non-UI thread would simply be discarded and the associated thread terminated. As of .NET 2.0, unhandled exceptions would cause the entire application to crash. While this greatly reduced the possibility of data corruption and undetected errors, it also meant that all calls made on back-ground threads were handled a top-level exception handler.


When the Task Parallel Library was introduced it followed this model. If a Task is faulted, its Exception property must be read before the Task is garbage collected. Failing to do so will cause the finalizer to terminate the application on the grounds that it had an unhandled exception.

In .NET 4.5 the rule for Tasks will change to be like the pre-2.0 rule for threads. While a global event will be raised for logging purposes, faulted Tasks will no longer crash the application.

System.Net.PeerToPeer.Collaboration

The namespace System.Net.PeerToPeer.Collaboration is not available and no explanation was given why.

These libraries were only available on non-server versions of Windows Vista and Windows 7 and are an extension to the Windows Peer-to-Peer Infrastructure. Being a rarely used subset of a rarely used technology, there is very little information on this namespace and it is unlikely to affect more than a handful of developers.

WCF

When the maxRequestLength or maxReceivedMessageSize quota is exceeded the HTTP status code has changed from 400 (Bad Request) to 413 (Request Entity Too Large).

WPF

The default value of TextBoxBase.UndoLimit has been changed from -1 (unlimited) to 100. No explanation was given, but presumably this offers a performance advantage over storing an indefinite number of prior versions of the text box contents.

XML/XSLT

Validation errors throw by XDocument will now include the line number and position if LoadOptions.SetLineInfo was passed to the Load method.

Forward compatibility mode for the System.Xml.Xsl.XslCompiledTransform class has been fixed.

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.

- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.

- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.

- Data Center

ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.

- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.

- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.

- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET 4.5 Hosting - ASPHostPortal :: Unobtrusive Validation with ASP.NET 4.5

clock March 27, 2012 06:20 by author Jervis

ASP.NET 4.5 has been improved and latest version ASP.NET. It includes an array of new and modified features. Today we’ll discuss one new feature Unobtrusive Validation that is introduced with ASP.NET 4.5 .

So what is Unobtrusive Validation?

In a normal validation scenario,when we use a validator to validate any any control and use Client side validation, some JavaScript is generated and rendered as HTML. Also some supportive JavaScript files is also get loaded by the browser for the validation.


Now with feature Unobtrusive Validation, inline JavaScript is not generated and rendered to handle the Client Side validation. Instead of this it uses HTML5 data-* attributes for all these validation.

So now lets see a normal scenario. I have taken textbox and applied two ASP.NET validators on it. One is RequiredFieldValidator and RangeValidator that allows to enter the value between 100 and 1000. Let’s see the aspx code.



Now Lets run the application and see the generated the HTML. Now if you look at the View Source of the page



To handle these validation, it generates the lots of JavaScript code on the page. It is



Now I have made the same application with Visual Studio 2011 Developer Preview. By default Unobtrusive Validation is enabled here. So lets see the generated HTML



Now if you see the above generated HTML, there are few data-* attributes are rendered. And these hold all the required information of the validator. And there is no inline JavaScript code generated. This reduces the significant amount of page size because here inline JavaScript code is not generated and this also makes the rendered HTML neat and clean.


So let’s see how asp.net 4.5 allows to configure the Unobtrusive Validation. There is one new property UnobtrusiveValidationMode got added, which can be assigned two values

-
None : means UnobtrusiveValidation is set to off
-
WebForms : means UnobtrusiveValidation is enabled

This property can be configured at three places in application. These are

1. First it can be set at application level in config file. We need to add it in the <appSettings> element.

<
add name="ValidationSettings:UnobtrusiveValidationMode" value="WebForms" />

As I discussed it is by default enabled in asp.net. The above key by default added in web.config. So if you want to disable it then change the above as

<add name="ValidationSettings:UnobtrusiveValidationMode" value="None" />

2. We can also set it at Application_Start method in Global.asaxfile as

void Application_Start(object sender, EventArgs e)
{
   //Enabling UnobtrusiveValidation application wide
   ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.WebForms;
}

3. We can also set it at page level by setting the property of Page Class as

Page.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.WebForms;

 



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in