Using Asynchronous Methods in ASP.NET 4.5

Using Asynchronous Methods in ASP.NET 4.5 Best and cheap ASP.NET 4.5 hosting. This tutorial will teach you the basics of building an asynchronous ASP.NET Web Forms application using Visual Studio Express 2012 for Web, which is a free version of Microsoft Visual Studio. You can also use Visual Studio 2012.

ASP.NET 4.5 Web Pages in combination .NET 4.5 enables you to register asynchronous methods that return an object of type Task. The .NET Framework 4 introduced an asynchronous programming concept referred to as a Task and ASP.NET 4.5 supports Task. Tasks are represented by the Task type and related types in the System.Threading.Tasks namespace. The .NET Framework 4.5 builds on this asynchronous support with the await and async keywords that make working with Task objects much less complex than previous asynchronous approaches. The awaitkeyword is syntactical shorthand for indicating that a piece of code should asynchronously wait on some other piece of code. The async keyword represents a hint that you can use to mark methods as task-based asynchronous methods. The combination of awaitasync, and the Taskobject makes it much easier for you to write asynchronous code in .NET 4.5. The new model for asynchronous methods is called the Task-based Asynchronous Pattern (TAP). This tutorial assumes you have some familiarity with asynchronous programing using await and asynckeywords and the Task namespace.

How Requests Are Processed by the Thread Pool

On the web server, the .NET Framework maintains a pool of threads that are used to service ASP.NET requests. When a request arrives, a thread from the pool is dispatched to process that request. If the request is processed synchronously, the thread that processes the request is busy while the request is being processed, and that thread cannot service another request.

This might not be a problem, because the thread pool can be made large enough to accommodate many busy threads. However, the number of threads in the thread pool is limited (the default maximum for .NET 4.5 is 5,000). In large applications with high concurrency of long-running requests, all available threads might be busy. This condition is known as thread starvation. When this condition is reached, the web server queues requests. If the request queue becomes full, the web server rejects requests with an HTTP 503 status (Server Too Busy). The CLR thread pool has limitations on new thread injections. If concurrency is bursty (that is, your web site can suddenly get a large number of requests) and all available request threads are busy because of backend calls with high latency, the limited thread injection rate can make your application respond very poorly. Additionally, each new thread added to the thread pool has overhead (such as 1 MB of stack memory). A web application using synchronous methods to service high latency calls where the thread pool grows to the .NET 4.5 default maximum of 5, 000 threads would consume approximately 5 GB more memory than an application able the service the same requests using asynchronous methods and only 50 threads. When you’re doing asynchronous work, you’re not always using a thread. For example, when you make an asynchronous web service request, ASP.NET will not be using any threads between the asyncmethod call and the await. Using the thread pool to service requests with high latency can lead to a large memory footprint and poor utilization of the server hardware.

Processing Asynchronous Requests

In web applications that see a large number of concurrent requests at start-up or has a bursty load (where concurrency increases suddenly), making web service calls asynchronous will increase the responsiveness of your application. An asynchronous request takes the same amount of time to process as a synchronous request. For example, if a request makes a web service call that requires two seconds to complete, the request takes two seconds whether it is performed synchronously or asynchronously. However, during an asynchronous call, a thread is not blocked from responding to other requests while it waits for the first request to complete. Therefore, asynchronous requests prevent request queuing and thread pool growth when there are many concurrent requests that invoke long-running operations.

Choosing Synchronous or Asynchronous Methods

This section lists guidelines for when to use synchronous or asynchronous Methods. These are just guidelines; examine each application individually to determine whether asynchronous methods help with performance.

