Monday, 20 August 2012

Per-Request Caching in ASP.NET

Earlier in the article, I mentioned that small improvements to frequently traversed code paths can lead to big, overall performance gains. One of my absolute favorites of these is something I've termed per-request caching.
Whereas the Cache API is designed to cache data for a long period or until some condition is met, per-request caching simply means caching the data for the duration of the request. A particular code path is accessed frequently on each request but the data only needs to be fetched, applied, modified, or updated once. This sounds fairly theoretical, so let's consider a concrete example.
In the Forums application of Community Server, each server control used on a page requires personalization data to determine which skin to use, the style sheet to use, as well as other personalization data. Some of this data can be cached for a long period of time, but some data, such as the skin to use for the controls, is fetched once on each request and reused multiple times during the execution of the request.
To accomplish per-request caching, use the ASP.NET HttpContext. An instance of HttpContext is created with every request and is accessible anywhere during that request from the HttpContext.Current property. The HttpContext class has a special Items collection property; objects and data added to this Items collection are cached only for the duration of the request. Just as you can use the Cache to store frequently accessed data, you can use HttpContext.Items to store data that you'll use only on a per-request basis. The logic behind this is simple: data is added to the HttpContext.Items collection when it doesn't exist, and on subsequent lookups the data found in HttpContext.Items is simply returned.

ASP.NET Cache API

One of the very first things you should do before writing a line of application code is architect the application tier to maximize and exploit the ASP.NET Cache feature.
If your components are running within an ASP.NET application, you simply need to include a reference to System.Web.dll in your application project. When you need access to the Cache, use the HttpRuntime.Cache property (the same object is also accessible through Page.Cache and HttpContext.Cache).
There are several rules for caching data. First, if data can be used more than once it's a good candidate for caching. Second, if data is general rather than specific to a given request or user, it's a great candidate for the cache. If the data is user- or request-specific, but is long lived, it can still be cached, but may not be used as frequently. Third, an often overlooked rule is that sometimes you can cache too much. Generally on an x86 machine, you want to run a process with no higher than 800MB of private bytes in order to reduce the chance of an out-of-memory error. Therefore, caching should be bounded. In other words, you may be able to reuse a result of a computation, but if that computation takes 10 parameters, you might attempt to cache on 10 permutations, which will likely get you into trouble. One of the most common support calls for ASP.NET is out-of-memory errors caused by overcaching, especially of large datasets.
There are a several great features of the Cache that you need to know. The first is that the Cache implements a least-recently-used algorithm, allowing ASP.NET to force a Cache purge—automatically removing unused items from the Cache—if memory is running low. Secondly, the Cache supports expiration dependencies that can force invalidation. These include time, key, and file.

Connection Pooling in ASP.NET

Setting up the TCP connection between your Web application and SQL Server can be an expensive operation. Developers at Microsoft have been able to take advantage of connection pooling for some time now, allowing them to reuse connections to the database. Rather than setting up a new TCP connection on each request, a new connection is set up only when one is not available in the connection pool. When the connection is closed, it is returned to the pool where it remains connected to the database, as opposed to completely tearing down that TCP connection.
Of course you need to watch out for leaking connections. Always close your connections when you're finished with them. I repeat: no matter what anyone says about garbage collection within the Microsoft® .NET Framework, always call Close or Dispose explicitly on your connection when you are finished with it. Do not trust the common language runtime (CLR) to clean up and close your connection for you at a predetermined time. The CLR will eventually destroy the class and force the connection closed, but you have no guarantee when the garbage collection on the object will actually happen.
To use connection pooling optimally, there are a couple of rules to live by. First, open the connection, do the work, and then close the connection. It's okay to open and close the connection multiple times on each request if you have to (optimally you apply Tip 1) rather than keeping the connection open and passing it around through different methods. Second, use the same connection string (and the same thread identity if you're using integrated authentication). If you don't use the same connection string, for example customizing the connection string based on the logged-in user, you won't get the same optimization value provided by connection pooling. And if you use integrated authentication while impersonating a large set of users, your pooling will also be much less effective. The .NET CLR data performance counters can be very useful when attempting to track down any performance issues that are related to connection pooling.
Whenever your application is connecting to a resource, such as a database, running in another process, you should optimize by focusing on the time spent connecting to the resource, the time spent sending or retrieving data, and the number of round-trips. Optimizing any kind of process hop in your application is the first place to start to achieve better performance.
The application tier contains the logic that connects to your data layer and transforms data into meaningful class instances and business processes. For example, in Community Server, this is where you populate a Forums or Threads collection, and apply business rules such as permissions; most importantly it is where the Caching logic is performed.

