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 FREE ASP.NET 4.5 Hosting Germany - HostForLIFE.eu :: ASP.NET 4.5 Hosting With Full Trust Level

clock March 17, 2014 10:59 by author Scott

There are many different levels of web hosting services for us to choose nowadays, the common web hosting types are ASP.NET shared hosting, Windows VPS and Windows dedicated server. To most of individuals and small businesses, I think the price should be the first thing we’ve to care about, so the ASP.NET shared hosting service should be the most popular type.

What’s ASP.NET 4.5 shared hosting trust level?

You need to check many aspects before choosing a .Net hosting provider, those aspects should include .Net MVC framework, SQL Server, disk space, monthly bandwidth, hosting prices, but there’s one thing you may ignore really – “IIS Security Trust Level”.

If you’re not familiar with what’s asp.net 4.5 shared hosting trust level, here I’d like to bring you a short introduction. The trust level is real important that could affect with your site secure and performance, and a full trust level means higher risk for hackers sneak into server to make destroy. Most of small .Net hosts only can give medium trust level on their servers. If your applications need to be run a full trust mode, then you’ve to look for a web host which can give full permission to you.

<system.web>
<securityPolicy>
<trustLevel name="High" policyFile="web_hightrust.config"/>
<trustLevel name="Medium" policyFile="web_mediumtrust.config"/>
<trustLevel name="Low" policyFile="web_lowtrust.config"/>
<trustLevel name="Minimal" policyFile="web_minimaltrust.config"/>
</securityPolicy>
</system.web>

You can see there are 4 trust levels for web hosts to pre-set by default – Minimal trust, Low trust, Medium trust and High / Full trust. High trust means higher risk for hackers to sneak into server, most of Windows hosting companies doesn’t allow their customers to run full trust level by default.

- Full Trust allows the users to do everything of application pool on one Windows web server. Some of applications cannot work properly under a medium trust web server, full trust means more flexible and you’re also able to change to medium trust once your application don’t need full trust.
- Medium Trust level websites are limited to access the file system and not so flexible as full trust level web server.
- Low Trust & Minimal Trust level are 2 options to restrict the users heavily, it won’t allow users to connect to server actively. At present, there’s no Windows hosts offering such asp.net shared hosting plan yet.

Who’s best ASP.NET 4.5 full trust web hosting?

I’ve to say that’s not easy to choose a best asp.net web hosting provider, since you’ve to check many aspects before making a decision, such as you should check:

1. How’s their server performance and reliability?
2. How much disk space and bandwidth can you receive?
3. How many MsSQL databases can you create?
4. Does it support IIS url-rewrite and isolated application pool?
5. How’s their technical support team?

and more..

Why you should choose HostForLIFE.eu for full trust ASP.NET hosting?

The reason is simple, HostForLIFE.eu web solutions started business since 2008 and we’ve been focusing on providing quality Microsoft Windows platform server over 6 years. We always the first web host to offer newest Microsoft technologies to their users. Whatever you need for your website, you can trust your site with us