In general, use synchronous methods for the following conditions:

  • The operations are simple or short-running.
  • Simplicity is more important than efficiency.
  • The operations are primarily CPU operations instead of operations that involve extensive disk or network overhead. Using asynchronous methods on CPU-bound operations provides no benefits and results in more overhead.

    In general, use asynchronous methods for the following conditions:

  • You’re calling services that can be consumed through asynchronous methods, and you’re using .NET 4.5 or higher.
  • The operations are network-bound or I/O-bound instead of CPU-bound.
  • Parallelism is more important than simplicity of code.
  • You want to provide a mechanism that lets users cancel a long-running request.
  • When the benefit of switching threads out weights the cost of the context switch. In general, you should make a method asynchronous if the synchronous method blocks the ASP.NET request thread while doing no work. By making the call asynchronous, the ASP.NET request thread is not blocked doing no work while it waits for the web service request to complete.
  • Testing shows that the blocking operations are a bottleneck in site performance and that IIS can service more requests by using asynchronous methods for these blocking calls.

    The downloadable sample shows how to use asynchronous methods effectively. The sample provided was designed to provide a simple demonstration of asynchronous programming in ASP.NET 4.5. The sample is not intended to be a reference architecture for asynchronous programming in ASP.NET. The sample program calls ASP.NET Web APImethods which in turn call Task.Delay to simulate long-running web service calls. Most production applications will not show such obvious benefits to using asynchronous Methods.

Few applications require all methods to be asynchronous. Often, converting a few synchronous methods to asynchronous methods provides the best efficiency increase for the amount of work required.

The Sample Application

You can download the sample application from the GitHub site. The repository consists of three projects:

  • WebAppAsync: The ASP.NET Web Forms project that consumes the Web API WebAPIpwgservice. Most of the code for this tutorial is from the this project.
  • WebAPIpgw: The ASP.NET MVC 4 Web API project that implements the Products, Gizmos and Widgets controllers. It provides the data for the WebAppAsyncproject and the Mvc4Async project.
  • Mvc4Async: The ASP.NET MVC 4 project that contains the code used in another tutorial. It makes Web API calls to the WebAPIpwg service.

The Gizmos Synchronous Page

The following code shows the Page_Load synchronous method that is used to display a list of gizmos. (For this article, a gizmo is a fictional mechanical device.)

The following code shows the GetGizmos method of the gizmo service.

The GizmoService GetGizmos method passes a URI to an ASP.NET Web API HTTP service which returns a list of gizmos data. The WebAPIpgw project contains the implementation of the Web API gizmos, widget and product controllers.
The following image shows the gizmos page from the sample project.


Creating an Asynchronous Gizmos Page

The sample uses the new async and await keywords (available in .NET 4.5 and Visual Studio 2012) to let the compiler be responsible for maintaining the complicated transformations necessary for asynchronous programming. The compiler lets you write code using the C#’s synchronous control flow constructs and the compiler automatically applies the transformations necessary to use callbacks in order to avoid blocking threads.

ASP.NET asynchronous pages must include the Page directive with the Async attribute set to “true”. The following code shows the Page directive with the Async attribute set to “true” for the GizmosAsync.aspx page.

 The following code shows the Gizmos synchronous Page_Load method and the GizmosAsyncasynchronous page. If your browser supports the HTML 5 <mark> element, you’ll see the changes in GizmosAsync in yellow highlight.

 The asynchronous version:

The following changes were applied to allow the GizmosAsync page be asynchronous.

  • The Page directive must have the Async attribute set to “true”.
  • The RegisterAsyncTask method is used to register an asynchronous task containing the code which runs asynchronously.
  • The new GetGizmosSvcAsync method is marked with the async keyword, which tells the compiler to generate callbacks for parts of the body and to automatically create a Taskthat is returned.
  • “Async” was appended to the asynchronous method name. Appending “Async” is not required but is the convention when writing asynchronous methods.
  • The return type of the new new GetGizmosSvcAsync method is Task. The return type of Task represents ongoing work and provides callers of the method with a handle through which to wait for the asynchronous operation’s completion.
  • The await keyword was applied to the web service call.
  • The asynchronous web service API was called (GetGizmosAsync).

Inside of the GetGizmosSvcAsync method body another asynchronous method, GetGizmosAsync is called. GetGizmosAsync immediately returns a Task<List<Gizmo>> that will eventually complete when the data is available. Because you don’t want to do anything else until you have the gizmo data, the code awaits the task (using the await keyword). You can use the await keyword only in methods annotated with the async keyword.