Friday, 17 August 2012

Paged Data Access in ASP.Net Data Grid

The ASP.NET DataGrid exposes a wonderful capability: data paging support. When paging is enabled in the DataGrid, a fixed number of records is shown at a time. Additionally, paging UI is also shown at the bottom of the DataGrid for navigating through the records. The paging UI allows you to navigate backwards and forwards through displayed data, displaying a fixed number of records at a time.
There's one slight wrinkle. Paging with the DataGrid requires all of the data to be bound to the grid. For example, your data layer will need to return all of the data and then the DataGrid will filter all the displayed records based on the current page. If 100,000 records are returned when you're paging through the DataGrid, 99,975 records would be discarded on each request (assuming a page size of 25). As the number of records grows, the performance of the application will suffer as more and more data must be sent on each request.
One good approach to writing better paging code is to use stored procedures.

The total number of records returned can vary depending on the query being executed. For example, a WHERE clause can be used to constrain the data returned. The total number of records to be returned must be known in order to calculate the total pages to be displayed in the paging UI. For example, if there are 1,000,000 total records and a WHERE clause is used that filters this to 1,000 records, the paging logic needs to be aware of the total number of records to properly render the paging UI.

Tip for Return Multiple Resultsets

Review your database code to see if you have request paths that go to the database more than once. Each of those round-trips decreases the number of requests per second your application can serve. By returning multiple resultsets in a single database request, you can cut the total time spent communicating with the database. You'll be making your system more scalable, too, as you'll cut down on the work the database server is doing managing requests.
While you can return multiple resultsets using dynamic SQL, I prefer to use stored procedures. It's arguable whether business logic should reside in a stored procedure, but I think that if logic in a stored procedure can constrain the data returned (reduce the size of the dataset, time spent on the network, and not having to filter the data in the logic tier), it's a good thing.
Using a SqlCommand instance and its ExecuteReader method to populate strongly typed business classes, you can move the resultset pointer forward by calling NextResult.

jQuery Plug-in for Showing Message Box in Topbar

Topbar message box plug-in can be used to showing message box or notifications on a web page. This is very simple to use and easy to configure. Of course you need jQuery to use this.

Usage

To use this plug-in include jQuery and juery.topbar.js in you web page -
<script src="jquery.js" type="text/javascript"></script>
<script src="juery.topbar.js" type="text/javascript"></script>
Now create a html element which you want to show in topbar as messagebox -
<p>
    <a href="javascript:void(0)" id="demo01">Demo 1 - Simple</a>
</p>
<div id="demo01-body" style="display:none;">
    This is a simple demo
    <span style="font-size: small">(click to close)</span>
</div>
Now use showTopbarMessage to show the notification on topbar -
$(function () {

    $("#demo01").click(function () {
        $('#demo01-body').showTopbarMessage();
    });

});
Currently you can configure following attributes -
  • background: Hex code of color for bar background. Default value is - "#888".
  • borderColor: Hex code of color for bar border color. Default value is - "#000".
  • foreColor: Hex code of color for bar fore color. Default value is - "#000".
  • height: Height of the bar. Default value is "50px".
  • fontSize: Size of the text displayed in the top bar. Default value is - "20px"
  • close: Specify how the notifications will be closed. "click" – means it will be closed on click, else specify number of milliseconds after which bar will be closed automatically.

Flex mobile development tips and tricks

This is Part 2 of a multipart series of articles that cover tips and tricks for Flex mobile development. Part 1 focused on handling data when switching between views and between application executions. This part covers styling the ActionBar and tab components in your mobile application.
When you’re building a TabbedViewNavigatorApplication in Flex 4.5, you can customize your tabs or ActionBar (the title bar that contains title text and any other components or navigation content) in a couple of different ways. One approach would be to skin the tabs with your own custom assets (for example with FXG or skins). If your application does not need extensive customization, however, you may be able to use simple CSS properties. CSS styling provides a quick and easy way to make a dramatic change away from the default boring gray tabs.
I created a sample tabbed application to illustrate how this can be done. In the following examples you will see how adding some simple properties and just a few lines of CSS can change your ActionBar and mobile application tabs quickly!

