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 :: Timeout in Regular Expressions ASP.NET 4.5

clock December 10, 2015 21:07 by author Jervis

Regular expressions are common forms of parsing a document and get meaning. It has been very popular and most of the people do use it regularly to solve their complex problems.

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. 

Try
{
    Regex regexpr =
new Regex("[A-Z ]{10}", RegexOptions.Singleline, TimeSpan.FromMilliseconds(1));
    Match mch = regexpr.Match(
"ABHISHEK SUR");
   
if (mch.Success)
        Console.WriteLine(
"Match found");
   
else
        Console.WriteLine(
"Not matched");

}
catch (RegexMatchTimeoutException ex)
{
    Console.WriteLine(
"Regex Timeout for {1} after {2} elapsed. Tried pattern {0}", ex.Pattern, ex.Message, ex.MatchTimeout);
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine(ex.ToString());
}
finally
{
    Console.ReadKey(
true);
}

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.

Try
{
    AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromMilliseconds(2));

    Regex regexpr = new Regex("[A-Z ]{10}", RegexOptions.Singleline);
    Match mch = regexpr.Match("ABHISHEK SUR");
    if (mch.Success)
        Console.WriteLine("Match found");
    else
        Console.WriteLine("Not matched");

}
catch (RegexMatchTimeoutException ex)
{
    Console.WriteLine("Regex Timeout for {1} after {2} elapsed. Tried pattern {0}", ex.Pattern, ex.Message, ex.MatchTimeout);
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine(ex.ToString());
}
finally
{
    Console.ReadKey(true);
}

Now this works exactly the same as the previous one. Here the Regex 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. In fact 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 you read MSDN thoroughly, it suggests to use Timeouts when specifying the Regular expressions. 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.  

 



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 :: How You Can Develop Asynchronous Device Page in ASP.Net 4.5

clock November 4, 2014 05:15 by author Ben

Within this tutorial we'll make use of the most recent ASP.Net 4.5 methods to come back up with a asynchronous gadget web page via help of Visual Studio Express.

The sample software that we're going to use listed here makes use of new async and awaits key phrases and they're obtainable in .NET 4.5 and Visual Studio 2012. This allows the complier to hold the responsibility of getting care from the complex transformations that are necessary for asynchronous programming. Also the compiler will allow you to write the code using the C#'s synchronous manage movement constructs. Therefore the compiler on its own applies the transformations which can be necessary to deploy call-backs. This is done in order to prevent blocking threads.



ASP.Net asynchronous web pages has to comprise in the Web page directive and Async feature label set to “true”. The code detailed under demonstrates the Page directive with all the value of Async attribute set to accurate for the DeviceAsync.aspx page.

<%@ Page Async="true" Language="C#" AutoEventWireup="true"
    CodeBehind="DeviceAsync.aspx.cs" Inherits="WebAppAsync.DeviceAsync" %>

The below code reflects the Device synchronous Page_Load method as well as the DeviceAsync asynchronous page. In case the browser supports the HTML5 <mark> element, the changes can be seen in DeviceAsync in yellow highlight.

protected void Page_Load(object sender, EventArgs e)
{
   var deviceService = new DeviceService();
   DeviceGridView.DataSource = deviceService.GetDevice();
   DeviceGridView.DataBind();
}

The below displays the asynchronous version:
protected void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(GetDeviceSvcAsync));
}

private async Task GetDeviceSvcAsync()
{
    var deviceService = new DeviceService();
    DeviceGridView.DataSource = await deviceService.GetDeviceAsync();
    DeviceGridView.DataBind();
}

The beneath lists the changes that were applied to permit DeviceAsync page to be asynchronous.

  • This is a need to to set the Webpage directive Async attribute to "true".
  • The RegisterAsyncTask indicates is deployed to sign up an asynchronous task that includes of the code which can be operated asynchronously.
  • The new GetDeviceSvcAsync approach is labelled with the async key phrase that informs the compiler to make callbacks for parts of the body and in addition to generate a Job of its personal which is returned.
  • Should you recognize, we appened "Async" towards the asynchronous technique title although this is not required however it is the conference while you're writing asynchronous methods.
  • The return sort in the Task defines the perform in progress and offers the callers of the approach having a deal with through which to halt for your completion of the asynchronous operation. The return type in the new GetDeviceSvcAsync method is Activity.
  • Internet support call helps make use of the await keyword.
  • The asynchronous web service API was referred to as GetDeviceAsync.