ASP.NET Hosting - Belgium - HostForLIFE.eu :: 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 &&
                req.Headers.Authorization.Scheme.Equals(
                          "basic", StringComparison.OrdinalIgnoreCase))
        {
            Encoding encoding = Encoding.GetEncoding("iso-8859-1");
            string credentials = encoding.GetString(
                                  Convert.FromBase64String(
                                      req.Headers.Authorization
                                                   .Parameter));
            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;
            }
        }
        else
        {
            context.ErrorResult = new UnauthorizedResult(
                     new AuthenticationHeaderValue[0],
                                          context.Request);
        }
 
        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)
    {
        this.next = next;
        this.realm = realm;
    }
 
    public async Task<HttpResponseMessage> ExecuteAsync(
                                CancellationToken cancellationToken)
    {
        var res = await next.ExecuteAsync(cancellationToken);
        if (res.StatusCode == HttpStatusCode.Unauthorized)
        {
            res.Headers.WwwAuthenticate.Add(
               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)
    {
        result.Headers.WwwAuthenticate.Add(
                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 - HostForLIFE.eu :: 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 asp.net 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 HostForLife.eu

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 asp.net pages.

Default page:

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

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

Slow page (contains some long-term execution):

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

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(10000);
        Response.Write("Hello, SessionId " + Session.SessionID);
    }
</script>

web.config

<configuration>
  <system.web>
    <sessionState mode="InProc"/>
  </system.web>
</configuration>

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"%>



HostForLIFE.eu Proudly Announces ASP.NET MVC 5.1.1 Hosting

clock February 28, 2014 11:03 by author Peter

European Recommended Windows and ASP.NET Spotlight Hosting Partner in Europe, HostForLIFE.eu, has announced the availability of new hosting plans that are optimized for the latest update of the Microsoft ASP.NET MVC 5.1.1 technology.  HostForLIFE.eu - a cheap, constant uptime, excellent customer service, quality and also reliable hosting provider in advanced Windows and ASP.NET technology. They proudly announces the availability of the ASP.NET MVC 5.1.1 hosting in their entire servers environment.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. You can start hosting your ASP.NET MVC 5.1.1 site on their environment from as just low €3.00/month only.

ASP.NET MVC 5.1.1  is the latest update to Microsoft's popular MVC (Model-View-Controller) technology - an established web application framework. MVC enables developers to build dynamic, data-driven web sites. ASP.NET MVC 5.1.1 adds sophisticated features. ASP.NET MVC 5.1.1  gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and that gives you full control over markup. For additional information about ASP.NET MVC 5.1.1 Hosting offered by HostForLIFE.eu, please visit http://hostforlife.eu/European-ASPNET-MVC-511-Hosting

About HostForLIFE.eu

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



ASP.NET European Hosting - HostForLIFE.eu :: 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.



European HostForLIFE.eu Proudly Launches Windows Server 2012 R2 Hosting

clock February 17, 2014 10:16 by author Peter

HostForLIFE.eu proudly launches the support of Windows Server 2012 R2 on all their newest Windows Server environment. On Windows Server 2012 R2 hosted by HostForLIFE.eu, you can try their new and improved features that deliver extremely high levels of uptime and continuous server availability start from €3.00/month.

Microsoft recently released it’s latest operating system Windows Server 2012 R2 to global customers. Microsoft Windows Server 2012 R2 is much more than just another service pack; adding new features that make it easier to build cloud applications and services in your datacenter.

Delivering on the promise of a modern datacenter, modern applications, and people-centric IT, Windows Server 2012 R2 provides a best-in-class server experience that cost-effectively cloud-optimizes your business. When you optimize your business for the cloud with Windows Server 2012 R2 hosting, you take advantage of your existing skillsets and technology investments.

You also gain all the Microsoft experience behind building and operating private and public clouds – right in the box. Windows Server 2012 R2 offers an enterprise-class, simple and cost-effective solution that’s application-focused and user centric.

Further information and the full range of features Windows Server 2012 R2 Hosting can be viewed here: http://hostforlife.eu/European-Windows-Server-2012-R2-Hosting

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



ASP.NET 4.5.1 France Hosting - HostForLIFE.eu :: 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 HostForLIFE.eu.

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:

 <system.web> 
 <httpRuntime executionTimeout="9999" maxRequestLength="2097151"/> 
 </system.web> 

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="http://www.w3.org/1999/xhtml"> 
 <head id="Head1" runat="server"> 
 <title>Untitled Page</title> 
 </head> 
 <body> 
 <form id="form1" runat="server"> 
 <div> 
 <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> 
 </div> 
 </form> 
 </body> 
 </html> 
 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) 
 { 
 try 
 { 
 Label1.Text = "File name: " + 
 FileUpload1.PostedFile.FileName + "<br>" + 
 FileUpload1.PostedFile.ContentLength + " kb<br>" + 
 "Content type: " + 
 FileUpload1.PostedFile.ContentType; 
 } 
 catch (Exception ex) 
 { 
 Label1.Text = "ERROR: " + ex.Message.ToString(); 
 }  
 } 
 else 
 { 
 Label1.Text = "File size exceeds maximum limit 20 MB."; 
 } 
 } 
 } 


After that write the following code in web.config

 <system.web> 
 <httpRuntime executionTimeout="9999" maxRequestLength="2097151"/> 
 </system.web>