Adding icons to the tabs

Consider the following code for a Flex TabbedViewNavigatorApplication with three tabs that link to their own first views:
<?xml version="1.0" encoding="utf-8"?> <s:TabbedViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"><s:ViewNavigator id="trends" label="Trends" width="100%" height="100%" firstView="views.TrendsView"/> <s:ViewNavigator id="attach" label="Attach" width="100%" height="100%" firstView="views.AttachView"/> <s:ViewNavigator id="call" label="Call Center" width="100%" height="100%" firstView="views.CallView"/> </s:TabbedViewNavigatorApplication>
By default, when you create a Flex mobile project the Mobile theme will be applied automatically (see Figure 1).
Figure 1. The sample application with the default Mobile theme.
Figure 1. The sample application with the default Mobile theme.
This is, of course, not very exciting. However, one way to make it more engaging is by adding icons to the tabs.
To add an icon to the tabs you can set the icon property on each of the ViewNavigator components to an icon of our choice. In the code below I’ve added three icons from the assets directory within my project root. .
<?xml version="1.0" encoding="utf-8"?> <s:TabbedViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"> <s:ViewNavigator id="trends" label="Trends" width="100%" height="100%" firstView="views.TrendsView" icon="@Embed('assets/column-chart-icon32.png')"/> <s:ViewNavigator id="attach" label="Attach" width="100%" height="100%" firstView="views.AttachView" icon="@Embed('assets/paperclip-icon32.png')"/> <s:ViewNavigator id="call" label="Call Center" width="100%" height="100%" firstView="views.CallView" icon="@Embed('assets/receptionist-icon32.png')"/> </s:TabbedViewNavigatorApplication>
With just that simple change, you can add character to your tabs (see Figure 2).
Figure 2. The sample application with icons on the tabs.
Figure 2. The sample application with icons on the tabs.

Styling the ActionBar