The await keyword does not block the thread until the task is complete. It signs up the rest of the method as a callback on the task, and immediately returns. When the awaited task eventually completes, it will invoke that callback and thus resume the execution of the method right where it left off. For more information on using the await and async keywords and the Task namespace, see the async references section.

The following code shows the GetGizmos and GetGizmosAsync methods.

The asynchronous changes are similar to those made to the GizmosAsync above.

  • The method signature was annotated with the async keyword, the return type was changed to Task<List<Gizmo>>, and Async was appended to the method name.
  • The asynchronous HttpClient class is used instead of the synchronous WebClient class.
  • The await keyword was applied to the HttpClientGetAsync asynchronous method.

The following image shows the asynchronous gizmo view.

The browsers presentation of the gizmos data is identical to the view created by the synchronous call. The only difference is the asynchronous version may be more performant under heavy loads.

RegisterAsyncTask Notes

Methods hooked up with RegisterAsyncTask will run immediately after PreRender. You can also use async void page events directly, as shown in the following code:

The downside to async void events is that developers no longer has full control over when events execute. For example, if both an .aspx and a .Master define Page_Load events and one or both of them are asynchronous, the order of execution can’t be guaranteed. The same indeterminiate order for non event handlers (such as async void Button_Click ) applies. For most developers this should be acceptable, but those who require full control over the order of execution should only use APIs like RegisterAsyncTask that consume methods which return a Task object.

Performing Multiple Operations in Parallel

Asynchronous Methods have a significant advantage over synchronous methods when an action must perform several independent operations. In the sample provided, the synchronous page PWG.aspx(for Products, Widgets and Gizmos) displays the results of three web service calls to get a list of products, widgets, and gizmos. The ASP.NET Web API project that provides these services uses Task.Delay to simulate latency or slow network calls. When the delay is set to 500 milliseconds, the asynchronous PWGasync.aspx page takes a little over 500 milliseconds to complete while the synchronous PWG version takes over 1,500 milliseconds. The synchronous PWG.aspx page is shown in the following code.

The asynchronous PWGasync code behind is shown below.

Using a Cancellation Token

Asynchronous Methods returning Taskare cancelable, that is they take a CancellationTokenparameter when one is provided with the AsyncTimeout attribute of the Page directive. The following code shows the GizmosCancelAsync.aspx page with a timeout of on second.

The following code shows the GizmosCancelAsync.aspx.cs file.

In the sample application provided, selecting the GizmosCancelAsync link calls the GizmosCancelAsync.aspx page and demonstrates the cancelation (by timing out) of the asynchronous call. Because the delay time is within a random range, you might need to refresh the page a couple times to get the time out error message.

Server Configuration for High Concurrency/High Latency Web Service Calls

To realize the benefits of an asynchronous web application, you might need to make some changes to the default server configuration. Keep the following in mind when configuring and stress testing your asynchronous web application.

  • Windows 7, Windows Vista, Window 8, and all Windows client operating systems have a maximum of 10 concurrent requests. You’ll need a Windows Server operating system to see the benefits of asynchronous methods under high load.
  • Register .NET 4.5 with IIS from an elevated command prompt using the following command:
    %windir%\Microsoft.NET\Framework64 \v4.0.30319\aspnet_regiis -i
    See ASP.NET IIS Registration Tool (Aspnet_regiis.exe)
  • You might need to increase the HTTP.sys queue limit from the default value of 1,000 to 5,000. If the setting is too low, you may see HTTP.sys reject requests with a HTTP 503 status. To change the HTTP.sys queue limit:

    • Open IIS manager and navigate to the Application Pools pane.
    • Right click on the target application pool and select Advanced Settings.
  • If your application is using web services or System.NET to communicate with a backend over HTTP you may need to increase the connectionManagement/maxconnection element. For ASP.NET applications, this is limited by the autoConfig feature to 12 times the number of CPUs. That means that on a quad-proc, you can have at most 12 * 4 = 48 concurrent connections to an IP end point. Because this is tied to autoConfig, the easiest way to increase maxconnection in an ASP.NET application is to set System.Net.ServicePointManager.DefaultConnectionLimit programmatically in the from Application_Start method in the global.asax file. See the sample download for an example.
  • In .NET 4.5, the default of 5000 for MaxConcurrentRequestsPerCPU should be fine.
