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 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).

ASP.NET 4.5.1 Germany Hosting - :: ASP.NET Session and Concurrent Access

clock March 5, 2014 05:35 by author Peter

In one of my projects I found some a strange at first sight issue related to concurrent Session usages. During one long request the other parallel requests were waiting until the previous one is finished.This issue occurs when user tries to download file from ashx-handler. Handler requires Session to get some user-related configuration which is stored there. I've tried to dig deeper and that what I've found. By default no concurrent access to the session state is allowed. Requests with same SessionID will be locked exclusively to prevent potential corruption of its state. This topic contains only brief information about ASP.NET, if you want to be more familiar with ASP.NET, you should try

When you have request1 `in progress` and trying to do request2 - Session object will be locked by request1 and our code in request2 will be waiting for request1 completed. ASP.NET Session is thread safe and synchronization mechanism is based on System.Threading.ReaderWriterLock. This means that we can do many reads but only one writing at the same time. ASP.NET Session object is configured for full (read\write) access, by default. That's why we need to configure Session object as 'read-only' on long-term pages to have non-blocking access to Session object from other pages. Be aware that even you don't use Session object explicitly you have this issue too.

How to reproduce

To reproduce this issue let's create 2 pages.

Default page:

<%@ Page Language="C#" %>

<script runat="server">
  protected void Page_Load(object sender, EventArgs e)
      Response.Write("Hello, SessionId " + Session.SessionID);

Slow page (contains some long-term execution):

<%@ Page Language="C#" %>

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
        Response.Write("Hello, SessionId " + Session.SessionID);


    <sessionState mode="InProc"/>

To resolve this issue we can re-configure ASP.NET Session object access. Session state is configured by using the sessionState element of the system.web configuration section. If you need non-blocking access to read from Session:

<%@ Page Language="C#" EnableSessionState="ReadOnly"%>

If you don't need Session:

<%@ Page Language="C#" EnableSessionState="False"%>

ASP.NET European Hosting - :: ASP.NET Identity

clock February 21, 2014 08:51 by author Peter

ASP.NET Identity provides an implementation of user and and rolemanagement. ASP.NET Identity does not do authentication. Cookie based authentication and redirects to external login providers such as Google and Facebook is handeled by the OWIN libraries. ASP.NET Identity is only concerned with creation of users and roles, and persisting information about users such as passwords, links to external login providers and claims. This functionality is provided by classes in the two assemblies

1. Microsoft.AspNet.Identity.Core - Core user and role management logic

2. Microsoft.AspNet.Identity.EntityFramework - EnitityFramework based persistence of Users, Roles, Claims etc.

Identity Core - user management logic

Identity.Core has two main classes which will be our main means to interact with ASP.NET Identity. They are named UserManager and RoleManager. UserManager is probably the most important one, and is the only one that are used in the AccountController that is created by the default templates for e.g. an MVC when you choose "Individual User Accounts".

The UserManager is used to add/create, find/get and remove:

1. Users
2. Passwords
3. Claims
4. Link to roles
5. Link to logins

A UserStore that is responsible for the persistence is injected into the UserManager. The usermanager will use the UserStore to perform all it's needs for persistence. The UserManager is a generic class that has a TUser type parameter. TUser must be a class that implements the IUser interface, which means that a User class needs to have a Id getter of string type and a UserName string property.

Developers often asks why Microsoft chose to type the Id as string instead of int. It is true that if we implement our own UserStore then we are free to use a different type for our primary key, but it is a bit inconvenient that this key can not be named "Id". IUser which we must implement already defines a string Id get'er.

Identity EntityFramework - Entity framework code first persistence

The classes of the Identity Core assembly require a persistence mechanism. Microsoft has provided a Entity Framework code first based implementation to us in the assembly Microsoft.AspNet.Identity. The Identity EntityFramework assembly provides a UserStore implementation that can be plugged right into the UserManager from the Core assembly. This is by far our easiest option to get started with ASP.NET Identity. In fact if you create a new MVC project and choose Individual User Accounts the template will create a working implementation for you right away.

The model consist of a IdentityUser and the following related objects:

1. IdentityUserClaim. A list of claims for the user

2. IdentityUserLogin. This is only used for external logins. Links the local user to an external account

3. IdentityRole. If you use roles this is where the roles and mapping from user to roles will be stored.

Simplicity comes at a price