Icons on the tabs are a good start, but if you’re like me, you’re eager to change the gray colors used on the ActionBar component and tabs to match a theme that you have in mind. You can do that with CSS.
For the ActionBar you simply use the Spark selector for the ActionBar component and specify any supported styles or inherited styles to change.
Note: The Flex 4.5 ActionScript API documentation shows the specific style properties supported for each component, as well as inherited styles. It also shows if a style property has CSS inheritance or not. If you check out the ActionBar component in the API, you can see what can be styled.
Before you start changing styles, you may be interested in knowing what the default values are. For instance, you may want to know what the default font size and weight is, which may not be as obvious as the font color. You can take a look at the default CSS properties for the Mobile theme to better understand what you’re styling. On Mac OS, the defaults.css file can be found at: /Applications/Adobe Flash Builder 4.5/sdks/4.5/frameworks/projects/mobiletheme/defaults.css. On Windows, it can be found at: C:\Program Files (x86)\Adobe\Adobe Flash Builder 4.5\sdks\4.5.0\frameworks\projects\mobiletheme\defaults.css.
Here are two snippets from that file on the ActionBar and its title:
ActionBar { chromeColor: #484848; defaultButtonAppearance: normal; skinClass: ClassReference("spark.skins.mobile.ActionBarSkin"); textShadowAlpha: .65; textShadowColor: #000000; paddingBottom: 1; paddingLeft: 0; paddingRight: 0; paddingTop: 1; } ... ActionBar #titleDisplay { color: #FFFFFF; fontSize: 28; fontWeight: bold; }
Notice the font color, size, and weight are set using the titleDisplay ID selector.
Since there’s not much to the ActionBar in my sample application—it just has a text title— I’m just going to customize the title. If you have buttons and other components within your ActionBar, you can customize supported styles for those as well.
The titleDisplay skin part of the ActionBar is easily styled using CSS. I simply set the following CSS properties for my sample application in an <fx:style> tag:
s|ActionBar { chromeColor: #229988; titleAlign: center; } s|ActionBar #titleDisplay { color: #CCCCCC; /* default color is white */ fontSize: 40; fontFamily: "Comic Sans MS"; }
The ActionBar now has centered white text on an aqua background in Comic Sans (see Figure 3).
Figure 3. The sample application with a styled ActionBar.
Figure 3. The sample application with a styled ActionBar.

Styling tabs

You can also use CSS to style the tabs in a tab bar. For this you’ll need to specify the tabBar skin part of the TabbedViewNavigator component in the CSS rule. Take another look at the defaults.css file for the Mobile theme, to see this skin part’s default settings:
TabbedViewNavigator #tabBar { chromeColor: #484848; color: #FFFFFF; fontSize: 20; fontWeight: normal; iconPlacement: top; interactionMode: mouse; skinClass: ClassReference("spark.skins.mobile.TabbedViewNavigatorTabBarSkin"); textShadowAlpha: .65; textShadowColor: #000000; }
Note: The tabBar defined in the TabbedViewNavigator component is actually a ButtonBar. The Spark TabBar is not yet optimized for mobile. If you go down the path of customizing skins, this is important to know since the TabbedViewNavigatorTabBarSkin actually extends ButtonBarSkin.
Once again, I can add a CSS rule to my application’s <fx:style> tag to customize the look of the component by adding my own style:
TabbedViewNavigator #tabBar { chromeColor: #229988; color: #CCCCCC; fontFamily: "Comic Sans MS"; iconPlacement:left; textDecoration:underline; }
Now the tabs are in Comic Sans with a background color that matches the ActionBar (see Figure 4). Keep in mind, I am definitely not a designer, but it should be apparent how easy it is to change the look of your application by simply adding a block of CSS.
Figure 4. The original sample application (left) and the application with styled tabs (right).
Figure 4. The original sample application (left) and the application with styled tabs (right).
Here’s the full source for the main tabbed application file. In addition to the CSS, it references the basic views in the views folder by setting the firstView property in the ViewNavigator objects to views.TrendsView, views.AttachView, and views.CallView respectively:
<?xml version="1.0" encoding="utf-8"?> <s:TabbedViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"> <fx:Style> @namespace s "library://ns.adobe.com/flex/spark"; s|ActionBar { chromeColor: #229988; titleAlign: center; } s|ActionBar #titleDisplay { color: #CCCCCC; fontSize: 40; fontFamily: "Comic Sans MS"; } s|TabbedViewNavigator #tabBar { chromeColor: #229988; color: #CCCCCC; fontFamily: "Comic Sans MS"; iconPlacement:left; textDecoration:underline; } </fx:Style> <s:ViewNavigator id="trends" label="Trends" width="100%" height="100%" firstView="views.TrendsView" icon="@Embed('assets/column-chart-icon32.png')"/> <s:ViewNavigator id="attach" label="Attach" width="100%" height="100%" firstView="views.AttachView" icon="@Embed('assets/paperclip-icon32.png')"/> <s:ViewNavigator id="call" label="Call Center" width="100%" height="100%" firstView="views.CallView" icon="@Embed('assets/receptionist-icon32.png')"/> </s:TabbedViewNavigatorApplication>
Note: The above example includes the styles within the MXML application for simplicity. However, it’s generally a good practice to create a separate CSS file to contain all of your styles and include a reference to that CSS file in your main application file.
You can explore the complete source code for this project by downloading and importing the sample files for this article.

Where to go from here

Now that you’ve seen how easy it is to style your Flex mobile application, here are some general guidelines to keep in mind:
  • If you are styling colors, text, alignment, icons, and so on then use CSS.
  • If you want to create a look with more graphical elements then use FXG, custom skins, and images.
  • If you need to skin for devices that have different dots-per-inch (DPI) densities then use CSS media filters or special skin classes in FXG loaded for each DPI you want to support. DPI varies between devices and operating systems. The iPhone 4 or iPad (both 320 DPI) have a different density than the Android Nexus One (240 DPI) and Motorola Xoom (160 DPI). Flex 4.5 has several built-in capabilities for supporting screen densities. Be sure to read Jason San Jose’s article Flex mobile skins – Part 2: Handling different pixel densities for more on this topic.