How Using Microsoft Enterprise Library in ASP.NET

How Using Microsoft Enterprise Library in ASP.NET | Best and cheap ASP.NET hosting. In this tutorial we will show you how to using Microsoft Enterprise Library is a collection of reusable software components used for  logging, validation, data access, exception handling etc.

Here I am describing how to use Microsoft Enterprise Library for data access.

Step 1: First download the project from URL.
Step 2: Now extract the project to get

And give reference in the Bin directory by Right click on Bin -> Add Reference -> then give the path of these 4 dlls. Then

Step 3: Modification in the web.config for Connection String.

Give the connection string as above where Datasource is your data source name, Initial Catalog is your database name and User ID and Password as in your sql server.

Step 4:

Now it is time to write the code.
Write the below 2 lines in the using block.

Here I am writting some examples how to work on:

The above code is a sample that will return a dataset. Here Fewlines4bijuConnection is the connection name and Topics_Return is the stored procedure name that is nothing but a Select statement.
But if the stored procedure is taking parameter then the code will be like:

As the code explained above ASPHostPortal Connection is the connection name and Topics_Save is the stored procedure name that is taking 3 (Subject,Description,PostedBy) input parameters and 1(Status) output parameter.

You may give values from textbox, I am here provideing sample values like  “Here is the subject”, “Here is the Descriptiont” or you may give the UserID from session, I am here giving 4. The output parameter will give you a string as defined and the code to get the value is

you can pass input parameter as below

DbType.AnsiString since Subject is of string time, you can select different values like AnsiString, DateTime from the Enum as be the parameter type.

The above code describes if you are using any stored procedure.
Below is an example that shows how to use inline SQL statements.

Happy coding!

How To Validation Bootstrap in ASP.NET MVC

How To Validation Bootstrap in ASP.NET MVC | Best and cheap ASP.NET MVC hosting. In this tutorial I will show you about bootstrap in ASP.NET MVC. I use Bootstrap in almost every project I build these days. I build up a custom Bootstrap configuration to reduce bloat, and have my workflow down-pat for updating those configurations (which I’ll write about in the near future). I have familiarised myself with it’s ins-and-outs to help ensure I use it to it’s full potential without being overkill, and it has sped up my HTML build time immensely.

Bootstrap Validation in ASP.NET MVC

One issue I’ve come across before is finding harmony between ASP.Net MVC’s validation and Bootstrap’s validation classes.

Out of the box when you use Html.ValidationMessageFor() to output a validation (with none of Microsoft’s validation classes set up), this is what I end up with:


Behind the scenes, the Microsoft validation has put an input-validation-error class on the text boxes that failed validation, and the validation message has some classes that can be styled:

Bootstrap’s method of validation styling is based on the parent’s class (the “form group”), instead of the element itself, thus allowing all children (e.g. labels and text boxes) to have a specific style:

 It’s not difficult to apply the Bootstrap validation classes when model errors exist using a little JavaScript, but I decided to look for a nice NuGet package to do this for me, and I found one – jquery.validate.unobtrusive.bootstrap by Sandro Caseiro.  Simply install it via the NuGet Package Manager Console:

 I use the bundling in the Microsoft.AspNet.Web.Optimization package, so rather than including the JavaScript library file raw in my view, I already have a validate bundle that will include it since this library has followed the naming convention, being jquery.validate.unobtrusive.bootstrap.js, so I don’t even need to update the BundleConfig.cs file:

 This bundle was already being included in my page using the following:

 Unfortunately this didn’t work! The jquery.validate.unobtrusive.bootstrap.js was being included, but when I look at the source, it’s being included BEFORE the jquery.validate.unobtrusive.js file:

The problem is that out of the box, the bundling library orders the packages included in the bundle alphabetically when using a wildcard *.

