Azure will definitely be a major topic of interest in 2010 for ASP.NET users. Here is a list of useful resources:
Category Archives: Tutorials
ASP.NET MVC Routing – StopRoutingHandler and IgnoreRoute
There are two methods to exclude a URL from being handled by Routing – StopRoutingHandler and IgnoreRoute.
StopRoutingHandler
The below listing shows two routes created manually, the first of which has a StopRoutingHandler which blocks Routing for handling the matching URL:
public static void RegisterRoutes(RouteCollection routes)
{
routes.Add(new Route
(
"{appresource}.axd/{*urlInfo}", new StopRoutingHandler() ));
routes.Add(new Route
(
"articles/{cat}/{id}", new SomeRouteHandler() ));
}
Therefore a URL such as resource1.axd will be matched to the first route and since that route returns a StopRoutingHandler Routing system will pass this request on for normal ASP.NET processing.
IgnoreRoute
A simpler way to circumvent Routing is to use IgnoreRoute .
This is declared in a similar manner to the familiar MapRoute method and is normally used alongside it as shown below:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(“{appresource}.axd/{*urlInfo}“);
routes.MapRoute("norm", “articles/{cat}/{id}“, new MvcRouteHandler());
}
This is a lot tidier than the method using StopRoutingHandler and functions exactly the same.
ASP.NET MVC Routing – WildCard Parameters
A wildcard or catch-all parameter in MVC Routing allows for a route to match a URL with an arbitrary number of parameters. This feature is especially useful when building CMSs, blogs, wikis and other content driven applications.
Typically, URLs for such content driven apps should be as descriptive as possible, for example reviews/hotels/germany/berlin/fourseasons. But what if the CMS also handles airline reviews, and want to use URLs like reviews/airlines/northwest . In this circumstance reviews would be the controller and airlines or hotels the action, but the id is either germany/berlin/fourseasons or northwest. Normally the parameters are inferred from the “/” character, but with wildcard parameters a chunk of a URL with multiple / characters can be read as a single parameter. In this case the below route definition could be used:
routes.MapRoute("reviews", "{controller}/{action}/{*id}");
The WildCard * character allows everything beyond the action parameter to be placed in the id parameter.
ASP.NET 4.0 URL Routing Tutorial
It is a common mis-perception that URL Routing is exclusive to MVC, with .NET 3.5 SP1 and above URL Routing can be also used with ASP.NET Web Forms. In ASP.NET 4.0 URL Routing is fully integrated and so straightforward and powerful to use it should be preferred over URL Rewriting whenever possible.
Routing allows for SEO friendly URLs such as aspnet101.com/category/routing/ to be used instead of a URL such as aspnet101.com/category.aspx?categoryid=8 .
First you will need to register the Routes in a subroutine and then add them in the Application_Start() event:
void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"articles-category", //Name of the Route (can be anyuthting)
"articles/{category}", // URL with parameters
"~/category.aspx"); //Page which will handles and process the request
}
void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
In the above code, the Route named articles-category will handle incoming requests for URLs which match the articles/{category} route definition. This route definition uses “articles/” as a literal string in the URL and then takes the subsequent URL text for the category parameter.
For example, the URL articles/routing will direct to the page category.aspx and pass “routing” as the value for the category parameter. There is a lot of flexibility in mapping parameters to the URL, please refer to Default Values, Constraints, Multiple Parameters for more details.
The parameters from the URL are passed to the aspx page in key-value dictionary pairs which can be accessed from Page.RouteData.Values. So in the above example the category value can be read into a variable using the below code:
string category = Page.RouteData.Values["category"] as string;
This code would typically be placed in the Page_Load() event of the page.
In addition to accessing the parameters programatically, they can also be read by the SQLDataSource control using the <asp:routeparameter> control:
<asp:sqldatasource id="ds1" runat="server" connectionstring="<%$ ConnectionStrings:Main %>" selectcommand="select title, text from Articles where category=@cat"> <selectparameters> <asp:routeparameter name="category" RouteKey="cat" /> </selectparameters> </asp:sqldatasource>
Generate URLs Using ASP.NET Routing
A major difference between Routing and URL rewriting is that Routing also allows for the generation of outgoing URLs served on the site. In the above example if we wanted to show users a URL for the ado category of articles, then we could generate a URL by using the below code:
string url = Page.GetRouteUrl("articles-category",
new { category = "ado" });
This code uses the articles-category Route to generate a url string, this could be used on the page or passed to the Response.Redirect method to redirect to another page. Whilst the last use is valid, if the user needs to be redirected to another page using Routing it is more efficient to use the Response.RedirectToRoute method:
Response.RedirectToRoute("articles-category",
new { category = "ado" });
ASP.NET MVC Routing – Constraints
MVC Routing Constraints allow for the application of a regular expression to a URL segment to determine if the route will match the request.
Previously in the introductory MVC Routing Tutorial we looked at defining Routes based on the number of segments in a URL. So the Route definition:
routes.MapRoute(“simple”, “{controller}/{action}/{id}“);
would match the URL /articles/category/12 . But suppose the content management system we are building also had a blog and we wanted to use URLs such as /2010/04/03. Such a URL would map to the simple Route we defined above and so in our example it would be processed as if it were referring to an article category.
Therefore we can see that just mapping URL segments to Route definitions is extremely limiting. Constraints allow for regex to be used to read the contents of the URL parameters to determine which Route definition to use. For example:
routes.MapRoute(“blogpost”, “{year}/{month}/{day}“
, new {controller=”blogpost”, action=”index”}
, new {year=@“\d{4}“, month=@“\d{2}“, day=@“\d{2}“});
routes.MapRoute(“simple”, “{controller}/{action}/{id}“);
Here there are two route definitions both of which have three parameters. Note the highlighted part of the blogpost route definition which is the definition of the constraint. The constraint in this case matches a URL of 4 digit number/2 digit number/2 digit number format. If this test is met the blogpost route definition will be applied, for all other 3 segment URLs the simple route definition will be applied.
Note the order of the definitions. ASP.NET MVC Routing attempts to match route definitions in sequence and once a match is made it is processed. Therefore, routes which contain constraints should always be placed before the simple non-constrained route definitions.
ASP.NET MVC Routing – Multiple Parameters
In MVC Routing, multiple parameters can be used in a URL segment. For example the route definition:
routes.MapRoute(“multiple”, “{controller}/{action}/{author}-{tag}");
contains multiple parameters (ie author and id) in the final segment. This will match the URL blog/technology/johnspencer-aspnet . Any literal string can separate the multiple parameters, so the route definitions {author}.{tag} , {author}on{tag}, author-{author}on{tag} are all be valid. The parameters must be separated by a literal string, so the definition {author}{tag} would not be valid.
When working with multiple parameters it is important to understand the concept of greedy matching. Under this concept the first parameter will take the maximum amount of the url fragment that is possible. For example, how would the URL fragment /john.francis.spencer.sqlserver/ be mapped the the route definition {author}.{tag} since the are three “.” characters and only one as a literal in the route definition? Under greedy matching, the first parameter (author) will take john.francis.spencer but leave sqlserver for the tag parameter since the tag parameter must take at least some text beyond a “.” character.
ASP.NET MVC Routing – Default Values
Default values in ASP.NET MVC Routing allow for much more flexible URL pattern matching. In our previous MVC Routing Tutorial we introduced Routing and how it matches a URL to a predefined Route and then extracts the parameters for processing. In our original simple examples, a URL segment had to be provided for each parameter in a URL Route.
So, to recap, if we defined a URL Route for handling incoming URLs for a content management system which needs to display the articles for a given category then the route may look as below:
routes.MapRoute(“simple”, “{controller}/{action}/{id}“);
and the URL of /articles/category/15 would result in the below controller (with 15 being passed in as the id parameter).
public class ArticlesController : Controller
{
public ActionResult Category(int id)
{
//Perform Operations....
}
}
This url would therefore output the articles for Category ID 15. But what if we wanted to use the URL /articles/category/ to display all the articles irrespective of category. For this we would need to use default values in Routing.
The provision of a default value in the Route definition allows ASP.NET MVC Routing to provide a preset value when none is provided in the URL (in a similar fashion to default values for parameters in function definitions).
The default value needs to be in the Route definition:
routes.MapRoute(“simple”, “{controller}/{action}/{id}“, new {id = 0});
Now, the URL /articles/category/ will be interpretted as /articles/category/0 and so in this example the 0 value for id can be used to display all articles regardless of category.
Multiple Default Values
Multiple default values can be used for different parameters as shown below:
routes.MapRoute(“simple” , “{controller}/{action}/{id}“,
new {id = 0, action=”home”});
In this example the URL /articles/category/ would behave as shown previously but the URL /articles/ would behave as /articles/home/ ( and so in the example of a content management system the URL /articles/category/ would be the articles home page).
One rule to bear in mind when using default values is the if a default is defined for a parameter then all subsequent parameters must have a default value as well. For example :
routes.MapRoute(“simple” , “{controller}/{action}/{id}“,
new { action=”home”});
is not valid and a default for the id parameter needs to be assigned.
Another caveat in using default values is that defaults cannot be used when literal values are used in parameters. For example the Route,
routes.MapRoute(“simple” , “{controller}/{action}-{id}”);
uses the literal string “ - ” to separate {controller} and {action} which would match URLs such as /articles/category-12/ . In this case a default cannot be used for action or id .
New Features in ASP.NET 4.0
By Joydip Kanjilal and Bhupali Khule
ASP.NET 4.0 is neither a revolutionary change nor a refactoring of the existing ASP.NET. Instead, it consists of a number of small-scale changes that allow developers to have a strong control of certain frequently used events. What makes ASP.NET 4.0 more effective than the already existing versions of ASP.NET are its rich features and powerful enhancements.
ViewState Control Enhancements
One of the major drawbacks of ASP.NET Webforms is ViewState, which can add significantly to the page size and slow performance. While initially you could set the EnableViewState property to true or false, all the controls, by default inherit and so if you set it at the control level, the behavior was inconsistent. However, with ASP.NET 4.0, the new ViewStateMode property helps to determines every control whether the ViewState should be enabled, disabled, or inherited.
Data Control Enhancements
Another interesting new enhancement in ASP.NET 4.0 is that the LayoutTemplate of the ListView data control is now optional – so you can just use the ItemTemplate of the control to display data. Here’s an example:
<asp:ListView ID="ListView1" runat="server"DataSourceID="SqlDataSource1"
ClientIDMode="Predictable">
<ItemTemplate>
Student Code:
<asp:LabelID="lblStudentCode" runat="server" Text='<%# Eval("StudentCode")%>' />
<br />
Student Name:
<asp:LabelID="lblStudentName" runat="server" Text='<%# Eval("StudentName")%>' />
<br />
</ItemTemplate>
</asp:ListView>
<asp:ListView ID="ListView1" runat="server"DataSourceID="SqlDataSource1"ClientIDMode="Predictable"><ItemTemplate>Student Code:<asp:LabelID="lblStudentCode" runat="server" Text='<%# Eval("StudentCode")%>' /><br />Student Name:<asp:LabelID="lblStudentName" runat="server" Text='<%# Eval("StudentName")%>' /><br /></ItemTemplate></asp:ListView>
In ASP.NET 3.5, you can achieve the same but you need to specify the layout template using the <layouttemplate> tag as shown below:
<asp:ListView runat="server" DataSourceID="SqlDataSource1" DataKeyNames="StudentCode" ItemContainerID="SqlDataSource1">
<layouttemplate>
<table runat="server" border="1">
<tr>
<th>StudentCode</th>
<th>StudentName</th>
</tr>
</table>
</layouttemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label runat="server"
Text='<%# Eval("StudentCode") %>'/>
</td>
<td>
<asp:Label runat="server"
Text='<%# Eval("StudentName") %>'/>
</td>
<td>
</tr>
</ItemTemplate>
</asp:ListView>
Also, the RadioButtonList and the CheckBoxList controls now include a new property called RepeatLayout.
Webform Routing
Routing is a feature in ASP.NET 4.0 that enables you to use URLs to map specific resources. These URLs can then become more descriptive and user friendly. Here is an example of an URL that is descriptive:http://server/mywebapplication/Students/View/NewStudents
Reading the routing information in an ASP.NET page is as simple as the following code:
String data = Page.RouteData.Values["Item"] as string;
ASP.NET Routing was originally developed as part of ASP.NET MVC but factored out into its own assembly (System.Web.Routing) as it is useful beyond the bounds of MVC. It is used in ASP.NET Dynamic Data for example and it’s even possible to use it in webforms with a bit of work.
In ASP.NET 4.0 all the necessary components to use ASP.NET Routing are inbuilt. These include theIRouteHandler implementation (PageRouteHandler class) that serves up the right IHttpHandler to service the request and a couple of expression builders to help capture parameters from routed requests and also generate route URLs. You simply need to set up your route patterns in Application_Start() as you do for ASP.NET MVC.
For a full details see ASP.NET 4.0 Routing .
SEO Enhancements
In addition to Webforms Routing, there are a couple of minor additions to ASP.NET 4.0 to make it easier to set the Keywords and Description meta tags on a page. The page class in ASP.NET 4.0 now has two new properties, namely, Keywords and Description. These can be set either in markup code or from the code behind so that you can generate the meta tags dynamically.
Continues…
50 Tips to Boost ASP.NET Performance – Part II
Continuing from ASP.NET Performance Tips Part 1 we now conclude with Performance Tips 26-50.
26. Batched Queries:
Queries can be used in a batch and thus network traffic can be reduced: Here is an example:
“Select EmpNo, EmpName, EmpAddress from Employee”;
“Select DepNo, DeptName From Department”;
From the above two queries it seems that there will be database hit twice .
Both the above queries can be executed in batched form and a single database hit will occur as follows:
“Select EmpNo, EmpName, EmpAddress from Employee; Select DepNo, DeptName From Department”;
27. Use IIS Compression
Page size can also be reduced using Http compression in IIS. Compression tool can also be used to reduced the size of rendered content.
28. Normalization
We should follow normalization rules in database table design but over Normalized tables can cause excessive joins for simple requirement. We should not make excessive joins for performance overhead and hence it is better to normalize only as much as required keeping in mind the performance issue.
29. Efficient Coding
While coding we should keep in mind the below issues which are potential performance drains:
1. Avoid use of Finalize method unless it is absolutely necessary.
2. Make a class sealed if inheritance is not required.
3. Avoid calling GC.Collect();
4. Use X+=1 instead X=X+1 to avoid evaluating X twice;
5. Use overloaded methods instead of different method names where possible.
30. Define The Scope of An Object
Defining an object’s scope properly increases efficient memory management and thus improve performance. We should keep the object scope at a lower level instead of a global level if possible because the garbage collector works more frequently on short lived object .
31. Using Loops
We should keep in mind while using loops in our code:
1. Better to use for a loop instead of foreach.
2. Do not create objects inside loop if not required absolutely.
3. Calling methods and properties inside loops is expensive.
4. Evaluating count etc. before loop starts. For example:
for(int i=0;i<Grid.Rows.Count;i++) {}can be written as
int iCount= Grid.Rows.Count; for(int i=0;i< iCount;i++){}
5. Never write exception handling code inside loop. Keep the exceptions handling code outside of the loop for better performance.
32. Dispose Instead of Finalize
Avoid using Finalize unless it is absolutely necessary. It is normally better to dispose of unmanaged resources if no longer required.
33. Minimize Thread Creation
Avoid creating threads on a per-request basis. Also avoid using Thread.Abort or Thread.Suspend.
34. Leave Connection pooling Enable
Connection Pooling is enabled by default. It boosts application performance as existing connections can be re-used from the pool rather than created . Leave this option enabled.
35. Using Blocks
Using blocks can be used as a short form of try..finally and it should be used only for those objects that implement the iDisposable interface. Here is a code snippet.
Using(SqlConnection con=new SqlConnection(connectionString)
{
try
{
con.Open();
//some code
}
catch(Exception e)
{
}
}
In the above example,there is no need to dispose of the connection object. The Connection object will be disposed automatically when it is out of scope.
Continues…
50 Tips to Boost ASP.NET Performance – Part I
When we are looking to optimize the performance of web applications we should keep in mind about Memory Load, Processor Load and Network Bandwidth. Here are 50 best practices to improve the performance and scalability of ASP.NET applications.
1. Page.IsPostBack Property
Keep code which only needs to be loaded once inside an IsPostBack block.
if(!IsPostBack)
{
BindDropDownList();
LoadDynamicControls();
}
As a result there will be no unnecessary database hits and server processing.
2. Enable Buffering
A buffer is a region in main memory to store temporary data for input and output .Data retrival from memory is faster than data retrieval from disk. We should leave buffering on unless there is any specific reason to turn it off. By default buffering is enable.
3. Remove unused HttpModules
There may be lot of HttpModules in Machine.Config that are not actually required for a particular application. In this scenario we should remove those unused HttpModules from application specific web.config file.
4. Trim Page Sizes
Reduce page size by removing any unnecessary space and tab characters from the page. As a result network traffic will be reduced.
5. Use a CDN
Not a performance tip exclusive to ASP.NET but an important step in speeding up a site is to use a Content Delivery Network (CDN) . CDN’s minimize the latency site visitors experience when they request a larger file from a data center that is located geographically far away. CDN’s cache files at numerous edge locations around the world to minimize latency.
If you are using Azure consider using the Windows Azure CDN , Amazon’s CloudFront cheap and easy to integrate into a website (if you happen to have a WordPress blog you can integrate S3 and CloudFront into WordPress)
6. Server.Transfer and Response.Redirect
“To perform client side redirection in ASP.NET, users can call Response.Redirect and pass the URL. When Response.Redirect is called, the server sends a command back to the browser telling it to request the page redirected to it. An extra roundtrip happens, which hit the performance. We can send information from the source page by using a query string. There is a limitation on the length of a query string; it cannot be used to pass large amounts of data over the wire.
To perform server-side redirection, users can use Server.Transfer. As the execution is transferred on the server, Server.Transfer does not require the client to request another page. In Server.Transfer, by using HttpContext we can access the source page’s items collection in target page. The drawback of using this method is that the browser does not know that a different page was returned to it. It displays the first page’s URL in the browser’s address bar. This can confuse the user and cause problems if the user tries to bookmark the page. Transfer is not recommended since the operations typically flow through several different pages.”
7. Precompiling
Precompiling an ASP.NET Web site provides faster initial response time for users because pages do not have to be compiled the first time they are requested. This is particularly useful for large Web sites that are updated frequently. In order to achieve that we can use ASP.NET Compilation Tool (Aspnet_compiler.exe).
8. Session State Management
Efficient state management helps to boost the performance and scalability of application. It is not advisable to keep large objects in a session variable and it is optimal to make disable session state whenever it is not required. We can turn session state off either at the Page level or at the application level using the config file.
9. ViewState
By default the viewstate is enabled for applications and we should disable it whenever it is not required. Otherwise it will increase the page size. Every byte added to a web page by enabling its viewstate causes two bytes of network traffic – one in each direction. Disable
view state in any of the following scenarios:
(i) A readonly page where there is no user input.
(ii) A page that does not postback to the server
(iii) A page which requires rebuilding server controls on each post back without checking the post back data.
It is best practice to turn ViewState off at the application level and then enable it as required at the page or even control level.
10. Caching
Probably the number one performance tip is to use caching. In order to store static data caching is ideal one. There are different types of caching: Page output caching, Page fragment caching data caching and we have to select the correct type as per requirement.
In almost all scenarios at least a part of a page can be cached.
11. Locking and Shared Resources
Acquire shared resources late and release them as early as possible. Avoid locking unless absolutely necessary. Do not set lock on the “this;” it is better to use a private object to lock on as follows:
public Class Test
{
private stativ readonly objLock=new Object();
public static Test Singleton
{
lock(ObjLock)
{
return new test();
}
}
Continues…