- ~ Posted by Deepak Kamboj on May 31, 2010
IIS combined with ASP.NET provides many technologies to improve performance and scalability. IIS provides a pool of threads so that it can server many requests simultaneously. The pool has a limited number of threads in it, and once they are used up additional requests can start to pile up. Keeping the total number of active threads down is an attempt to prevent too many active threads from consuming all of the available CPU time. However, with today's data intensive websites, much of the time threads are tied up waiting for an external resource such as a request from a web service or from a database. Asynchronous pages in ASP.NET can boost performance in these situations by enabling threads in the pool to be used to serve additional requests while an operation is waiting for an external resource request to complete.
Suppose you have a website with two web pages. One is your home page which display's a greeting, and the second page displays a large dataset from a database. You have 25 threads in your thread pool. 25 people simultaneously are accessing the database query page, and one additional person comes onto the site to see the home page which has static content on it.
Compare these two scenarios:
Synchronous database driven page: While everyone is waiting for the dataset to load, all available threads are in use so the 26th request for the home page becomes blocked.
Asynchronous database driven page: While 25 requests are waiting for data from the database, those threads are returned to the pool for work. When the 26th request comes in for the home page, that page is returned immediately. As the datasets are returned the threads are drawn out of the thread pool to finish serving the pages. The result is that the threads spend much more time available to serve requests.
Here are two good pages for getting started with asynchronous ASP.NET pages:
Asynchronous ASP.NET Page Processing by Peter Bromberg
http://www.eggheadcafe.com/articles/20060918.asp
Use Threads and Build Asynchronous Handlers in Your Server-Side Web Code by Fritz Onion
http://msdn.microsoft.com/msdnmag/issues/03/06/threading/default.aspx
After reading these and some other articles, here is a piece of code to get you started. I put this together to process a job in the background as a generic pattern. I wrap my big job in a delegate so that I can get an IAsyncResult object back. This simplifies things, because in most examples I read you get this by calling a web service asynchronously but this isn't always what you want done.
Step 1: Make an empty asp.net page. Add async="true" to the @Page tag in the .aspx file.
Step 2: In the class code, declare a delegate
public delegate void AsyncTaskDelegate();
Step 3: Declare a member variable in the class to prevent the delegate from going out of scope
AsyncTaskDelegate _runnerDelegate = null;
Step 4: Create a method that will be run asynchronously:
public void DoJob()
{
this.GridView1.DataSource = GetDatasetFromDatabase(); this.GridView1.DataBind();
}
Step 5: Tell the framework you want your job run. You can put this in Page_Load or in a response to a button click / postback:
// Register async methods
AddOnPreRenderCompleteAsync(
new BeginEventHandler(OnBegin),
new EndEventHandler(OnEnd)
);
Step 6: Add the event to kick off the delegate and run the job asynchronously.
IAsyncResult OnBegin(object sender, EventArgs e, AsyncCallback cb, object state)
{
_runnerDelegate = new AsyncTaskDelegate(this.DoJob);
IAsyncResult result = _runnerDelegate.BeginInvoke(cb, state);
return result;
}
Step 7: Add an event handler for after the request finishes
void OnEnd(IAsyncResult ar)
{
_runnerDelegate.EndInvoke(ar);
}
All together, it looks like this:
1: public partial class Async : System.Web.UI.Page
2: {
3: public delegate void AsyncTaskDelegate();
4:
5: AsyncTaskDelegate _runnerDelegate = null;
6:
7: IAsyncResult OnBegin(object sender, EventArgs e, AsyncCallback cb, object state)
8: {
9: _runnerDelegate = new AsyncTaskDelegate(this.DoJob);
10: IAsyncResult result = _runnerDelegate.BeginInvoke(cb, state);
11: return result;
12: }
13:
14: public void DoJob()
15: {
16: this.GridView1.DataSource = new AsyncTaskDelegate(this.DoJob);
17: this.GridView1.DataBind();
18: }
19:
20: void OnEnd(IAsyncResult ar)
21: {
22: _runnerDelegate.EndInvoke(ar);
23: }
24:
25: protected void Button1_Click(object sender, EventArgs e)
26: {
27: // Register async methods
28: AddOnPreRenderCompleteAsync(
29: new BeginEventHandler(OnBegin),
30: new EndEventHandler(OnEnd)
31: );
32: }
33:
34: }
Original Source: http://davidjberman.com/blogs/csharp/archive/2007/08/13/how-to-create-asynchronous-asp-net-pages-using-c.aspx
- Tags: c#
- Categories: C# | ASP.NET | .NET Framework
- ~ Posted by Deepak Kamboj on November 23, 2009
ASP.NET 4.0 platform is built up with various components Web Forms,ASP.NET MVC, Dynamic Data Controls and ASP.NET AJAX. It has the same foundation as in ASP.NET 3.5 SP1 but refined the above features. This post speaks about features in the Web Form model.
ASP.NET 4.0 features are nothing new, all are in 3.5 but this version gives more control over frequently used features.
Example: ASP.NET 4.0 Web Forms give developers more control over viewstate management, generation of Control ID’s, and HTML generated by some template based controls.
Control Over the Viewstate
Every developer knows that ASP.NET Viewstate burdens the page and waste of bandwidth. Same developers welcomed the ASP.NET MVC because of its complete absence of viewstate. If you ignore the viewstate on your page then you need to reload the data from server to controls.
The Viewstate is functional to Web Forms model, as it caches the contents from cache for control in the page.The overlooked feature is we can turnoff the viewstate for the page or control.The viewstate support is turned on for each page by default. The property EnableViewstate is defined is System.Web.UI.Control class and can be used to turn it on or off.
You can turn off the viewstate for ASP.NET page either declaratively or programmatically during the page’s life cycle.
void Page_Load(object sender,EventArgs e)
{
//Disable viewstate for the page and all of its child controls
this.EnableViewState = false;
....
}
Viewstate setting in ASP.NET has hierarchical nature, which means if the viewstate is enabled on the parent control, it can not be disabled on any of its child controls. You can disable the viewstate at page level and enable it in control level wherever it required.
ASP.NET 4.0 feature is you can enable viewstate at control level. In ASP.NET 4.0, the System.Web.UI.Control class exposes a new property named ViewStateMode:
public virtual ViewStateMode {get; set; }
ViewStateMode enumeration has the following values
| Value |
Description |
| Inherit |
Inherits the value of ViewStateMode property from the parent control |
| Enabled |
Enables viewstate for this control even if the parent control has set the viewstate property disabled. |
| Disabled |
Disables viewstate for this control even if the parent control has set the viewstate property enabled. |
Auto-Generated IDs
It is possible that rendered HTML can contain the same ID. When search for an element using getElementById, you will simply get an array of elements.Most data-bound controls generate their output by repeating the HTML for every data-bound item.
The sample generated Id string look like the following
ctl00$ContentPlaceHolder2$Gridview11$TextBox1
First issue might be with the length of the string, which repeated for several elements, makes the downloaded larger. Predicting the ID of a given control from script is difficult.
A frequently used technique for the above issue is
var btn = document.getElementById("<%=Button1.ClientID %> ");
ASP.NET 4.0 supports another option for autogenerated ids problem and developer can has greater control over generating the clientid of a control.
The System.Web.UI.Control Class now has a brand new property named ClientIDMode.
The ClientIDMode property values can be
| Value |
Description |
| Legacy |
Indicates that ID should be generated as in earlier versions of ASP.NET |
| Static |
ASP.NET doesn’t make any attempt to scope the client ID. The ID is assigned as-is. |
| Predictable |
The ID is obtained by simply concatenating the ID of parent controls and ignoring master page’s parent elements. |
| Inherit |
The control will use the same algorithm as its parent. |
Consider the following code:
<asp:GridView ID="GridView1" runat="server"
ClientIDMode = "Predictable"
RowClientIdsuffix="CustomerID">
......
</asp:GridView>
In this case, each row of the grid is identified by one or more columns in the data source with a trailing index. example
Panel1_GridView1_ALFKI_1
Finally, note that the ClientIDMode property affects only the ID attribute of the resulting HTML. The more about clientids in ASP.NET 4.0 can read here
HTML Enhancements
In the early version of ASP.NET developer didn’t have much control over programmatically accessing the HTML tags of a Web Page.
In ASP.NET 4.0, the Page class exposes two new string properties to set some common tags in the <head> section of a page. The two properties are Keywords and Description. The Keywords and Description properties can also be set directly as attributes of the @Page directive as shown below
<%@ Page Language="c#"
AutoEventWireup="true"
CodeFile="Default.aspx.cs"
Inherits="_Default"
Keywords="ASP.NET, AJAX "
Description="ASP.NET 4.0 WebForms" %>
permanently redirecting the page feature can be found here
More Control over Output Caching here
Conclusion
ASP.NET 4.0 Web Forms contains a number of features that together can make it a bigger development platform. It is moreover a refinement of existing features.
Source: MSDN Magazine
Backtrack: http://www.techbubbles.com/aspnet/web-forms-model-in-asp-net-4-0/
- Tags: asp.net 4.0
- Categories: ASP.NET | C#
- ~ Posted by Deepak Kamboj on October 6, 2009
Here is an example on how to send HTML email from your ASP.NET page using your Google account.
(This setup can be easily used to send messages via any other SMTP server that requires authentication).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
public class Gmail
{
/// <summary>
/// Sends the mail.
/// </summary>
public string SendMail(string toEmail, string subject, string body)
{
string returnMsg = string.Empty;
SmtpClient client = new SmtpClient();
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Host = "smtp.gmail.com";
client.Port = 587;
// setup Smtp authentication
NetworkCredential credentials =
new NetworkCredential("your_account@gmail.com",
"yourpassword");
client.UseDefaultCredentials = false;
client.Credentials = credentials;
MailMessage msg = new MailMessage();
msg.From = new MailAddress("your_account@gmail.com");
msg.To.Add(new MailAddress(toEmail));
msg.Subject = subject;
msg.IsBodyHtml = true;
msg.Body = string.Format(body);
try {
client.Send(msg);
returnMsg = "Message has been successfully sent.";
}
catch (Exception ex)
{
returnMsg = "Error occured while sending message."
+ ex.Message;
}
return returnMsg;
}
}
Backtrack: http://www.aspdotnetfaq.com/Faq/How-to-send-HTML-Email-from-ASP-NET-using-your-Gmail-account.aspx
- Tags: asp.net, email
- Categories: ASP.NET
- ~ Posted by Deepak Kamboj on September 22, 2009
Introduction
This Article series helps the .NET developers and architects to design the effective applications on .NET latest technologies. There are so many articles,books on application architecture but it is still challenging for developers to understand best practices, principles for the application design.
This post speaks about the fundamentals concepts of Application Architecture and principles.
What is Application Architecture?
Defining a solution which meets all technical and operational requirements by optimizing performance,security and manageability.
Why Architecture?
Software must built on a solid considerations and failing to meet the key scenarios and understand the design problems will lead to long term consequences. The application needs to address the following concerns .
- How the end user be using your application?
- What about quality attributes security,performance,concurrency, internationalization and configuration.
- What architecture suits for your application now or after it has been deployed?
Goals of Architecture
Application Architecture builds the bridge between business requirements and technical requirements. Good architecture reduces the business risks associated with the solution.
Architecture should consider
- Structure of the system not the implementation details
- User case scenarios
- Concerns of stake holders
- functional and quality requirements
Approach to Architecture
You must determine the type of application that you are building and architecture styles that will be used and cross cutting technologies.
- Identify the type of application
- How the application will be deployed?
- Drill down for architecture styles and technologies
- Considering Quality attributes and cross=cutting concerns.
Application Type
Key part in architecture and design is identifying the type of application.
The application types can be
- Rich Client application designed to run on client PC.
- Rich Internet applications.
- SOA applications designed to support communication between loosely coupled components.
- Smart client applications.
Deployment Strategy
When you design your application you must plan the infrastructure to deploy your application. Your application must accommodate any restrictions that exist in the environment. Identify infrastructure architecture early in the design process.
Architectural Style
Architectural style is set of policies and rules that we used in the component design later that we use in the application.
Examples of architecture styles
- Client-server
- Layered architecture
- MVC
- SOA
Cross cutting concerns
These concerns are key areas in your design that are not related to any layer in your application. You must consider the following concerns when you are designing your application.
Authentication Determine how to authenticate users and pass the identities across the layers.
Authorization Ensure proper authorization across the trusted boundary.
Caching Identify what should be cached and where to cache to improve your application’s performance and responsiveness.
Communication Choose appropriate protocols to protect sensitive data passing over the network.
Exception Management Catch exceptions at the boundaries and show meaning full messages to the end users.
Instrumentation and Logging Instrument all business and system-critical events and log sufficient details. Do not log sensitive information.
Software Architecture can be described as structure of system, where system represents the collection of components that accomplish a set of functions. This post explains the key design principles for software architecture.