ASP.NET France Hosting - HostForLIFE.eu :: How to consume an XML feed in ASP.NET – RSS

clock February 5, 2014 15:41 by author Peter

In this example i am showing how to use Cross Page Posting or Postback In ASP.NET 2.0, 3.5, 4.0 Using C#. Cross Page posting is used to submit a form on one page (say default.aspx) and retrieve values of controls of this page on another page (say Default2.aspx). There are two ways we can use cross page postsbacks in ASP.NET.

1st method
In this i've created a Default.aspx page with two textbox and one button , button click will post back to Default2.aspx and there we will retrieve and show values of both textboxes Html source of Default.aspx page is like

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

<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
First Name:
<asp:TextBox ID="txtFirstName" runat="server">
</asp:TextBox><br /><br />
Last Name:
<asp:TextBox ID="txtLastName" runat="server">
</asp:TextBox><br /><br /><br />
       
<asp:Button ID="btnSubmit" runat="server"
            OnClick="btnSubmit_Click"
            PostBackUrl="~/Default2.aspx"
            Text="Submit to Second Page" /><br />
</div>
</form>
</body>
</html>

Don't forget to set PostBackUrl Property of Button
PostBackUrl="~/Default2.aspx"

Now to retrieve values of textBoxes on Default2.aspx page, write below mentioned code in Page_Load event of second page (Default2.aspx)

protected void Page_Load(object sender, EventArgs e)

{
    //Check whether previous page is cross page post back or not
    if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
    {
        TextBox txtPbFirstName = (TextBox)PreviousPage.FindControl("txtFirstName");
        TextBox txtPbLastName = (TextBox)PreviousPage.FindControl("txtLastName");
        Label1.Text = "Welcome " + txtPbFirstName.Text + " " + txtPbLastName.Text;
    }
    else
    {
        Response.Redirect("Default.aspx");
    }
}

If you are using masterpages then you need to write code to FindControl as mentioned below

ContentPlaceHolder exampleHolder =(ContentPlaceHolder)Page.PreviousPage.Form.FindControl ("Content1"));
TextBox txtExample = exampleHolder.FindControl("txtFirstName");

2nd Method
Using Property to expose and Consume values of TextBox
If we are using this method then we don't need to use FindControl method at all
For this we need to create property in code behind of the page to be cross page post back (Default.aspx)
Html of the page needs no changes ,
C# code behind for Default.aspx
public TextBox pbTxtFirstName
    {
        get
        {
            return txtFirstName;
        }
    }
 
    public TextBox pbTxtLastName
    {
        get
        {
            return txtLastName;
        }
    }

Now write this code in page_Load event of second page to retrieve values of controls

protected void Page_Load(object sender, EventArgs e)
{
    if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
    {
        Label1.Text = "Welcome " + PreviousPage.pbTxtFirstName.Text + " " + PreviousPage.pbTxtLastName.Text;
    }
    else
    {
        Response.Redirect("Default.aspx");
    }
}



ASP.NET 4 European Hosting - HostForLIFE.eu :: Tips to Improve ASP.NET Application Performance

clock February 4, 2014 06:35 by author Peter

Web application is designed to handle hundreds and thousands of requests per seconds so to handle these requests effectively and successfully it is important to resolve any potential performance bottlenecks. Now we will state some tips that improve the performance of your web application. Try HostForLife.eu, only with € 3.00/month, you can get a reasonable price with best service. This topic contains only brief information about ASP.NET, if you want to be more familiar with ASP.NET, you should try HostForLife.eu.

1. Cache Commonly used objects
You can cache commonly used objects in ASP.Net using Cache class that provides an extensive caching mechanism that storing resources and allow you to:

- Define an expiration for a cached object either by specified a TimeSpan or a fixed DateTime.

- Define priority for cached objects. when there is a memory lack and objects need to be freed.

- Define validity for a cached object by adding dependacies

- Attach callbacks to cached objects,so when an objects is removed from cache the callback is invoked.

you can add objects to cache by adding it to cache Dictionary.

Cache["Mykey"] = myObject;

or using Insert method of Cache class