This simplicity comes at a price though. The UserStore require us to not only have our user class implement the IUser interface, it also demands that we need to inherit from the ASP.NET Identity EntityFramework class called IdentityUser which adds two new properties to the IUser interface. The hashed password and a SecurityStamp is stored on the user. Many developers and myself included are not too happy about being forced to have a reference to EntityFramework and ASP.NET EntityFramework from our domain model assembly and that we are required to inherit from this IdentityUser class, but if we want to have the simplicity of just using the Microsoft Identity persistence then we just have to swallow that one.

The UserStore will by default create a DbContext that in turn will create five tables for us, one for each of the entities in the model.

1. AspNetUsers - for storing IdentityUser

2. AspNetUserClaims - for storing IdentiyUserClaim

3. AspNetUserLogin - for storing IdentityUserLogin

4. AspNetRoles - for storing IdentityRole

5. AspNetUserRoles - for storing the many-to-many relation between IdentityUser and IdentityRole

The table names and the Entity Framework configuration of relations between the entities are configured in the OnModelCreating method of the IdentityDbContext that the UserStore will create if we don't provide our own DbContext. If we want to use different table names or map things differently in our database we need to provide our own DbContext. We can either create a completely new DbContext class with the 5 required DbSets (one for each of the model classes) or we can simply subclass the IdentityDbContext and override the OnModelCreating method where we can configure the EF mappings as we wish.

What next?

As I wrote in my previous post I was hoping that Microsoft would remove the requirement of having to inherit the IdentityUser. As we have seen, it didn't happen.

If we want to use the stock implementation in the form of ASP.NET Identity EntityFramework we have to inherit from the IdentityUser class. Still, what they did do was refactor the implementation into two clearly separate concerns. The core assembly containing the core logic and the EntityFramework assembly containing EF persistence. It's the latter that forces me to do things I don't like, and because the designers has made this clean separation it is possible for me to opt out of the EF persistence implementation while still use the user management logic in the Core assembly. In my next post I will show how to write my own UserStore class. To show that the ASP.NET Identity model is flexible and in no way tied to Entity Framework or SQL server I will be persisting my user data to a MongoDatabase instead of using Entity Framework.

ASP.NET 4.5.1 France Hosting - :: How to restrict size of file upload in ASP.NET

clock February 10, 2014 06:49 by author Peter

I have one page that contains one file upload control to accept files from user and saving it in one folder. I have written code to upload file and saving it to folder it’s working fine after completion of my application my friend has tested my application like he uploaded large size file nearly 10 MB file at that time it’s shown the error page like “the page cannot displayed”. This topic contains only brief information about ASP.NET, if you're loooking for ASP.NET Hosting and want to be more familiar with ASP.NET, you should try

Again I have search in net I found that file upload control allows maximum file size is 4MB for that reason if we upload file size larger than 4MB we will get error page like “the page cannot displayed” or “Maximum request length exceeded”. After that I tried to increase the size of uploaded file by setting some properties in web.config file like this:

 <httpRuntime executionTimeout="9999" maxRequestLength="2097151"/> 

Here httpRuntime means: Configures ASP.NET HTTP runtime settings. This section can be declared at the machine, site, application, and subdirectory levels.

executionTimeout means: Indicates the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.

maxRequestLength means: Indicates the maximum file upload size supported by ASP.NET. This limit can be used to prevent denial of service attacks caused by users posting large files to the server. The size specified is in kilobytes. The default is 4096 KB (4 MB).

After that write the following code in aspx page

 <html xmlns=""> 
 <head id="Head1" runat="server"> 
 <title>Untitled Page</title> 
 <form id="form1" runat="server"> 
 <asp:FileUpload ID="FileUpload1" runat="server" /> 
 <br /> 
 <asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" /> 
 <br /> 
 <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> 
 After that write the following code in code behind 
 protected void btnUpload_Click(object sender, EventArgs e) 
 if (FileUpload1.HasFile) 
 if (FileUpload1.PostedFile.ContentLength < 20728650) 
 Label1.Text = "File name: " + 
 FileUpload1.PostedFile.FileName + "<br>" + 
 FileUpload1.PostedFile.ContentLength + " kb<br>" + 
 "Content type: " + 
 catch (Exception ex) 
 Label1.Text = "ERROR: " + ex.Message.ToString(); 
 Label1.Text = "File size exceeds maximum limit 20 MB."; 

After that write the following code in web.config

 <httpRuntime executionTimeout="9999" maxRequestLength="2097151"/> 

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 2012 Hosting, ASP.NET 4.5 Hosting, ASP.NET MVC 4 Hosting, ASP.NET MVC 5 Hosting and SQL 2014 Hosting.

Tag cloud

Sign in