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

FREE ASP.NET 4.5 Spain Hosting – HostForLIFE.eu :: 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;  
    gvReport.DataBind();  
    ExportToExcel();//Method to use export to excel.  
    gvReport.AllowPaging = true;  
    gvReport.AllowSorting = false;  
    gvReport.DataBind();   

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.Clear();  
        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);  
        gvReport.RenderControl(htmlWrite);  
        Response.Write(stringWrite.ToString());  
        Response.End();  
    } 

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.



FREE ASP.NET 4.5 Hosting UK - HostForLIFE.eu :: How can HostForLIFE.eu Guarantee Our Windows ASP.NET 4.5 Hosting Service?

clock March 24, 2014 07:05 by author Scott

Only focusing on ASP.NET hosting service, HostForLIFE prove ourselves to be one of the best ASP.NET hosting providers that offer the most highlights, although there are thousands of ASP.NET hosting companies on the market. In below, we have listed our main features that has integrated with our 4 ASP.NET hosting plans.

Offering Many Excellent Features

- 1-Click Application Installer

In the HostForLIFE control panel, there is a 1-click web application installer for convenient installation of many popular open source web applications, including PHP apps like WordPress, Joomla, Drupal and phpBB, and ASP.NET applications like DotNetNuke, nopCommerce, BlogEngine and Orchard.

- PHP & MySQL

In the past, PHP didn't run well on a Windows server, but over the last several years, Microsoft has improved IIS and now PHP runs vey well on Windows hosting platforms, which means famous open source apps like Joomla, WordPress and Drupal can run well on HostForLIFE Windows hosting plans.

In addition, by supporting MySQL as part of their Windows hosting platform, a popular open source relational database system, HostForLIFE enables customers to use a lot of popular open source apps.

- ASP.NET 4.5.1 Hosting

We support ASP.NET 4.5.1 hosting on our Windows 2012 platform, which is compatible with Visual Studio 2013/2012, and our Windows 2008 hosting platform also fully supports ASP.NET 4.0 and is compatible with Visual Studio 2010, which enables customers' applications to be written in any language that is compatible with the common language runtime, including Visual Basic and C#.

- SQL Server

HostForLIFE always improve our technology and we always up to date with the Micorosoft technology. We offer the latest SQL 2012 version. We also support integrated full text search, stored procedures and ASP.NET SQL Session, which makes their customers get DBO right and manage SQL database remotely using SQL Management Studio or SQL Management Studio Express.

- Windows 2012 Hosting

We use Windows server 2012 – the latest Windows operating system comes with IIS8 to deliver customers with more options for their web applications including support for .NET, ASP and PHP. What's more, they support Full Trust to make customers' sites isolated from one another for greater reliability and security.

Utilizing Cutting-Edge Facilities & Infrastructures

HostForLIFE uses a state-of-the-art data enter which is featured with UPS backup power, diesel generators, firewall protection and 24×7 security. Moreover, we houses dual quad Dell servers that are 100% factory built and tested, coming with the best specification of 64 bit software, 32 GB of RAM, and RAID 10 disk arrays. All of the first-class facilities and infrastructures enable HostForLIFE to provide satisfying uptime and fast hosting speed for our customers to run websites smoothly and stably.

Providing Quality Technical Support

As one of the most reliable hosting companies, HostForLIFE offers quality technical support powered by a group of support staffs through email, all of who are professional, knowledgeable, experienced and on-site 24×7, so that we are able to give quick response and effective assistance to troubled customers to resolve problems.

In addition, in our online knowledgebase and blog, HostForLIFE technicians and engineers have worked out a lot of in-depth articles to teach customers how to deal with common issues independently.



European FREE ASP.NET MVC Hosting Netherlands - HostForLIFE.eu :: How to Custom Error Pages In ASP.NET MVC

clock March 20, 2014 07:00 by author Peter

If you're having problems setting up custom error pages in ASP.NET MVC you're not alone. It's surprisingly difficult to do this correctly, not helped by the fact that some errors are handled by ASP.NET and others by IIS.Ideally (and I expect such is the case with some other frameworks/servers) we would just configure our custom error pages in one place and it would just work, no matter how/where the error was raised. Something like:

<customErrors mode="On">

    <error code="404" path="404.html" />

    <error code="500" path="500.html" />

</customErrors>

Custom 404 error pages

When a resource does not exist (either static or dynamic) we should return a 404 HTTP status code. Ideally we should return something a little friendlier to our site visitors than the error pages built in to ASP.NET/IIS, perhaps offering some advice on why the resource may not exist or providing an option to search the site.

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="utf-8"/>

    <title>404 Page Not Found</title>

</head>

<body>

    <h1>404 Page Not Found</h1>

</body>

</html>

I created a new ASP.NET MVC 5 application using the standard template in Visual Studio. If I run the site and try to navigate to a resource that does not exist e.g. /foo/bar, I'll get the standard ASP.NET 404 page with the following information:

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /foo/bar

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.33440

In this case the error was raised by ASP.NET MVC because it could not find a matching controller and/or action that matched the specified URL. In order to set up a custom 404 error page add the following to web.config inside <system.web></system.web>:

<customErrors mode="On">

  <error statusCode="404" redirect="~/404.html"/>

</customErrors>

I've set mode="On" so we can view the custom errors pages locally. Generally you would only want to display these in production so would set mode="RemoteOnly".

Now if I navigate to /foo/bar once more I see my custom error page. However, the URL is not /foo/bar as I'd expect. Instead ASP.NET issued a redirect to /404.html?aspxerrorpath=/foo/bar. Also if I check the HTTP status code of the response, it's 200 (OK).

This is very wrong indeed. Not only is is misleading as we're returning a 200 response when a resource does not exist, but it's also bad for SEO. Quite simply, if a resource does not exist at the specified URL you should return a 404 or redirect to a new location if the resource has moved. To fix this we can change ASP.NET's default behaviour of redirecting to the custom error page to rewrite the response:

<customErrors mode="On" redirectMode="ResponseRewrite">

  <error statusCode="404" redirect="~/404.html"/>

</customErrors>

Unfortunately this doesn't help us much. Although the original URL is now preserved, ASP.NET still returns a 200 response and furthermore displays our custom error page as plain text. To fix the incorrect content type we have to return an ASP.NET page. So if you thought that you'd never have to deal with *.aspx pages again, I'm sorry to dissapoint you.

After renaming the error page to 404.aspx and updating web.config accordingly, the URL is preserved and we get the correct content type (text/html) in the response.

However, we still get a HTTP 200 response. We therefore need to add the following to the top of 404.aspx:

<% Response.StatusCode = 404 %>

We now get the correct status code, URL preserved and our custom error page. If we navigate to a static resource (e.g. foo.html) or a URL that doesn't match our routing configuration (e.g. /foo/bar/foo/bar) we get the standard IIS 404 error page. In the above scenarios ASP.NET is bypassed and IIS handles the request. Also if you happen to be returning HttpNotFound() from your controller actions you'll get the same result - this is because MVC simply sets the status code rather than throwing an exception, leaving IIS to do its thing. In these cases we need to set up custom error pages in IIS (note that this only works in IIS 7+). In web.config add the following inside <system.webServer></system.webServer>:

<httpErrors errorMode="Custom">

  <remove statusCode="404"/>

  <error statusCode="404" path="/404.html" responseMode="ExecuteURL"/>

</httpErrors>

Similar to ASP.NET custom errors I've set errorMode="Custom" so we can test the error page locally. Normally you'd want this set to errorMode="DetailedLocalOnly".

Also note that I'm using a html page again, not aspx. Ideally you should always use simple static files for your error pages. This way if there's something wrong with ASP.NET you should still be able to display your custom error pages. If we navigate to a static file that does not exist we now get our custom error page instead of the default IIS one. However if we look at the response headers we get a 200 status code, not 404; just like the problem we had with ASP.NET's custom errors (hey, at least the IIS and ASP.NET teams are consistent).

Fortunately IIS actually provides a built in solution to resolve this rather than having to rely on hacks. If you set responseMode="File" IIS will return your custom errors page without altering the original response headers:

<error statusCode="404" path="404.html" responseMode="File"/>

Custom 500 error pages

Most of the issues addressed above relate to other error pages so if you use the same techniques you should be able to set up a custom "500 Server Error" page. There are however a few caveats.

The standard ASP.NET MVC template sets up the built in HandleErrorAttribute as a global filter. This captures any error thrown in the ASP.NET MVC pipeline and returns a custom "Error" view providing you have custom errors enabled in web.config. It will look for this view at ~/views/{controllerName}/error.cshtml or ~/views/shared/error.cshtml.

If you're using this filter you'll need to either update the existing view with your custom error page HTML or create the view if it doesn't already exist (best to do so in the views/shared directory).

Personally, I don't really see the value in this filter. Any exceptions thrown outside of the MVC pipeline will fall back to the standard ASP.NET error pages configuration. Since you're going to have to set those up anyway there is no real need to have the filter.

To do so add the following to the ASP.NET custom error pages configuration:

   <customErrors mode="On" redirectMode="ResponseRewrite">

     <error statusCode="404" redirect="~/404.aspx"/>

     <error statusCode="500" redirect="~/500.aspx"/>

   </customErrors>

Like before I created an ASPX page that sets the response code:

<% Response.StatusCode = 500 %>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="utf-8" />

    <title>500 Server Error</title>

</head>

<body>

    <h1>500 Server Error</h1>

</body>

</html>

Unfortunately this won't capture every exception you're likely to encounter in your application. A fairly common error is produced by ASP.NET's request validation, for example requesting a URL with a dangerous path such as /foo/bar<script></script>. This will actually produce a 400 (Bad Request) response so you can either add a specific error page for this or set up a default like so:

<customErrors mode="Off" redirectMode="ResponseRewrite" defaultRedirect="~/500.aspx">

<error statusCode="404" redirect="~/404.aspx"/>

<error statusCode="500" redirect="~/500.aspx"/>

</customErrors>

Finally to capture any non ASP.NET exceptions we can set up an IIS custom error page for server errors:

   <error statusCode="500" path="500.html" responseMode="File"/>



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



About HostForLIFE.eu

HostForLIFE.eu 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