I saw a nice solution to this on someone’s the jquery.validate.unobtrusive.bootstrap GitHub issues page, it involves creating a custom orderer for the bundle:

Step 1: Create a new orderer class (I placed it within the BundleConfig class to keep it local):

 Step 2: Update the bundle creation code to use this orderer:

 The result is that your scripts will be output in order of the “dots” – a kind of heirarchy assumed based on the file naming convention, which works in this particular situation, at least (and it would be great if it worked in general, signifying a naming convention for JavaScript files):

 And the result is a lovely looking form, utilising Bootstrap validation styling:


ASP.NET Hosting Tutorial – SEO Tips For ASP.NET

ASP.NET Hosting Tutorial – SEO Tips For ASP.NET | Best and cheap ASP.NET Hosting in Australia. In this post we will expains you about 7 tips for your ASP.NET site.


Here are 7 tips on SEO for your ASP.NET website:

A Microsoft server-side Web technology. ASP.NET takes an object-oriented programming approach to Web page execution. Every element in an ASP.NET page is treated as an object and run on the server. An ASP.NET page gets compiled into an intermediate language by a .NET Common Language Runtime-compliant compiler.

Page Tittles

Page titles between tags is one important thing that many fail to practice in SEO. When a search is made in Google, these titles show up as links in the result. So that explains its importance. The common mistake among website owners is giving the same title for all pages. Page titles drive traffic to your site, hence it is important to have a proper title to attract visitors. Adding titles is not as hard as you imagine. If you have a product catalog use your product name as title. You can also choose to give a different title that is related to your product.

Meaningful URL

URLs that are long with query parameters do not look neat and it is difficult for the visitor to remember. Instead use formatted URLs for your static pages. URL which has a meaning explains the content in your website. Although experts agree with using an URL that has query parameters, it is better to have a meaningful URL. Components like UrlRewritingNet can be used for this purpose. Mapping support in URL is offered by IIS7 which has plenty of features.

Structure of the Content

Content without a structure is not possible.  You will have titles, headings, sub headings, paragraphs and others. How would you emphasize some quotes or important points in your content? If you follow the below mentioned steps, the structure of your content will be semantically correct.

  • Divide long stories or parts using headings. Short paragraphs make more sense to the readers. Use tags to bring beauty to your content.
  • If you want to emphasize an important point or quote, place them between tags.

Visitors can create structured content if you use FCKEditor and the like. Integrating these to your website is not complex.

Clean the Source Code

Don’t panic, it is advisable to clean up the source code and minimize the number of codes. The following simple steps will assist you in cleaning the source code: You can use

  • External stylesheets and not inline CSS
    • js files instead of inline JavaScript
  • HTML comments is not encouraged
  • Avoid massive line breaking
  • Avoid using viewstate when not required

The relation between the content and the code (JavaScript, HTML, CSS) determines the ranking of your website. Smaller source codes help build a strong relation.

Crawlable Site

Do not use

  • Silver or flash light for menus or to highlight information
  • Menus based on JavaScript
  • Menus based on buttons
  • Intro-pages

Do use

  • Simple tags wherever possible
  • Sitemap
  • “Alt” for images
  • RSS

Test the Site

What happens to the requests that are sent when the site is slow? Sometimes requests are sent by robots and if they are unable to connect to your site continuously, they drop the site from their index. Enable your site to respond fast to requests even during peak hours. Moreover, visitors don’t like to visit slow sites. Use the various tools available and conduct the stress test for your site. Perform this and locate all the weak parts of the site. Fix them so that your site gets indexed.

Test the AJAX site

Spiders can only run a few parts of your AJAX website because they don’t run JavaScripts. Spiders can only analyze the data and hence they remain invisible to robots. The AJAX sites do not get indexed which does not help in search engine optimization. To make the site spider friendly, try and keep away from initial content loading into the JavaScript. You can also follow this only for pages that you like to index.  Make it easy for robots so that they can navigate. Try this simple trick to see how your AJAX site will appear to the robots. Disable JavaScript from the browser and visit your AJAX site. You can view the pages which robots will index.

Cheap ASP.NET Hosting in Autralia Click here