GetDeviceAsync is another asynchronous method that's known as inside of the GetDeviceSvcAsync method physique. Task<List<Device>> is immediately returned by a GetDeviceAsync that will finally full on the availability of the info. For your purpose that you'd not want to proceed additional just before you have the device data, the code waits for the task making use of the await keyword. 1 might make usage of the await keyword just in techniques annotated with all the async search term.

Until finally we have the completion from the task, the thread is not blocked from the await search term. It indications up the rest of the method as being a callback within the job, and immediately returns. Within the completion in the awaited activity, that callback will likely be invoked thereby resuming the implementation from the method right exactly where it left off.

The below code displays the GetDevice and GetDeviceAsync techniques:

public List<Device> GetDevice()
{
   var uri = Util.getServiceUri("Device");
   using (WebClient webClient = new WebClient())
   {
        return JsonConvert.DeserializeObject<List<Device>>(
            webClient.DownloadString(uri)
        );
    }
}

public async Task<List<Device>> GetDevicesAsync()
{
    var uri = Util.getServiceUri("Devices");
    using (HttpClient httpClient = new HttpClient())
    {
        var response = await httpClient.GetAsync(uri);
        return (await response.Content.ReadAsAsync<List<Device>>());
    }
}

The asynchronous modifications which were utilized are same as those applied to the DevicesAsync above.

  • Async key phrase was used to annotate the method signature, the return sort was changed to Task<List<Device>>, and Async was appended for the technique title.
  • The asynchronous HttpClient is utilized rather than synchronous WebClient class.
  • The await keyword was used to the HttpClient GetAsync asynchronous method.

The below image displays the asynchronous device see.

The browsers screen of the gadget info is same concerning the check out that's created by the synchronous contact. Here the only difference will be the asynchronous model might be more execute ant below main hefty loads.

Methods that are hooked up with RegisterAsyncTasks will likely be executed instantly after PreRender. 1 may also utilize async void page events directly as may be seen from the under code:

protected void Page_Load(object sender, EventArgs e) {
    await ...;
    // do work
}

The disadvantage for the async occasions is that the programmers now don't have the complete use of the occasions when activities are applied. Example, in case both an .aspx as well as a .Master signifies Page_Load occasions and a minimum of 1 of them is asynchronous, there's no guarantee from the execution.

Getting a developer, it is recommended to apply the above stated procedure to come up with the asynchronous unit web page making use of the newest ASP.Net 4.5 systems.

 



ASP.Net 4.5 Hosting - ASPHostPortal.com :: Producing Data-driven Web Apps Utilizing ASP.Net 4.5 Web Forms

clock October 16, 2014 06:30 by author Ben

Data binding is less complicated and more effective in ASP.Net 4.5 Kinds.This publish discuss about making Data-driven software using ASP.Net 4.5 preview. Additionally, it discuss about distinct Info access methods, especially about design entry binding features in Internet Types. You need to install Visual Studio 11 Developer preview to use this function.

Typical ASP.Net developer could use a single from the following Info Access mechanisms for binding the data

  • You could set up your Database Initial - Making a Schema and creating product from it. Listed here model is actually a class which you're going to communicate with your databases from your code.
  • You may setup your Product Initial - Instead of developing the database first, we design the entity model initial eg: making use of entity framework. Style your product first after which generate a schema and code.
  • You could setup your Code First- On this strategy you very first write code to design and style the product and after that produce a schema making use of that code.

Your model designer floor could search like beneath should you stick to the any of above Information Accessibility mechanisms


This post discuss the third strategy Code Very first Information Entry mechanism to connect with the databases. This method makes use of the Product Binding , the phrase barrowed from MVC. In MVC whenever you call an motion method which received some parameters in which you need to move values from question string or from cookie assortment and bind these values into parameters. Design Binding does this in MVC. The concept is comparable Web Types but context is little little bit different.

Step1 Construct courses which represent your model.

Incorporate a folder within your remedy referred to as Model and then add new item class named Issue.