Cache.Insert("MyKey",myObject, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(60), dependacies : null );

2. Using Asynchronous Pages,Modules and Controllers
When IIS passes a request to ASP.NET, the request is queued to the thread pool and a worker thread is assigned to handle this request. the worker thread is limited so any new request will be queued to be handle after the current requests handled. If a request need to do some I/O operation like retrieving data from  a database or calling web service that mean you need to reduce the request time.

You can change I/O operation in your web page by making it as Asynchronous Page. In ASP.NET you can do that by firstly marking the page as async

<%@ Page Async="true"....

then create new PageAsyncTask object and pass it the delegates for the begin, end, and timeout methods. After creating PageAsyncTask object, call the Page.RegisterAsuncTask method to start the asynchronous opertaion.

public partial class MyAsyncPage : System.Web.UI.Page
{
   private SqlConnection _sqlConnection;
   private SqlCommand _sqlCommand;
   private SqlDataReader _sqlReader;

   IAsyncResult BeginAsyncOp(Object sender, EventArgs e, AsyncCallback cb, Object state)
   {
       // this method will be executed in the original worker thread,
       //so don't do any lengthy operation here
       _sqlcommand = CreateSqlCommand(_sqlConnection);
       return _sqlCommand.BeginExecuteReader();
   }
   void EndAsyncOp(IAsyncResult asyncResult)
   {
       _sqlReader = _sqlCommand.EndExecuteReader(asyncResult);
       // read the data and build page contents
       .............
   }
   void TimeoutAsyncOp(IAsyncResult asyncResult)
   {
       _sqlReader = _sqlCommand.EndExecuteReader(asyncResult);
       // read the data and build page contents
       .............
   }
   public override void Dispose()
   {
       if(_sqlConnection != null)
       {
           _sqlConnection.Close();
       }
   }
   protected void btnClick_Click(Object sender, EventArgs e)
   {
       PageAsyncTask task = new PageAsyncTask( new BeginEventHandler(BeginAsyncOp),
                                               new EndEventHandler(EndAsyncOp),
                                               new TimeoutEventHandler(TimeoutAsyncOp),
                                               state : null);
       RegisterAsyncTask(task);
   }
}

There is another way to create async pages is by using completion events.

public partial class MyAsyncPage2 : System.Web.UI.Page
{
   protected void btnGetData_Click(Object sender , EventArgs e)
   {
       Services.MyService serviceProxy = new Services.MyService();
       serviceProxy.GetDataCompleted +=Services.GetDataCompletedEventHandler(GetData_Completed);
       serviceProxy.GetDataAsync();
   }
   void GetData_Completed(Object sender,Services.GetDataCompletedEventArgs e)
   {
       //Extract the result from the event args and build the page's content
   }

}

In ASP.NET MVC you can create such mechanisme by creating Asynchronous Controller. To create such contoller you need to follow these four steps:

- Create a Controller class that inherits from the AsyncController type.

- Implement  a set of action methods for each async operation according to the following convention, where xx is the name of the action: xxAsync and xxCompleted.

- In the xxAsync method, call the AsyncManager.OutstandingOperations.Increment method with the number of asynchronous operations you are about to perform.

- In the code which executes during the return of the async operation, call the AsyncManager.OutstandingOperations.Decrement method to notify the operation has completed.

The following code shows you how to implement these steps:

public class MyController : AsyncController
{
   public void IndexAsync()
   {
       AsyncManager.OutStandingOperations.Increment();      
       MyService serviceProxy = new MyService();
       serviceProxy.GetDataCompleted += (sender , e) => {
                                        AsyncManager.Parameters["result"] = e.Value;
                                        AsyncManager.OutStandingOperations.Decrement();
                                        };
       serviceProxy.GetHeadlinesAsync();
   }
   public ActionResult IndexCompleted(MyData result)
   {
       return view("Index",new MyViewModel { TheData = result });
   }
}

3. Turn off ASP.NET Tracing and debugging
before deploying your web application turn of tracing feature by setting it to false in web.config file

<configuration>
    <system.web>
        <trace enabled="false" />
    </system.web>
</configuration>