The above picture shows you the common application architecture and different components in the system and how they work together.
Design Principles
- Separation of Concerns Break your application into distinct features.
- Prefer composition over inheritance When reusing the functionality use composition over inheritance because inheritance increases the dependency between parent and child classes.
- Don’t Repeat Yourself(DRY) Define only one component for providing specific functionality and should not be duplicated in any other component.
Design Considerations
When designing a application, software architect is to minimize the complexity by separating the design into different areas. For example UI processing components should not include code that directly access a data source, instead it should use data access components to retrieve data.
Authentication
Failure to design a good authentication strategy can leave your application vulnerable to spoofing attacks and session hijacking.
Consider the following guidelines when designing the authentication strategy
- Identify your trust boundaries
- If you have multiple systems with in the application consider using the single sign-on strategy.
- Store the hash of the passwords in the database.
- Enforce the use of strong passwords.
Authorization
Consider the following guidelines when you are designing the authentication strategy
- Protect resources by applying authorization to callers based on their identity.
- Use resource-based authorization for system auditing.
Caching
Caching improves the performance and responsiveness of your application.
- You should use the cache for avoiding network round trips and avoid duplicate processing of data.
- Do not cache the volatile data.
- Do not cache the sensitive data unless you encrypt it.
Communication
It concerns the interaction between components across the layers. When crossing the physical boundaries, you should use message-based communication.
- Build the service interfaces for communication
- Consider using MSMQ to queue messages for later delivery.
Concurrency and Transactions
When designing for concurrency and transactions for accessing the database it is important to identify the concurrency data model that you want to use. The model can be optimistic or pessimistic.
- If you have business-critical operations, consider wrapping them in transactions.
- Use connection-based transactions when accessing a single-data source.
- Updates to shared data should be mutually exclusive, which is accomplished by applying locks.
- Avoid holding locks for longer period.
Configuration Management
- Encrypt sensitive information in configuration store.
- Provide separate administrative interface for editing configuration information.
- Categorize the configuration items into logical sections.
Data Access
Designing a Data Access Layer is important for application maintainability. The Data Access Layer should be responsible for managing connections and executing commands against data source.
- Avoid accessing database directly from other layers and should have the data access layer interaction for DB operations.
- Release the DB connections as early as possible.
Exception Management
Good Design of exception-management strategy is important for the reliability of your application.
- Do not catch the internal exceptions unless you can handle them.
- Design a appropriate exception propagation strategy.
- Design a strategy for unhandled exceptions.
- Design a appropriate logging and notification strategy.
Layering
Designing the layers allows you to separate the functionality into different areas of concern.
- Layers should represent the logical grouping of components.
- Components with in a layer should be cohesive means business layer components should provide options only related to application business logic.
Backtrack:
http://www.techbubbles.com/softwarearchitecture/application-architecture-for-net-applications-part2/
- ~ Posted by Deepak Kamboj on September 8, 2009
In this post I will explain the Difference between ASP.NET web service and programming WCF services like ASP.NET web services. It also discusses how we use the both technologies for developing the web services.
The development of web service with ASP.NET relies on defining data and relies on the XmlSerializer to transform data to or from a service.
Key issues with XmlSerializer to serialize .NET types to XML
- Only Public fields or Properties of .NET types can be translated into XML.
- Only the classes which implement IEnumerable interface.
- Classes that implement the IDictionary interface, such as Hash table can not be serialized.
The WCF uses the DataContractAttribute and DataMemeberAttribute to translate .NET FW types in to XML.
[DataContract]
public class Item
{
[DataMember]
public string ItemID;
[DataMember]
public decimal ItemQuantity;
[DataMember]
public decimal ItemPrice;
}
The DataContractAttribute can be applied to the class or a strcture. DataMemberAttribute can be applied to field or a property and theses fields or properties can be either public or private.
Important difference between DataContractSerializer and XMLSerializer.
- A practical benefit of the design of the DataContractSerializer is better performance over XMLserialization.
- XMLSerialization does not indicate the which fields or properties of the type are serialized into XML where as DataCotratSerializer Explicitly shows the which fields or properties are serialized into XML.
- The DataContractSerializer can translate the HashTable into XML.
Developing Service
To develop a service using ASP.NET we must add the WebService attribute to the class and WebMethodAttribute to any of the class methods.
Example
[WebService]
public class Service : System.Web.Services.WebService
{
[WebMethod]
public string Test(string strMsg)
{
return strMsg;
}
}
To develop a service in WCF we will write the following code
[ServiceContract]
public interface ITest
{
[OperationContract]
string ShowMessage(string strMsg);
}
public class Service : ITest
{
public string ShowMessage(string strMsg)
{
return strMsg;
}
}
The ServiceContractAttribute specifies that a interface defines a WCF service contract, OperationContract Attribute indicates which of the methods of the interface defines the operations of the service contract.
A class that implements the service contract is referred to as a service type in WCF.
Hosting the Service
ASP.NET web services are compiled into a class library assembly and a service file with an extension .asmx will have the code for the service. The service file is copied into the root of the ASP.NET application and Assembly will be copied to the bin directory. The application is accessible using url of the service file.
WCF Service can be hosted within IIS or WindowsActivationService.
- Compile the service type into a class library
- Copy the service file with an extension .SVC into a virtual directory and assembly into bin sub directory of the virtual directory.
- Copy the web.config file into the virtual directory.
Client Development
Clients for the ASP.NET Web services are generated using the command-line tool WSDL.EXE.
WCF uses the ServiceMetadata tool(svcutil.exe) to generate the client for the service.
Message Representation
The Header of the SOAP Message can be customized in ASP.NET Web service.
WCF provides attributes MessageContractAttribute , MessageHeaderAttribute and MessageBodyMemberAttribute to describe the structure of the SOAP Message.
Service Description
Issuing a HTTP GET Request with query WSDL causes ASP.NET to generate WSDL to describe the service. It returns the WSDL as response to the request.
The generated WSDL can be customized by deriving the class of ServiceDescriptionFormatExtension.
Issuing a Request with the query WSDL for the .svc file generates the WSDL. The WSDL that generated by WCF can customized by using ServiceMetadataBehavior class.
Exception Handling
In ASP.NET Web services, Unhandled exceptions are returned to the client as SOAP faults.
In WCF Services, unhandled exceptions are not returned to clients as SOAP faults. A configuration setting is provided to have the unhandled exceptions returned to clients for the purpose of debugging.
Backtrack: http://www.techbubbles.com/wcf/wcf-vs-aspnet-web-services/
- ~ Posted by Deepak Kamboj on September 7, 2009
In this article I will discuss how to sort columns in grid and more. At the end it will help answer some very frequently asked questions like following.
- How to sort DataGrid in ASP.Net?
- How to sort GridView?
- How to show sort direction image in column header of GridView or DataGrid?
- How to keep track of sorting direction and sort expression while sorting GridView?
Along with getting answers to these question I will also discuss some of the issues with implementation of sorting in GridView. And one of the very frequently brought up issue is that SortDirection property of GridViewSortEventArgs is always set to Ascending.
Specifying Sorting Attributes For GridView
To enable sorting for GridView set Sorting attribute for the control to True and if you are specifying event handlers for controls on page itself then set the event handler function for OnSort event of the control. The following code snippet from ASPX page shows how these attributes are set.