The difficulty class code getting some homes which appear like as below


Consequently the above mentioned code turns into a database desk. You can discover info annotations on every home. You'll be able to specify your validation at a single spot. eg: Required in above properties.

Produce an additional class which represent the database context named IssuesDb.


Now add the connection string in web.config file with same name as your DbContext. Here it is IssuesDb.

Create another class which initializes your database as shown below

public class Dbinitializer : DropCreateDatabaseIfModelChanges<IssuesDb>

    {

      protected override void Seed(IssueDb context)

        {

            context.Issues.Add(new Issue { CreatedBy="xyz",

            CreatedOn = new DateTime(), Title="Issue1"})

            context.Issues.Add(new Issue { CreatedBy="abc",

             CreatedOn = new DateTime(), Title="Issue2"})

            context.Issues.Add(new Issue { CreatedBy="aaa",

           CreatedOn = new DateTime(), Title="Issue3"})       

      

       }

You'll be able to override the tactic See to insert some values into the produced desk.

Step2 Displaying the above specifics in UI. We will set up a Gridview to Model Binding to list the details from database table.


We are not performing anything at all new listed here , Product Binding is merge of concept from Object information resource and MVC Design Binding. Specify your ModelType and SelectMethod to point out the main points.

We will also template fields to gridview and established the binding expression to point out the values but in different way.

The normal way is one thing proven below


The problem with the above expression is we do not know the type of the column. Now you will get an intellisense inside data binding expressions with a name Item.


The GetIssues method code will look like as below


Before running your application, Initialize the database initializer class in Global.asax file Application Start method

DataBase.SetInitializer(new IssueDbInitializer());


It also creates database and tables as you specified in the model class


Step3 Now let us add a filter to this application.

Add a lable, text box and a button to UI.


Now modify GetIssues method as shown below where Model Data binding comes into the picture.


The method having a parameter named createdSince that is a textbox id and we have been telling the strategy it is a handle. You are able to go ahead and take price from parameter and filter the values as demonstrated below


Instead of finding the control and writing the code, Model Binding takes the input from the user and retrieves the values from Dbcontext.

Points to note:

There's no If !(IsPostBack) or button handlers to attain this functionality. Just get in touch with this process by passing the worth from this handle. that is it!. We will dynamically manipulate the query by just using the values in the user.

Step4 Adding a FormView which exhibits all particulars and permits you to insert and edit the issue. The FormView markup seems like as below


The GetIssue method code as below. The idea is enable autogenerated select column in gridview and show the details when you select the particular issue.


You saying to method to get the id value from issuesGrid control and return the issue details. Run the application then you will see the below result


Note that we've not composed any code to re-bind the values from database to grid. Design Binding maintain observe from the values of parameters across the submit backs. It truly retailers these values in viewstate.

The InsertMethod code seems as below


and above code you can see we are validating whether user is logged in or not and based  on that we are using ModelState to add the model error message.

ModelState represents the current state of Model Binding system on your page.

You can pass this error message to Validation Summary on your page by setting ShowModelStateErrors = true.


Another new point to notice is TryUpdateModel method which is an explicit Model Binding. This method tells model to try and bind the data from current request in to this issue variable.

The binding expression in InsertItem template in gridview will look like


Previously we do something like this


Run the application you then will begin to see the under screen


The update method exactly looks like insert method but having an additional parameter named id which is an id of record in the current Model Binding expression.


We have seen the new data-related improvements in ASP.NET 4.5 Web Forms with Model Binders and Data annotations.



ASP.NET 4.5 Hosting :: Publishing Your ASP.NET 4.5 Site with Visual Studio 2012

clock May 6, 2014 08:33 by author Ben

Microsoft Visual Studio 2012 is loaded with new capabilities for Windows 8, the web, SharePoint, mobile, and cloud development—as well as the application management lifecycle tools you need to break down team barriers and reduce cycle times to deliver value continuously.

Visual Studio 2012 is New versions of Visual Studio usually coincide with updates to the .NET Framework and one of our biggest releases yet. It comes purpose-built to help you thrive in an environment in which ideas are at a premium and speed is of the essence.

This Article can tell you how to publish your asp.net 4.5 site in vistul studio 2012.
Steps to Publish Web Application in Visual Studio 2012:
Step 1: Right click on the web project in the solution explorer window and then select the option Publish.

Step 2: Publish Web Application Window will open .Here under the option Select or Import a publish profile Select the option New in the drop down.

Step 3: In New Profile Window give any name to Profile and then click on Ok.

Step 4: Next in Connection Select the Publish method File System.

Step 5: Again in Connection for Target location select the folder on your computer where you want to publish the web application and then click on Next Button.
Step 6: In Settings Select the Configuration Release in the drop down and then click on Next Button.

Step 7: Finally in the Preview Click on Publish to Publish the web Project to  folder selected in the Step 5 above.



Best and Affordable Visual Studio 2012 Hosting with ASPHostPortal.com

We have supported site developed with
Visual Studio 2012 Hosting. Host your site on our Windows Server 2012 today. Visual Studio 2012 is New versions of Visual Studio usually coincide with updates to the .NET Framework and one of our biggest releases yet. It comes purpose-built to help you thrive in an environment in which ideas are at a premium and speed is of the essence.

For fast, secure and reliable Visual Studio 2012 Hosting, look no further than ASPHostPortal.com for all your web hosting related needs. Microsoft Visual Studio 2012 provides many new capabilities to support development on the latest platforms with modern lifecycle tools to make it easier for teams to deliver value continuously.

Visual Studio Updates help ensure you always have the best solution for building modern applications and for managing the modern application lifecycle. New to Windows Extensions, Modules, and Libraries? Ready to try out? Sign up for a FREE Trial Hosting account from ASPHostPortal.com with absolutely no cost and get going in minutes. Our Windows Server is also compatible with Visual Studio 2005, Visual Studio 2008, and Visual Studio 2010.



Free Trial ASP.NET 4.5 Hosting with ASPHostPortal.com :: How to Resolve Unobtrusive validation on Your ASP.NET 4.5 Apps

clock April 4, 2014 08:36 by author Ben

Now, I want to tell you How to Resolve Unobtrusive validation on Your ASP.NET 4.5 Apps.

By default, ASP.NET 4.5 has changed the way validation works. On the surface, it works exactly the same as usual, but under the hood, now it uses by default a new kind of unobtrusive validation based in jQuery, instead of the previous default scripts.

Now, the client-side validation is made in a simpler way by using the jQuery validation plugin, and by decorating the different controls with “data-val” attributes, instead of polluting your page with a lot of validation scripts.

For example, this is the resulting HTML for a Requiredvalidator control when you are using the unobtrusive validation mode:


<span
id="RequiredFieldValidator1"
data-val-controltovalidate="TextBox1"
data-val-focusonerror="t"

data-val-errormessage="Required!"

data-val-display="Dynamic"
data-val="true"
data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid"

data-val-initialvalue=""
style="color:Red;display:none;">Required!</span>


Notice all those “data-val” attributes. By simply inspecting this code you can easily tell how this validation control is behaving. That’s great!

However, if you create a new Empty Web Application using Visual Studio 2012 or later and add a validation control to one page, when you run the app you’ll get this error screen:

 


“UnobtrusiveValidationMode requires a ScriptResourceMapping for jQuery”
You get this error because the validation scripts search for a script resource called “jquery”, and it’s not present in your app.

You have several options to make it work correctly:

1. Disable the unobtrusive validation on a per-page fashion.
This enables again the former validation system from previous ASP.NET Web Forms versions (up to v.4.0).
Doing this bay hand is tedious if you have more than one or two pages, but is easy. You just need to add this line to the Load event of your page:
   
Page.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;

2. Disable de unobtrusive validation for the whole app.
For achieving this you just need to add one line to our web.config file, under the app.settings node, like this:

<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />

</appSettings>


3. Add a ScriptResourceMapping for jQuery, as indicated in the error page.
For achieving this, first you need to download the latest version of jQuery. Download both available editions (the production and development one) and copy those .js files to a “scripts” folder in your app’s root folder.

Now we need to add the Global.asax file to your project. In the Application_Start event you need to define a new ScriptResourceMapping with the name “jquery”, so that the framework knows where to get the jQuery scripts.
This is the needed code in C#:

protected void Application_Start(object sender, EventArgs e)

{

    ScriptManager.ScriptResourceMapping.AddDefinition("jquery",

                new ScriptResourceDefinition

                {

                    Path = "~/scripts/jquery-1.8.3.min.js",

                    DebugPath = "~/scripts/jquery-1.8.3.js",

                    CdnPath = "http://<a title="ajax" href="#">ajax</a>.aspnetcdn.com/<a title="ajax" href="#">ajax</a>/jQuery/jquery-1.8.3.min.js",

                    CdnDebugPath = "http://<a title="ajax" href="#">ajax</a>#"

                });

}

Don’t forget to include a:

using System.Web.UI;


at the beginning of the page.

 



ASP.NET 4.5.1 Hosting - with ASPHostPortal.com :: How to Load GMap Direction from Database in ASP.NET

clock March 11, 2014 06:45 by author Kenny

Well i am going to explain how to load GMap direction from database in ASP.NET.
Google maps is a web mapping service application and technology provided by Google, powering many map-based services, including the Google maps website, Google ride finder, Google transit, and maps embedded on third-party websites via the Google maps API. ASP.NET is a server-side web application framework designed for web development to produce dynamic web pages.
Let’s check the steps for run this program.

For the first: Go to file > new > project > select asp.net web forms application > entry application name > click ok.

And then add a database: Go to solution explorer > right click on app_data folder > add > new item > select sql server database under data > enter database name > add.


After that create table: Open database > right click on table > add new table > add columns > save > enter table name > ok.

This is the table sample:

Next, create a stored procedure in sql server: Open database > right click on stored procedure > add new stored procedure > write below sql code > save.

Next step, add a webpage: Go to solution explorer > right click on project name form solution explorer > add > new item > select web form/ web form using master page under web > enter page name > add.
Html code



Js code

Write this below js code for load gmap direction from database.

<script src="//maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=abqiaaaaupsjpk3mbtdpj4g8cqbnjrragtyh6uml8madna0ykuwnna8vnxqczvbxtx2dyyxgstoxpwhvig7djw" type="text/javascript"></script><script language="javascript">
        var gmap;

        var directionpanel;
        var direction;
        function initialize() {
            gmap = new gmap2(document.getelementbyid("map"));
            gmap.setcenter(new glatlng(22.573438, 88.36293), 15);
// here i have set kolkata as center and 15 zoom level

            directionpanel = document.getelementbyid("route");
            direction = new gdirections(gmap, directionpanel);
        }
        $(document).ready(function ()
{
            initialize();

            $('#btngetdirection').click(function () {
                //here populate data from database and get to gmap direction
                populatedirection();
            });
        });
        function populatedirection() {
            var from = $('#<%=ddfrom.clientid%>').val();
            var to = $('#<%=ddto.clientid%>').val();

            $.ajax({
                url: "default.aspx/getdirectioin",
// here url for code behind function
                type: "post",
                data: "{from: '"+from+"', to: '"+to+"'}",
                datatype: "json",
                contenttype: "application/json; charset=utf-8",
                success: function (data) {
                    direction.load(data.d.tostring());

                },
                error: function () {
                    alert("error!");
                }
            });
        }
    </script>

And then: write following code in page_load event:
Protected void page_load(object sender, eventargs e)
{
    if (!ispostback)
    {
        populatelocation();
    }}


Here is the function...

Private void populatelocation(){

// populate location here
    datatable dt = new datatable();
    using (sqlconnection con = new sqlconnection(configurationmanager.connectionstrings["con"].connectionstring))
    {
        string query = "select * from locations";
        sqlcommand cmd = new sqlcommand(query, con);
        if (con.state != connectionstate.open)
        {
            con.open(); }
        dt.load(cmd.executereader());}
    ddfrom.datasource = dt;
    ddfrom.datatextfield = "locname";
    ddfrom.datavaluefield = "locid";
    ddfrom.databind();
    ddto.datasource = dt;
    ddto.datatextfield = "locname";
    ddto.datavaluefield = "locid";
    ddto.databind();}


Don’t forget write this function into your page code behind for called from jquery code:

// this is the function is for called from jquery
[webmethod]
Public static string getdirectioin(string from, string to){
    string returnval = "";
    datatable dt = new datatable();
using (sqlconnection con = new sqlconnection(configurationmanager.connectionstrings["con"].connectionstring))
    {
        sqlcommand cmd = new sqlcommand("getdirection", con);
        cmd.commandtype = commandtype.storedprocedure;
        cmd.parameters.addwithvalue("@locfrom", from);
        cmd.parameters.addwithvalue("@locto", to);
        if (con.state != connectionstate.open)
        {
            con.open();}
        dt.load(cmd.executereader());}
    returnval = "from: " + dt.rows[0]["fromloc"].tostring() + " to: " + dt.rows[0]["toloc"].tostring();
    return returnval;}


And the last, Just run your application



Free Trial ASP.NET 4.5.1 Hosting - with ASPHostPortal.com :: How to make Scrollable GridView with a Fixed Header in .NET 4.5.1

clock March 7, 2014 05:38 by author Diego

In this article I will explain how to implement scrollable gridview with fixed header in asp.net using JQuery. GridView control of ASP.NET 4.5.1 makes our task much simpler as compared to HTML tables. But one problem which I always faced with GridView control is of scrolling headers. I tried several forums and websites, but didn’t come up with a good solution. GridView doesn’t have the ability to scroll. But if the GridView contains the larger number of rows or columns (say more than 100 rows and 15 columns), we want it to have scrollbars.

Now it is time to see all the activity in detail :

  • create a database in the SQL ServerCreate an ASP.NET website.
  • Create jquery-1.4.1.min.js and ScrollableGridPlugin.js and write this code in the header section. copy and paste it inside  <Head>.
    These script files by using these files we can manage the GridView header fixed postion.


    <
    script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>

    <
    script type="text/javascript" src="Scripts/ScrollableGridPlugin.js"></script>
  • Write the jQuery code that is given below.

    script
    type="text/javascript">
            $(document).ready(function () {
                $('#<%=GridView1.ClientID %>').Scrollable();
            });

    </
    script
    >

  • The next step is to create a new HTML table in HeaderDiv which will contain the new header for the GridView. This job will be done by a JavaScript function (say CreateGridHeader()). This JavaScript function also sets the HeaderDiv style as per the DataDiv and new HTML table style as per GridView style and also we will hide the original header of GridView. This function will be called every time after filling the GridView with data as well as on the Page Load.
    created in the Page Load Default.aspx page like this :

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat
="server">
    <title>Scrollable GridView With a Fixed Header Using jQuery</title>
    <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
    <
script type="text/javascript" src="Scripts/ScrollableGridPlugin.js"></script>
      <
script type="text/javascript">
        $(document).ready(function () {
            $('#<%=GridView1.ClientID %>').Scrollable();
        });
      </script
>
<
body>
    <form id="form1" runat="server">
    <asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="false">
        <RowStyle BackColor="#EFF3FB" />
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <AlternatingRowStyle BackColor="White"
/>
        <Columns>
            <asp:BoundField DataField="id" HeaderText="Id" />
            <asp:BoundField DataField="name" HeaderText="Name" />
            <asp:BoundField DataField="salary" HeaderText="Salary" />\
            <asp:BoundField DataField="addres" HeaderText="Address" />
        </Columns>
    </asp:GridView>
    </form>
</
body
>

</html>

  • Binding the GridView with a DataTable object in the code behind file of Default.aspx page.

    using
    System;
    using
    System.Collections.Generic;
    using
    System.Linq;
    using
    System.Web;
    using
    System.Web.UI;
    using
    System.Web.UI.WebControls;
    using
    System.Data;
    using
    System.Data.SqlClient;


    public
    partial class Default2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=akshay;Persist Security Info=True;User ID=sa;Password=wintellect";
            SqlDataAdapter adap = new SqlDataAdapter("select * from Person",con);
            DataSet ds=new DataSet();
            adap.Fill(ds,"Person");
            GridView1.DataSource = ds.Tables["Person"];
            GridView1.DataBind();
            GridView1.UseAccessibleHeader = true;
            GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
        }

    }
  • Run the Page by f5, you will see that the Header and Footer is fixed when you scrolling. You are now ready with the GridView with fixed headers.

If you looking for windows web hosting services who support ASP.Net 4.5.1 please visit our Site ASPHostPortal.com



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