While development phase you need to enable debugger to debug your code by setting it to true in web.config file. Neglecting change it again to false before deploying will affect your web application performance by facing many problems:

- Scripts that are downloaded using the WebResources.axd handler, by setting debug to false responses from that handler will be returned with caching headers, allowing browsers to cache the responses for future use.

- Request will not timeout when debug is set to true. By setting it to false will enable ASP.NET to define timeouts for requests according to the HttpRuntime.Execution Timeout configuration settings.

- JIT optimization will not be applied to the code when running with debug = true. JIT can efficiently improve the performance of your ASP.NET application without requiring you change your code.

- The compilation process does not use batch compilation when using debug = true. without batch compilation an assembly will be created for each page and control causing web application to load so many of assemblies during runtime. When debug set to false batch compilation is used, generating a single assembly for the user control and a several assemblies for pages.

in case you fear to forget setting debug to false when deploying your application, you can force all ASP.NET applications in a server to ignore the debug setting by adding  the following configurations in the server's machine.config file.

<configuration>
    <system.web>
        <deployment retail="true" />
    </system.web>
</configuration>

4. Disable View State
View state is used to allow ASP.NET to keep the state of the page between postbacks performed by user. View state data is stored in HTML output inside hidden field. If your page displays many controls that contains a huge data, the view state field will be big enough to affect the response time of your page. if your page just display data without need any postback so it will be better to disable the view state of the whole page by set EnableViewState to false.

<%@ Page EnableViewState="false".......%>

or disable view state of some controls in your page

<Asp:GridView ID="MyGrid" runat="server" DataSource="MyDataSource" EnableViewState="false" />

if you don't want to use view state in all pages of your web application it recommended to disable view state for whole web application by setting it to false in your web.config file

<system.web>
    <pages enableViewState="false" ....../>
</system.web>

5. Pre-Compiling ASP.NET Application
When compiling an ASP.NET application project, a single assembly is created to hold all application's code but web pages(.aspx) and user controls(.ascx) not compiled and be deployed as it is. In the first request ASP.NET dynamically compiles the web pages and user control and places the compiled files in the ASP.NET temporary files folder.
To reduce the time of first request the web application can be pre-compiled, including all code, pages, and user controls, by using the ASP.NET compilation tool (Aspnet_compiler.exe). Running this tool in production servers can reduce the delay users experience on first requests.

- Open a command prompt in your production server.

- Navigate to the %windir%\Microsoft.Net folder

- Navigate to either the Framework or Framework64 according to the configuration of web application's application pool.

- Navigate to framework version's folder.

- Enter the following command to start the compilation

Aspnet_compiler.exe  -v  /FullPathOfYourWebApplication



European Italy HostForLIFE.eu Proudly Launches ASP.NET 4.5.1 Hosting

clock January 30, 2014 06:07 by author Scott

HostForLIFE.eu proudly launches the support of ASP.NET 4.5.1 on all their newest Windows Server environment. HostForLIFE.eu ASP.NET 4.5.1 Hosting plan starts from just as low as €3.00/month only.

ASP.NET is Microsoft's dynamic website technology, enabling developers to create data-driven websites using the .NET platform and the latest version is 4.5.1 with lots of awesome features.

According to Microsoft officials, much of the functionality in the ASP.NET 4.5.1 release is focused on improving debugging and general diagnostics. The update also builds on top of .NET 4.5 and includes new features such as async-aware debugging, ADO.NET idle connection resiliency, ASP.NET app suspension, and allows developers to enable Edit and Continue for 64-bit.

HostForLIFE.eu is a popular online ASP.NET based hosting service provider catering to those people who face such issues. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market.

The new ASP.NET 4.5.1 also add support for asynchronous debugging for C#, VB, JavaScript and C++ developers. ASP.NET 4.5.1 also adds performance improvements for apps running on multicore machines. And more C++ standards support, including features like delegating constructors, raw string literals, explicit conversion operators and variadic templates.

Microsoft also is continuing to add features meant to entice more JavaScript and HTML development for those using Visual Studio to build Windows Store. Further information and the full range of features ASP.NET 4.5.1 Hosting can be viewed here http://www.hostforlife.eu/European-ASPNET-451-Hosting.



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in