European ASP.NET 4.5 Hosting BLOG

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

European ASP.NET Hosting - :: jQuery PJAX Implementation In ASP.NET Core

clock February 26, 2019 11:15 by author Peter

PJAX is a jQuery plugin that uses AJAX and pushState to deliver a fast browsing experience with real permalinks, page titles, and a working back button. It is available to download from GitHub.

In all websites, the header and footer remain the same for all pages. Only the page contents (the content in the middle area between the header and footer) are changed for each page. PJAX uses this concept to fetch only the page contents while the header and footer remains the same for each page. In short, you can also say PJAX is the brother of the Update Panel of Web Forms that works for ASP.NET Core.

With PJAX, you get the following advantages.

    The website becomes fast since the header and footer are not loaded for different pages.
    You website behaves like a SPA (Single Page Application), and you don’t need to employ Angular framework in your ASP.NET Core Application.
    If you have worked with Update Panel of ASP.NET Web Forms then it is quite similar to it.

This is how PJAX will work.
See the below video which illustrates the working of PJAX.

PJAX Implementation in ASP.NET Core

Integration of PJAX in ASP.NET Core involves the following things.

Layout.cshtml View
In your application _Layout.cshml View, add jQuery and PJAX script links. You do this inside the head section:
    <script src=""></script> 
    <script src="~/js/jquery.pjax.js"></script> 
    Also call PJAX on all anchors inside the #main element.  
    <script type="text/javascript"> 
        $(function () { 
            // call pjax 
            $(document).pjax('#menu li a', '#main', { timeout: 10000 }); 

Loading Image
If you want to show the loading image when a new page contents are being fetched then add the following code inside the script section of Layout:
    $(document).ajaxStart(function () { 
    $(document).ajaxComplete(function (event, jqxhr, settings) { 

Also, place the loading image somewhere in your layout.
    <div id="loadingDiv" style="display:none;"> 
        <img src="~/loading.gif" /> 

Do not worry as the source code contains all the loading image codes. Do check it.

Add some links to your _Layout.cshtml View. On these links, PJAX will work so when these links are clicked then their page’s contents are loaded by PJAX (but the header and footer area are not loaded).
        <li><a href="/Home/Index">Index</a></li> 
        <li><a href="/Home/About">About</a></li> 
        <li><a href="/Home/Contact">Contact</a></li> 

Don’t forget to add the #main element on the Layout so that PJAX only fetches the contents inside this #main element with AJAX.
    <div id="main"> 

Add a controller called Home with the following 3 action methods:

    public IActionResult Index() 
        if (string.IsNullOrEmpty(Request.Headers["X-PJAX"])) 
            return View(); 
            return PartialView("/Views/Home/Index.cshtml"); 
    public IActionResult About() 
        if (string.IsNullOrEmpty(Request.Headers["X-PJAX"])) 
            return View(); 
            return PartialView("/Views/Home/About.cshtml"); 
    public IActionResult Contact() 
        if (string.IsNullOrEmpty(Request.Headers["X-PJAX"])) 
            return View(); 
            return PartialView("/Views/Home/Contact.cshtml"); 

Make sure that the Action methods that are called by PJAX (i.e. clicking on menu links in my case) return PartialViews. Since PJAX sends ‘X-PJAX’ request in the HTTP Header therefore I can easily make a selection of View or Partial View by checking the HTTP header.

The condition applied in each action method that does this work is:
    if (string.IsNullOrEmpty(Request.Headers["X-PJAX"])) 
        return View(); 
        return PartialView("/Views/Home/Index.cshtml");  


Add the 3 Views called ‘Index.cshtml’, ‘About.cshtml’ and ‘Contact.cshtml’ inside the ‘Views/Home’ folder:

    <div class="templatemo_content_area"> 
        <h1>WELCOME TO Index Page</h1> 

    <div class="templatemo_content_area"> 
        <h1>WELCOME TO About Page</h1> 

    <div class="templatemo_content_area"> 
        <h1>WELCOME TO Contact Page</h1> 

Also add _ViewStart.cshtml View inside the ‘Views’ folder:
        Layout = "_Layout"; 

European ASP.NET Hosting :: Overriding ASP.NET Core Framework

clock February 20, 2019 10:57 by author Scott


In .NET it’s really easy to create your own interfaces and implementations. Likewise, it’s seemingly effortless to register them for dependency injection. But it is not always obvious how to override existing implementations. Let’s discuss various aspects of “dependency injection” and how you can override the “framework-provided services”.

As an example, let’s take a recent story on our product backlog for building a security audit of login attempts. The story involved the capture of attempted usernames along with their corresponding IP addresses. This would allow system administrators to monitor for potential attackers. This would require our ASP.NET Core application to have custom logging implemented.


Luckily ASP.NET Core Logging is simple to use and is a first-class citizen within ASP.NET Core.

In the Logging repository there is an extension method namely AddLogging, here is what it looks like:

public static IServiceCollection AddLogging(this IServiceCollection services)
    if (services == null)
        throw new ArgumentNullException(nameof(services));

    services.TryAdd(ServiceDescriptor.Singleton<ILoggerFactory, LoggerFactory>());
    services.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>)));

    return services;

As you can see, it is rather simple. It adds two ServiceDescriptor instances to the IServiceCollection, effectively registering the given service type to the corresponding implementation type.


When you create a new ASP.NET Core project from Visual Studio, all the templates follow the same pattern. They have the Program.cs file with a Main method that looks very similar to this:

public static void Main(string[] args)
    var host = new WebHostBuilder()



One thing that is concerning about a template like this is that the IWebHost is an IDisposable, so why then is this statement not wrapped in a using you ask? The answer is that the Run extension method internally wraps itself in a using. If you were wondering where the AddLogging occurs, it is a result of invoking the Build function.

[ Microsoft.AspNetCore.Hosting.WebHostBuilder ]
    public IWebHost Build() ...
        private IServiceCollection BuildCommonServices() ...
            creates services then invokes services.AddLogging()


The ServiceDescriptor class is an object that describes a service, and this is used by dependency injection. In other words, instances of the ServiceDescriptor are descriptions of services. The ServiceDescriptor class exposes several static methods that allow its instantiation.

The ILoggerFactory interface is registered as a ServiceLifetime.Singleton and its implementation is mapped to the LoggerFactory. Likewise, the generic type typeof(ILogger<>) is mapped to typeof(Logger<>). This is just one of the several key “Framework-Provided Services” that are registered.


Now we know that the framework is providing all implementations of ILogger<T>, and resolving them as their Logger<T>. We also know that we could write our own implementation of the ILogger<T>interface. Being that this is open-source we can look to their implementation for inspiration.

public class RequestDetailLogger<T> : ILogger<T>
    private readonly ILogger _logger;

    public RequestDetailLogger(ILoggerFactory factory,
                               IRequestCategoryProvider requestCategoryProvider)
        if (factory == null)
            throw new ArgumentNullException(nameof(factory));
        if (requestCategoryProvider == null)
            throw new ArgumentNullException(nameof(requestCategoryProvider));

        var category = requestDetailCategoryProvider.CreateCategory<T>();
        _logger = factory.CreateLogger(category);

    IDisposable ILogger.BeginScope<TState>(TState state)
        => _logger.BeginScope(state);

    bool ILogger.IsEnabled(LogLevel logLevel)
        => _logger.IsEnabled(logLevel);

    void ILogger.Log<TState>(LogLevel logLevel,
                             EventId eventId,
                             TState state,
                             Exception exception,
                             Func<TState, Exception, string> formatter)
        => _logger.Log(logLevel, eventId, state, exception, formatter);

The IRequestCategoryProvider is defined and implemented as follows:

using static Microsoft.Extensions.Logging.Abstractions.Internal.TypeNameHelper;

public interface IRequestCategoryProvider
    string CreateCategory<T>();

public class RequestCategoryProvider : IRequestCategoryProvider
    private readonly IPrincipal _principal;
    private readonly IPAddress _ipAddress;

    public RequestCategoryProvider(IPrincipal principal,
                                   IPAddress ipAddress)
        _principal = principal;
        _ipAddress = ipAddress;

    public string CreateCategory<T>()
        var typeDisplayName = GetTypeDisplayName(typeof(T));

        if (_principal == null || _ipAddress == null)
            return typeDisplayName;

        var username = _principal?.Identity?.Name;
        return $"User: {username}, IP: {_ipAddress} {typeDisplayName}";

If you’re curious how to get the IPrincipal and IPAddress into this implementation (with DI). It is pretty straight-forward. In the Startup.ConfigureServices method do the following:

public void ConfigureServices(IServiceCollection services)
    // ... omitted for brevity

    services.AddTransient<IRequestCategoryProvider, RequestCategoryProvider>();
    services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();
        provider => provider.GetService<IHttpContextAccessor>()
        provider => provider.GetService<IHttpContextAccessor>()

Finally, we can Replace the implementations for the ILogger<T> by using the following:

public void ConfigureServices(IServiceCollection services)
    // ... omitted for brevity

Notice that we replace the framework-provided service as a ServiceLifetime.Transient. Opposed to the default ServiceLifetime.Singleton. This is more or less an extra precaution. We know that with each request we get the HttpContext from the IHttpContextAccessor, and from this we have the User. This is what is passed to each ILogger<T>.


This approach is valid for overriding any of the various framework-provided service implementations. It is simply a matter of knowing the correct ServiceLifetime for your specific needs. Likewise, it is a good idea to leverage the open-source libraries of the framework for inspiration. With this you can take finite control of your web-stack.

European ASP.NET Hosting :: How to Add Custom 404 and Error Pages in ASP.NET

clock January 23, 2019 10:26 by author Scott

I post this to remind myself how we got this working for both ASP.NET and static files, both for remote and local requests on IIS 7 and IIS 7.5.

<httpErrors> over <customErrors>

<customErrors> in web.config is a construct for specifying custom error pages for requests handled by ASP.NET. In other words, static files such as HTML files or directory (“friendly”) URLs are not handled.

<httpErrors> configures error pages in IIS itself, outside the web application. This handles all requests, whether they’re in fact handled by ASP.NET or IIS natively.

We ignore customErrors altogether and only use httpErrors.

Displaying a static HTML file

This is useful for error codes such as 500 where the ASP.NET web application in itself may suffer problems:

<httpErrors errorMode="Custom" defaultResponseMode="File">
    <clear />
    <error statusCode="500" path="Static\html\error.html"/>

Displaying an ASP.NET page

This displays an ASP.NET page when a 404 error occurs, without rewriting the URL (the visitor will still see the requested URL in the address bar):

<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" subStatusCode="-1" />
  <error statusCode="404" path="/Errors/404.aspx" responseMode="ExecuteURL"/>

Note that we skip the <clear /> element and simply remove the standard 404 handling (in order to avoid an exception caused by duplicate elements for the 404 status code).

Redirecting to another URL

ExecuteURL can only be used to execute an ASP.NET file within the same application. If we want to redirect to another application, or possibly an entirely different external URL, we use the Rewrite response mode with an absolute URL:

<httpErrors errorMode="Custom" existingResponse="Replace">
  <clear />
  <error statusCode="404" path="" responseMode="Redirect"/>

Make sure HTTP errors is enabled in IIS

For this to work you have to make sure the HTTP Errors feature is installed for IIS, otherwise you’ll just get an empty 404 response:

European ASP.NET Core Hosting - :: Customising model-binding conventions in ASP.NET Core

clock February 21, 2017 08:04 by author Scott

A pattern I use when building Web APIs is to create commands to represent an API operation and models to represent resources or results. We share these "common" objects with our .NET client so we can be sure we're using the same parameters names/types.

Here's an excerpt from Fabrik's API for creating a project:

public HttpResponseMessage Post(int siteId, AddProjectCommand command)
    var project = new CMS.Domain.Project(


    var model = CreateProjectModel(project);
    var link = Url.Link(RouteNames.DefaultRoute, new { controller = "projects", siteId = siteId, id = project.Id.ToIntId() });

    return Created(model, new Uri(link));

We also use commands for GET operations that have multiple parameters such as search endpoints. So instead of:

public IActionResult GetProjects(string searchTerm = null, int page = 1, int pageSize = 10)


We have a GetProjectsCommand:

public class GetProjectsCommand
    public string SearchTerm { get; set; }
    [MinValue(1, ErrorMessage = "Page must be greater than 0.")]
    public int Page { get; set; } = 1;
    public int PageSize { get; set; } = 20;

This provides a single place to encapsulate our default values and validation rules, keeping our controllers nice and lean.

Model-binding in ASP.NET Core MVC

To bind complex types to query strings in ASP.NET Web API we had to change the parameter binding rules. This is because the default was to bind complex types from the HTTP Request body.

When implementing the above pattern in ASP.NET Core I was pleasantly surprised to see that the following worked out of the box:

// GET: api/values
public IEnumerable<string> Get(GetValuesCommand command)


I thought that perhaps the framework detected that this was a HTTP GET request and therefore bound the parameter values from the query string instead.

Actually this is not the case - in ASP.NET Core, complex types are not bound from the request body by default. Instead you have to opt-in to body-based binding with the FromBodyAttribute:

// POST api/values
public void Post([FromBody]AddValueCommand command)

This seems an odd default given that (in my experience) binding complex types from the request body is far more common.

In any case, we can customise the default model-binding behaviour by providing a convention:

public class CommandParameterBindingConvention : IActionModelConvention
    public void Apply(ActionModel action)
        if (action == null)
            throw new ArgumentNullException(nameof(action));

        foreach (var parameter in action.Parameters)
            if (typeof(ICommand).IsAssignableFrom((parameter.ParameterInfo.ParameterType)))
                parameter.BindingInfo = parameter.BindingInfo ?? new BindingInfo();
                parameter.BindingInfo.BindingSource = BindingSource.Body;

Which is registered like so:

public void ConfigureServices(IServiceCollection services)
    services.AddMvc(options =>
        options.Conventions.Add(new CommandParameterBindingConvention());

This convention checks to see if the parameter type implements ICommand (a marker interface I created) and if so, instructs the framework to bind the values for this parameter from the request body.

All I have to do then is update my command with this interface:

public class AddValueCommand : ICommand
    public string Value { get; set; }

Then I can drop the unnecessary [FromBody] attribute:

// POST api/values
public void Post(AddValueCommand command)


ASP.NET 4.5 Hosting - :: Secure Your Website No Copy Paste

clock June 2, 2016 20:43 by author Anthony

Have you ever worked really hard on graphics for your site only to find later that someone has stolen them as their own. You can help encrypt and protect your site with the following codes. No right click block is 100% effective, but they will help against novices.

In the real world, sometimes a developer needs to restrict a basic facility such as cut, copy and paste on an entire web page but not on a specific control. At that time you will need some easy way to stop these kinds of facilities on the page but not create code in every control to disable these facilities.
Suppose you have 20 "TextBox" controls in your page and you want to restrict the cut, copy and paste in all the textboxes, then you do not need to write the disable code in each TextBox. In this scenario, you need to just write the disable code only in the "body" tag.
To explain such implementation, I will use the following procedure.

Step 1

Create an ASP.Net Empty Website named "My Project".

Step 2

Add a new web form named "Default.aspx" into it.

Step 3

Add 2 "TextBox" controls to the page named "Default.aspx" .

Step 4

On Cut: By this, you can disable the "Cut " facility in both of the "TextBox" Controls.
Syntax: oncut= “return false”;

On Copy: By this, you can disable the "Copy " facility in both of the "TextBox" controls.
Syntax: oncopy= “return false”;

On Paste: By this, you can disable the "Cut" facility in both of the "TextBox" controls.
Syntax: onpaste= “return false”;

To disable the All (Cut, Copy and Paste) in the entire page: ASP.NET 4.5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.


Free ASP.NET 4.5 Cloud Hosting Spain - :: Count Number of Nodes in XML File in ASP.NET 4.5

clock May 6, 2014 06:00 by author Peter

Here I will explain how to count number of records in xml file in C# using ASP.NET 4.5 Cloud Hosting Spain or how to count number of nodes in xml file in using C# and VB.NET or count number of elements in xml file in C#.

In previous articles I explained insert xml data to sql table using stored procedure, Bind xml data to dropdown/gridview in, create online poll system with percentage graphs in and many articles relating to xml, Gridview, SQL, jQuery,, C#,VB.NET. Now I will explain how to count number of records in xml file in C# using ASP.NET.

To count number of nodes from xml file we need to write the code like as shown below

XmlDocument readDoc = new XmlDocument();
int count = readDoc.SelectNodes("CommentsInformation/Comments").Count;
lblcount.InnerHtml = "Number of Records: "+ count;

If you want to see it in complete example we need to write the code like as shown below
<html xmlns="">
<form id="form1" runat="server">
<td style="width: 100px">
<td style="width: 100px">
<asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
<td style="width: 100px">
<td style="width: 100px">
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" /></td>
<br />
<label id="lblcount" runat="server" />

After that add XML file to your application and give name as "Sample.xml" then add root element in xml file otherwise it will through error. Here I added CommentInformation as root element in XML file.
<?xml version="1.0" encoding="utf-8"?>

After that add this namespace in codebehind

C# Code
using System;
using System.Xml;

After that add below code in code behind

protected void Page_Load(object sender, EventArgs e)
protected void btnSubmit_Click(object sender, EventArgs e)
XmlDocument xmldoc = new XmlDocument();
XmlElement parentelement = xmldoc.CreateElement("Comments");
XmlElement name = xmldoc.CreateElement("Name");
name.InnerText = txtName.Text;
XmlElement email = xmldoc.CreateElement("Email");
email.InnerText = txtEmail.Text;

XmlDocument readDoc = new XmlDocument();
int count = readDoc.SelectNodes("CommentsInformation/Comments").Count;
lblcount.InnerHtml = "Number of Records: "+ count;

Imports System.Xml
Partial Class vbcode
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim xmldoc As New XmlDocument()
Dim parentelement As XmlElement = xmldoc.CreateElement("Comments")
Dim name As XmlElement = xmldoc.CreateElement("Name")
name.InnerText = txtName.Text
Dim email As XmlElement = xmldoc.CreateElement("Email")
email.InnerText = txtEmail.Text
Dim readDoc As New XmlDocument()
Dim count As Integer = readDoc.SelectNodes("CommentsInformation/Comments").Count
lblcount.InnerHtml = "Number of Records: " & count
End Sub
End Class

Free ASP.NET 4.5 Hosting Spain - :: ASP.NET Validation Controls.

clock April 29, 2014 09:01 by author Peter

Today I will discuss about the various validation control that ASP.NET Hosting provide and benefit of using it over client side validation. ASP.NET validation control provide two ways validation. i.e. both Server side and Client side. They perform client-side validation if after confirming that browser allows client side validation(i.e JavaScript is enabled), thereby reducing the overhead of round trip. If client side validation is disabled, it will perform the server side validation. All this from detection to validation is all taken care by the ASP.NET.

In total ASP.NET provide 5 + 1(ValidationSummary) validation control:

  1. RequiredFieldValidator 
  2. CompareValidator
  3. CustomValidator
  4. RangeValidator
  5. RegularExpressionValidator 
  6. ValidationSummary Control      

will discuss about all the control in detail, but before that i will elaborate the attributes that are common to all the controls. 

1. Display - This attribute is used to display the error message. It takes 3 options

  • None: This will ensure that no error message is displayed. Used when Validation summary is used.
  • Static: This will ensure that space on the  page is reserved even if validation pass. i.e. Real estate area on the page will be allocated.
  • Dynamic: This will ensure that space for error message is reserved only if validation fails.

In short static and dynamic do exactly the same thing. Difference between them is that in case of static Style for the <span> is

style="visibility: hidden; color: red;"

and in case of Dynamic Style for span is

style="display: none; color: red;"

2. ControlToValidate - This attribute is used to get the control on which validation is to applied
3. EnableClientScript - Boolean value to indicate whether client- side validation is enabled or not. Default value is true.
4. IsValid - Boolean value to indicate whether the control mention is ControlToValidate attribute is valid or not. Default value is true.
5. Enabled - Boolean valued to indicate if Validation control is enabled or not. Default value is true.
6. ErrorMessage - This is the text message that will be displayed in the validation summary.

RequiredFieldValidator Control
As the name suggest, this validation control make sure that control mention in ControlToValidate cannot be empty.
<asp:TextBox ID="txtSampleTextBox" runat="server">
<asp:RequiredFieldValidator ID="reqfldValidator" runat="server" ControlToValidate="txtSampleTextBox" 
Enabled="true" Display="Dynamic" ErrorMessage="Required" ToolTip="Required">

CompareValidator Control
This Control is used to compare the value or one control to the value of another control or to a fixed value. One catch here is that validation pass if both the fields are empty. To handle that one require to apply Required field validator along with CompareValidator.
<asp:TextBox ID="TextBox1" runat="server" />
<asp:TextBox ID="txtTextBox2" runat="server" />
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="txtTextBox1" ControlToCompare="txtTextBox2" Display="Dynamic" ValidationGroup="MyGroup" ToolTip="No Match">*</asp:CompareValidator>

ControlToCompare - This take the Id of control with which comparison is being done.
Comparison can be made on following data types: Currency, Date, Double, Integer and String

As the name suggest this control is used to make sure that data entered by the user fall within the specified range. Again as for Compare validator validation will pass if input control is empty. Use RequiredFieldValidator to fix this issue.
<asp:TextBox ID="TextBox1" runat="server" ValidationGroup="MyGroup" />
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txtTextBox1" MaximumValue="800"
MinimumValue="5" ValidationGroup="MyGroup" Display="Dynamic" Type="String" ToolTip="Error">*</asp:RangeValidator>

A little explanation for this validator. It has a Type attribute that signifies the datatype for Range. In above example datatype is string with MinimumValue="5" and MaximumValue="100". The validation goes like it will accept all the value that satisfy the regex ^[5-8]+$. A little confusing but will get clear after 2 3 reading.

This is one of my favorite validator control. This control provide maximum level of flexibility to the developer and almost all the validator control function can be achieved using this validator control. RegularExpressionValidator control has attribute ValidationExpression that is used to specify the regular expression that is used to validate the input control.

<asp:TextBox ID="TextBox1" runat="server" ValidationGroup="MyGroup" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"  

ValidationGroup="MyGroup" Display="Dynamic" ValidationExpression="^[5-8]+$" ToolTip="Error">*</asp:RegularExpressionValidator>

CustomValidator Control: Custom validator control is used to capture the validation that cannot be handled by the validator controls provided by ASP.NET. Here user is at the freedom to define his own custom method, both Client side and Server side. 
<asp:TextBox ID="TextBox1" runat="server" ValidationGroup="MyGroup" />
<asp:CustomValidator runat="server" ClientValidationFunction="YouClientValidationFunction" ControlToValidate="txtTextBox1" ID="cstmValidatorControl" OnServerValidate="ServerSideMethod" ValidateEmptyText="true" ToolTip="Error">*</asp:CustomValidator>

ValidateEmptyText  is a boolean attribute that if set to true, the input control will be validated even if it is empty.
ClientValidationFunction contains name of client validation function.
OnServerValidate contains name of server validation function.

ValidationSummary Control
This control is used to display the list of all the validation error that has occurred on the page. The error message displayed is the one set for the ErrorMessage attribute of the validation control. No error message will be displayed if this attribute is not set.  
<asp:TextBox ID="TextBox1" runat="server" ValidationGroup="MyGroup" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtTextBox1" ValidationGroup="MyGroup" Display="Dynamic" ValidationExpression="^[5-8]+$" ErrorMessage="Error" ToolTip="Error">*</asp:RegularExpressionValidator>

<asp:Button runat="server" ID="Button1" ValidationGroup="MyGroup" Text="Submit" />
<asp:ValidationSummary runat="server" ID="ValidationSummary1" ShowMessageBox="true" ValidationGroup="MyGroup" ShowSummary="true" DisplayMode="BulletList" />

DisplayMode has three options List, BulletList and SingleParagraph
ShowMessageBox when set to true will display the error as a alert popup
ShowSummary will display the error on the page. By default it is true.

Free Italy ASP.NET 4.5 Hosting - :: Programmatically Clearing The ASP.NET Cache For Web Forms and MVC Pages

clock April 16, 2014 06:01 by author Peter

Page level caching for ASP.NET 4.5 web forms and MVC websites is pretty awesome, because it allows you to implement something that's quite complex; multilevel caching, without having to really understand too much about caching, or even write much code. But what if you want to clear a cached page before it's due to expire.

What page caching aims to achieve

When developers turn to caching pages in their websites, usually it's because of one thing; the need for speed. When our code bases start to require continual requests to a data store, be it disk or database, that doesn't change too much overtime, caching is usually the first hammer we turn to to minimise fetching from slower stores. ASP.NET Web Forms and ASP.Net MVC both make this a pretty trivial thing to do by hiding the complexity of cache providers behind simple attributes to either your .aspx pages or controller actions:

WebForms page output caching example:

<%@ OutputCache Duration="300" VaryByParam="productId" %> MVC controller caching:
[OutputCache(Duration = 300, VaryByParam = "prodId")]
public ActionResult ProductDetails(string prodId)


The above is awesome because it's simplicity, but you'll notice one key thing here: I've set my cache expiry to 300 seconds. This is primarily because I want the content to pull from the source now and then just in case something has changed. I've used 300 seconds, but really the time may be inconsequential – I've just set it to an arbitrary number that I deemed would meet my needs.

This doesn't really use the cache as well as it could be used in many scenarios, the primary one being during a period where my site isn't being updated, and the content only changes once every few days/weeks/months. The .NET tooling attempts to allow for these situations by having support for providers like the SQLCacheDependency you can add to your application. But the SQL cache provider or even a CustomCacheProvider don't give you the fine grain control you really want: being able to programmatically remove page, control, action or child-action level cached pages. Like most great things: simple and elegant does support this out of the box – you just don't hear about it much. You can tell the runtime to remove cached pages and controls simply by using a very simple recursive API that refers to it's relative URL.

// remove any webforms cached item with the wildcard default.aspx*
// just remove the webforms product page with the prodId=1234 param
// remove my MVC controller action's output
HttpResponse.RemoveOutputCacheItem(Url.Action("details", "product", new { id = 1234 }));

You'll notice for the MVC page's cache reference I used the Url.Action helper, and I recommend this, as it uses the same MVC routing as the cache provider – usually taking the first route found. Using the Url.Action helper means your provided Url follows the same path in reverse to that of the cache provider. For MVC child actions there is currently no way that I know of clearing individual control's caches. MVC controller child actions are stored in the ChildActionCache. To clear the entire child action cache you can do the following:

OutputCacheAttribute.ChildActionCache = new MemoryCache("NewRandomStringNameToClearTheCache");

Obviously this is a pretty aggressive approach, but if you would like to do this in a more granular fashion, try the open source project MVC Doughnut caching instead.

FREE ASP.NET 4.5 Spain Hosting – :: GridView and Export to Excel

clock March 29, 2014 18:18 by author Peter

This is very simple to implement in ASP.NET 4.5 Hosting. But, there are possibilities to get problems in exporting to excel from grid view. When you bind data to gridview and write some logic to export to excel then it will not be enough. We have to check or write some additional logic which will help us to solve the problems. Below is the explanation for all problems we may get in the complete process along with detailed solution. You may encounter below errors when you try to implement the export to excel for gridview.

Control of type "GridView" must be placed inside of the form tag with runat="server"
This is very well known error to ASP.NET developers and by seeing it, we think that the control is not inside the form with runat server. But this is not correct. This error will come even if we put the GridView inside form with runat server. The reason is, in the export to excel logic we are calling RenderControl() method of GridView. So, to render it without any issues we have to override the "VerifyRenderingInServerForm" in our code.  Below is the syntax of the event. Add this to the c# code in code behind file. Remember this event is a Page event means this method you should place in ASPX page. If you are using user control to implement this export to excel logic then below are the ways to go.

1. If your user control is using by less than 3-4 pages then go to each and every page and add this event to the page.

2. If your user control is using by more than 5 pages then the best solution is to create a base page [Which inherits from System.Web.UI.Page class] and all your ASPX pages should inherit from this base page.public override void VerifyRenderingInServerForm(Control control)  

    //Confirms that an HtmlForm control is rendered for the specified ASP.NET   
    //server control at run time. 

Now, after we added the event to page, the error will go away for sure. Even when you add the above code/event to the page, this is not enough if you have the paging, sorting enabled on gridview. If you enable paging or sorting then you encounter the below error.

"RegisterForEventValidation can only be called during Render();"

This error is coming because we are doing paging and sorting. If no paging or sorting enabled this error will not come. To resolve this error, please follow below steps.

1. In your export to excel button click event, first disable the paging, sorting on gridview and do data bind.
2. Call export to excel logic.
3. Re-enable paging, sorting on gridview and databind.

Below is the logic we have to use in export to excel button click event.

gvReport.AllowPaging = false;  
    gvReport.AllowSorting = false;  
    ExportToExcel();//Method to use export to excel.  
    gvReport.AllowPaging = true;  
    gvReport.AllowSorting = false;  

Now, you are clear with all errors and the logic will export all data in gridview to excel.

FYI, I am placing a sample of ExportToExcel() functionality here.

private void ExportToExcel()  
        Response.AddHeader("content-disposition", string.Format("attachment;filename=excel_report.xls"));  
        Response.Charset = ""; 
        // Response.Cache.SetCacheability(HttpCacheability.NoCache);  
        Response.ContentType = "application/vnd.xls";  
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();  
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);  

Note: gvReport is the gridview control name in my example. And there are lot of posts in internet guide you incorrect to resolve the above error. For example, they will say set EnableEventValidation="false" in the <%@ Page directive Or disable validation in web.config level to resolve the error. Please do not set it.

ASP.NET Hosting - Belgium - :: Basic Authentication with ASP.NET Web API Using Authentication Filter

clock March 10, 2014 07:42 by author Peter

Authorization filters and action filters have been around for a while in ASP.NET Web API but there is this new authentication filter introduced in Web API 2. Authentication filters have their own place in the ASP.NET Web API pipeline like other filters. Historically, authorization filters have been used to implement authentication and there is ton of samples out there with all kinds of authentication implemented in authorization filters. Web API 2 introduces the authentication filter so that authentication concerns can be separated out of authorization filter and put into an authentication filter.

This blog post is just a quick introduction to writing a custom authentication filter for implementing HTTP Basic Authentication. There is a full-blown example here, if you are interested in writing a production-strength filter.First up, we create the filter class BasicAuthenticator implementing the IAuthenticationFilter interface. We also derive from Attribute so that we can apply the filter on action methods, like so.

public class EmployeesController : ApiController
    [BasicAuthenticator(realm: "Magical")]
    public HttpResponseMessage Get(int id)
        return Request.CreateResponse<Employee>(
        new Employee()
            Id = id,
            FirstName = "Johnny",
            LastName = "Law"

There are two interesting methods that we need to implement in the filter – (1) AuthenticateAsync and (2) ChallengeAsync.

AuthenticateAsync contains the core authentication logic. If authentication is successful, context.Prinicipal is set. Otherwise, context.ErrorResult is set to UnauthorizedResult, which basically gets translated to a “401 – Unauthorized” HTTP response status code.

public class BasicAuthenticator : Attribute, IAuthenticationFilter
    private readonly string realm;
    public bool AllowMultiple { get { return false; } }
    public BasicAuthenticator(string realm)
        this.realm = "realm=" + realm;
    public Task AuthenticateAsync(HttpAuthenticationContext context,
                                  CancellationToken cancellationToken)
        var req = context.Request;
        if (req.Headers.Authorization != null &&
                          "basic", StringComparison.OrdinalIgnoreCase))
            Encoding encoding = Encoding.GetEncoding("iso-8859-1");
            string credentials = encoding.GetString(
            string[] parts = credentials.Split(':');
            string userId = parts[0].Trim();
            string password = parts[1].Trim();
            if (userId.Equals(password)) // Just a dumb check
                var claims = new List<Claim>()
                    new Claim(ClaimTypes.Name, "badri")
                var id = new ClaimsIdentity(claims, "Basic");
                var principal = new ClaimsPrincipal(new[] { id });
                context.Principal = principal;
            context.ErrorResult = new UnauthorizedResult(
                     new AuthenticationHeaderValue[0],
        return Task.FromResult(0);
    public Task ChallengeAsync(
                     HttpAuthenticationChallengeContext context,
                            CancellationToken cancellationToken) {}

For basic authentication, when there is a 401, we are supposed to send WWW-Authenticate header and the right place to write such challenge related logic will be the ChallengeAsync method. This is where things get interesting because it is not so straight forward to add headers here. The recommended approach is to create a class implementing IHttpActionResult and set an instance of it to context.Result, like so.

public Task ChallengeAsync(HttpAuthenticationChallengeContext context,
                                      CancellationToken cancellationToken)
    context.Result = new ResultWithChallenge(context.Result, realm);
    return Task.FromResult(0);

Here is the result class. The crux of this class is in the ExecuteAsync method and that is where we set the WWW-Authenticate response header indicating the scheme and the realm.

public class ResultWithChallenge : IHttpActionResult
    private readonly IHttpActionResult next;
    private readonly string realm;
    public ResultWithChallenge(IHttpActionResult next, string realm)
    { = next;
        this.realm = realm;
    public async Task<HttpResponseMessage> ExecuteAsync(
                                CancellationToken cancellationToken)
        var res = await next.ExecuteAsync(cancellationToken);
        if (res.StatusCode == HttpStatusCode.Unauthorized)
               new AuthenticationHeaderValue("Basic", this.realm));
        return res;

For setting the WWW-Authenticate response header, we created a class. However, it is possible to get away without creating one, like this.

public Task ChallengeAsync(HttpAuthenticationChallengeContext context,
                               CancellationToken cancellationToken)
    var result = await context.Result.ExecuteAsync(cancellationToken);
    if (result.StatusCode == HttpStatusCode.Unauthorized)
                new AuthenticationHeaderValue(
                    "Basic", "realm=" + this.realm));
    context.Result = new ResponseMessageResult(result);

However, this approach will not work with MVC since there is no ResponseMessageResult. For the sake of consistency, it is better to create our own class. Also, the code above changes the pipeline behavior slightly. For these reasons, it is recommended to create a class implementing IAuthenticationFilter (the initial approach in this post).

About is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.

Tag cloud

Sign in