July 02, 2008

Caching multiple versions of a page

A web page may be required to display different data on user selection. Caching such pages will enable visitors to browse all the pages speedily and avail a better user experience. Creating a cache for such pages can be done by using the declarative method of using OutputCache directive. The declarative method is the most simple and straight forward method of implementing a cache.

We have already seen how to implement a basic technique of page output caching. To recap, we enable page output caching by including following page directive in a web page.

<%@ OutputCache Duration=”60”  VaryByParam=”none” %>

An example of displaying data on user selection is when a web page has to display data pertaining to a country based on the country selected by the user. Such web pages are also referred to as multiple versions of a web page. To program such a web page, we pass a value selected by the user, to a stored procedure and the resulting data is displayed on the web page.

By using page output caching, we can cache each version of the web page. For the example discussed above we can have a cache of the data for each of the country. So, whichever the country the user selects, the cache will be displayed thereby enhancing performance. 

In the code statement given above we have used the OutputCache directive which includes two attributes using which we can modify the cache output.

The two attributes are:

VaryByParam
VaryByHeader


VaryByParam

The VaryByParam attribute specifies how a page should be cached when a request for that page contains parameters. A simple and straight forward implementation is the use of *. This directs that a cache be created for each of the form field parameters. However in cases where the parameters are many in number, it is advised to list the parameters separated by the semicolon, so that a cache is created for those parameters listed only. This will optimize the resouce usage on the server.

<%@ OutputCache Duration=”60”  VaryByParam=”Country,State” %>


VaryByHeader

This attribute is used to overcome the problem of displaying the same cached content to all browsers. By using this attribute we can store different versions of the web page content for different browsers. We assign User.Agent value to this attribute. To identify the browser, we use the statement in the web page, as shown below.

Sub Page_Load
If Request.Browser.Brower =”Netscape” Then
// display content in bold
Else
// display content in italics
End If
End sub

From the above code, the User.Agent header identifies the type of browser being used to request the page. If the browser is Netscape, it display the content of a control in bold. Similarly we can alter the content to be displayed based on the type of browser. The various versions of a browser are also accommodated with this attribute. 

Related articles

Caching multiple versions of a web page

Related topics

Caching Multiple Versions of a User Control using SetVaryByCustom()
Page fragment caching
Varying page fragment caching by parameter
Page data caching
Cache file dependencies


July 01, 2008

Cache in ASP.Net application

Cache is a temporary storage place inside a computer. This storage place is used to store and access data which is frequently used in an application. Cache is pronounced cash.

This article is about using a cache in a web application. A web application is accessed by many people via the Internet. It is important that the visitors to the web site (web application) are able to experience a fast page load. This enhances user experience and entices visitors to keep coming back. This is one of the major requirements of creating and running a web application.

We will discuss this topic in the context of ensuring faster page upload and less frequent data access. Note that the cache feature is available in almost web application programming languages. For instance PHP has its set of classes and methods to implement cache. You can have a detailed overview of PHP cache at:

http://en.wikipedia.org/wiki/PHP_accelerator

Coming back to ASP.Net Cache, there are two types of implementing Cache. They are

  • Page output caching
  • Application caching


As mentioned before, cache is used to reduce frequency of data access. This is accomplished by storing a copy of the web application or web page in memory and feeding this copy to the user’s browser whenever a request is made. However, ASP.Net provides different ways of creating and using a cache.

Page output caching

Let us now recall how a web page loads.

When a browser requests a web page, the IIS server (web server)  processes the request and creates the cache of the output. This cache is sent to the browser every time the browser requests the page. IIS has to find the directive in the ASP.Net web page.

<%@ OutputCache Duration=”10” VaryByParam=”none” %>

ASP.net provides options to specify the duration of the Cache.

This method of creating Cache is called as page output caching.

A high-traffic Web page that has to display data that is not frequently updated, is suitable for implementing page output caching. Using Webconfig file, page caching can be configured for many pages. Page output caching dramatically increases the performance by eliminating the need for going through the asp.net page life cycle for creating the page output. Note that for the first time page the IIS has to generate an output and send it to the browser. The freshness of the data is dependent on the duration of the cache.

There are two models for page output caching:

Full page caching
Full page caching is used to cache the entire contents of a page.

Partial page caching.
Partial page caching is used to cache the parts of a web page which are dynamic.

Application caching

In many web applications, it may be necessary to cache only that data which is generated from a database. In such circumstances, application caching is used. In this method, we can cache only that data such as DataSet which is created from the database and use it whenever required. The applcation of this method can be in applications where the same data is required to be shown in multiple pages.   

We create the cache programmatically using Cache class which includes key/value pairs.

Application Cache programming involves determining whether the required data exists in the cache and if it does use it and if not recreate the cache.

Two instances when we find using cache is beneficial.

When an application processes large amounts of data. 
When an application processes data which is updated only occasionally.

How to implement cache?

The following code shows how to implement application caching.

Application caching

DataSet dstNews;
dstNews = Cache["News"] as DataSet;
if (dstNews == null) {
  strConString = "Data Source=202.XX.XXX.XX;database=newsabc;User ID=abc123;Password=cd546dc;";
   conRes= new SqlConnection( strConString );
    dstNews = new DataSet();
    //Get Newest 100 news From Database
    dadNews = new SqlDataAdapter( "getNews", conRes );
    dadNews.SelectCommand.CommandType = CommandType.StoredProcedure;
    dadNews.Fill( dstNews, "news_msg");
Cache["News"] = dstResumes;
}

Page output caching

The following statement  shows how to implement Page output caching.

<%@ OutputCache Duration=”10” VaryByParam=”none” %>

May 08, 2008

How to retrieve a particular identifier when multiple tables have identifier columns

What is an Identity Column? An identity column is a method to build primary keys. Like an auto-number column or sequence column in other databases, the identity column in SQL Server generates consecutive integers as new rows are inserted into the database. Advantages of using Identity column as primary keys are:

  • Integers are easier to manually recognize and edit than GUIDs.
  • Integers are small and fast.
  • An Identity column used as a primary key with a clustered index (a common, but poor practice) may be extremely fast when retrieving a single row with a single user. However, that configuration will cause lock-contention hot spots on the database.

Identity column values are created by SQL Server as the row is being inserted. Note that for the Identity column the NOT NULL option is essential.

How to Create an Identity Column for a Table:

Select the identity column in the table view and expand Identity specification in the Column Property window and then set the property Is Identity to Yes.

Type a value in the Identity increment cell. This value is the increment that is added to the Identity Seed for each subsequent row. The default value is 1.

Type value in Identity Seed cell. This value is assigned to the first row in the Table. Default value is 1.

Identity Column does not guarantee that the value used as an identifier will be unique throughout the database across tables. Note that the data type to be selected for Identity columns are int, smallint, tinyint, decimal or numeric. Below is the code for creating unique identifiers.

CREATE TABLE mySchema.Customer (
CustID INT  IDENTITY NOT NULL PRIMARY KEY NONCLUSTERED,
CustName VARCHAR(30) UNIQUE NOT NULL,
City VARCHAR(50) NOT NULL
)
ON [Primary]

We need to retrieve an identifier of a row of data in a table to insert the same value in that table or another table to maintain relationships.

Normally, we use the function @@IDENTITY which returns the last identity value that was inserted in the database. But, what we need is the identity value of a particular table in which the last record was inserted. We use UDFs to accomplish this task. A typical UDF code snippet is given below:

CREATE   FUNCTION GetComIdentity() RETURNS INT AS
BEGIN
RETURN (IDENT_CURRENT('com_msg'))
END

CREATE TABLE admin.com_msg (
    [id_msg] [int] IDENTITY (1, 1) NOT NULL ,
    [idtop_msg] [int] NOT NULL ,
    [idmsg_msg] [int] NULL ,
    [id_init_msg] [int] NOT NULL CONSTRAINT  [DF__com_m__id_in__4257997F] DEFAULT ([admin].[GetComIdentity]()),
    [brief_msg] [varchar] (200) NULL,
     PRIMARY KEY  CLUSTERED
    (
        [id_msg]
    ) WITH  FILLFACTOR = 90  ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

Creating Tables with SQL Scripts

We can create a Database tables in SQL Server using any of the following two modes:

  • Using Graphical Environment – Object Explorer
  • Using Scripts

The graphical environment is intuitive and is easy to use. It is a great tool for the beginner to get started quickly.

An experienced programmer prefers to use scripts to create the Database tables. A script is a batch file which is run in the SQL Server environment.

The following CREATE TABLE DDL command creates the Customer table. The table name, including the name of the schema is provided, followed by the table’s columns. The code directs SQL Server to create the table on the primary filegroup. Apart from the columns, the only information you normally supply when creating a table is the name.

CREATE TABLE mySchema.Customer (
CustID INT  NOT NULL PRIMARY KEY NONCLUSTERED,
CustName VARCHAR(30) UNIQUE NOT NULL,
City VARCHAR(50) NOT NULL
)
ON [Primary]

Note:

A filegroup is a collection of files. A file or filegroup cannot be used by more than one database. Every database comprises of a Primary filegroup which contains the system tables.

If you are developing a database for mass deployment or repeat installations, having the code in one location helps in mass deployment. Working with SQL scripts is similar to developing an application with Visual Basic or C#.

Another advantage of using scripts is that the existing database can be upgraded to the most current version of the database without running ‘change scripts’ or restoring the backup.

Drawbacks

The T-SQL commands may be unfamiliar and the size of the script may become overwhelming.

If the foreign-key constraints are embedded within the table, the table-creation order is very strict. If the constraints are applied after the tables are created, the table-creation order is no longer a problem; however, the foreign keys are distanced from the tables in the script.

How to implement business rules in a Microsoft Sql Server Database?

Business rules are rules or conditions that drive your entire software application system. Business Rules ensure that your data is correct and of use at any point of time. A software application system developed for a Health care domain will have a set of business rules, which may be entirely or partly different from those for a Banking and Financial software system. System analysts while designing the software application system, decide where to implement the business rules – whether on the client side or at the server side. MS SQL Server offers the following means to implement business rules: Constraints, Stored Procedures, Triggers and Rules.

Common examples of simple business rules: A sales order should not have a negative sales amount and should have a unit price, which is greater than zero. Another example is, when a sales order is being generated the stock level should not fall below the zero level. This is required to ensure that there is stock available to fulfill the order. Using an RDBMS, we can incorporate these rules right into the database itself. Let us see how we implement these business rules in SQL Server database by using Constraints.

A Constraint is an object that exists only within the table either at column level or table level. A Constraint is a high-level data validation check or business logic check performed at the database-engine level. Implementing constraints has undergone changes with every release of SQL Server. A common type of Constraint used is Check constraint. Check constraints are useful for ensuring the enforcement of general data-validation rules or simple business rules. A constraint is defined using the same rules that we use in a WHERE clause of a SQL Query.

Examples

To Limit Month column to appropriate numbers

SQL:

BETWEEN 1 AND 12

To Limit to a specific list of shippers

SQL:

IN(‘UPS’,’Fed Ex’,’USPS’)

To ensure Price is a positive number

SQL:

UnitPrice >=0

To Reference another column in the same row and to validate shipment date is always greater than order date.

SQL:

Shipdate >=OrderDate

Note:

Almost anything we put in a WHERE clause can also be put in a constraint.  Constraints are fast compared to the alternatives like rules and triggers.

Another example of a using a Constraint:

In an accounting software database, consider the customer registration table. We need to check for a valid date in a date field while recording the customer registration. Note that we cannot have a date in the system that is a future date. To enforce this validation we use the following constraint.

ALTER TABLE Customers
ADD CONSTRAINT CK_CN_CustomerDate
CHECK
(date<=GETDATE())

If we try to insert a record that violates the CHECK constraint, MS SQL Server will report an error.

Next: Client and Server responsibilities, which a programmer should be aware of.

April 06, 2008

Common Features of Programming Languages

Every programming language has core features. These features have evolved over a period, depending on the purpose the languages were created for and the market they targeted. All programming languages have common core set of common features. Implementation of these core set of features varies from language to language. The history of the language will give us an idea of the market the languages were intended for.

Here is a list of the common features:

  • A place for storing data. Arrays are advanced storing data facility. Also known as data structures.
  • Rules for writing programs in that programming language
  • Control statements – which are building blocks for logic implementation.
  • Most programming languages of today support OOPs. So, constructs to implement like features Class declaration, objects, inheritance, polymorphism and constructors are included.
  • Every language has operators. Operators are used execute mathematical operations.
  • All languages include facility to write programs, functions and procedures. Incidentally, this is the place where you write your programs. Functions return values after execution, whereas procedures simply execute programs.
  • All programs include facility to write libraries. Libraries are themselves programs, which can be used in other programs.
  • All languages support exception handling. This feature is helpful to identify errors and generate appropriate messages.
  • All languages include built in functionalities, provided as classes and functions. These classes help to write better programs.

All languages include a compiler and memory handling features. These are implemented in different ways by the person (s) who have developed the language. Dot net strives to hide the remove the memory handling issue from the developer.

If you have any thing to add do post your reply. I will gladly include the same. If you need to contact email me at k. vkpub @ gmail.com.

Next :
Common Features of RAD Tools.
Common Features of Open Source Tools.

February 25, 2008

How to make your web site work in all browsers

When we develop a web page with features which may not work in all browsers we need to ensure that the web page works with all browsers by programming the DOM elements. We do this by adding an event handler to an event exposed by a DOM element using $addhandler.

For those of you who are not familiar, a DOM element is a element of a DOM tree. A DOM tree is a hierarchical representation of all HTML elements which we place in the web page. An event handler helps to associate a function with an event. For example,

Object             Event Handler

Button              onclick
Text                onchange,  Onfocus

Note that this definition of event handler pertains to JavaScript.

Firstly, let us see how to attach code to Dom events using Javascript. If you use Javascript earlier, we will acquitted with the event model. We can program each DOM element of the DOM tree of a web page by associating events and code in event handlers as we will see below.

Let us take the example of a button. A HTML button element can raise a click event when it's clicked by the user. We will associate the function validcheck(), to the event handler onclick of the button object. The following code does this.

<input type=”button” name=cmdsubmit” onclick=” validcheck()>

A number of different types of event handlers can be triggered by different events.Common events that can trigger JavaScripts are mouse actions ,keyboard actions , actions on form fields.

This method of attaching code to DOM events will not work in all browsers. This is because, different browsers implement the DOM programming differently. So, your web page working on one browser may not work on other browsers.

The Microsoft Ajax Library provides to the problem by including an abstract API which abstracts the operations made on Dom elements. This API eliminates the need to know which functions are supported by the DOM implementation of a particular browser whether it is a Internet explorer, Firefox, Safari or Opera.

The abstraction API consists of two classes: Sys.UI.DomElement and Sys.UI.DomEvent.


Sys.UI.DomEvent Class
 

The Sys.UI.DomEvent Class is included in the Microsift Ajax library to provide cross browser compatibility to DOM events.  This class contains in the Namespace: Sys.UI. We use the DomEvent class to add, remove, modify, and handle client events.

Sys.UI.DomEvent addHandler Method
 

This method is a class of the Sys.UI.DomEvent and  enables us to add a DOM event handler to the DOM element.

Sys.UI.DomEvent.addHandler(element, eventName, handler);

Term              Definition

element          The element that exposes the event.
eventName     The name of the event.
handler           The client function that is called when the event occurs.

The class  Sys.UI.DomEvent addHandler can also be written as $addHandler.

Use the addHandler method to add a DOM event handler to the element that exposes the event. The eventName parameter should not include the "on" prefix. For example, specify "click" instead of "onclick". This method can be accessed through the $addHandler shortcut method.

$addHandler(element, eventName, handler);

The below example demonstrates how a blur event occurs when a text field on a form loses focus. This example also demonstrates the $addhandler will result in cross browser compatibility.

<form id="form1" runat="server">
<asp:ScriptManager ID="TheScriptManager" runat="server"></asp:ScriptManager>
<script type="text/javascript">
function pageLoad() {
            var txtName = $get('txtName');                

            $addHandler(txtName,                              
               'blur', txtName_focus);                
        }

        function pageUnload() {
            $removeHandler($get('txtName'),                     
                'blur', txtName_focus);                
        }                                                         

        function txtName_focus(evt) { 
                      var count = $get("txtName").value.length;
                       $get("count").innerHTML="";
                       $get("count").innerHTML = count;

                                                                

        }

    </script>
    <span>Please type some text:</span>
    <input type="text" id="txtName" />                
    <span id="count">Number of characters</span>
    </form>

The above program displays the number of characters entered in the textbox when the textbox loses the focus.

February 22, 2008

Pros and cons of Programming models (AJAX)

Server Centric Programming Model

Compared to the client-centric programming model, the Server-centric programming model is easy to implement. All we need to know is develop the Asp.net application and then wrap certain areas of the page with UpdatePanels. By doing so, we will be using the minimal Ajax implementation.

Using UpdatePanels means posting the entire page to the server. Even when the required update to the web page is minimal, every asynchronous postback results in more server side processing. This results in downgraded performance.

From coding point of view, using UpdatePanel control results in elegant code. Sections of the page are wrapped by the UpdatePanels and all Ajax processing is taken up by the UpdatePanel control.

The server-centric approach denies granular level of control to the developer which is needed for sophisticated interactive web applications.

Client-Centric programming model

The Client-centric approach is adopted to build sophisticated interactive web applications. Such application scan be developed by using JavaScript, which means a high degree of expertise.

The Client-centric approach involves using ScriptManager control which enables calling of methods of a class bypassing the asp.net page life cycle. Which means, optimum usage of server resources.

Because we use client side DHTML controls, during a response, only required data from the server is rendered. This reduces the network traffic.

From a coding point of view, JavaScript code used for various features of a web page results in more maintenance.

The client-side approach has its own limitations as it cannot handle rich UI elements like menus, treeviews, grids, etc.




February 21, 2008

ASP.Net AJAX Programming models

When we set out to develop AJAX based web applications, we need to make a clear choice whether the application is going to be based on :

  • Server-centric programming model   
  • Client-centric programming model
  • Hybrid or a mixture of  Server-centric programming model and  Client-centric programming model

Many a times this decision is based on the existing applications which needs to be upgraded. Often factors like skills of a programmers available determine the choice of the programming model. Note that there are no clear guidelines which can help us to decide on the programming model. In this blog post we will see how a client-centric model and server-centric model is implemented.

Server-centric programming model

  • The application logic (written in VB.Net or C# )and user interface is hosted on the server.
  • This model is more like a minimal ajax implementation because we use only ScriptManager control, UpdatePanel control and almost no JavaScript code.
  • For existing applications to be upgraded to Ajax, we can retain the core Application logic and UI.
  • Flicker free increamental updates by using only the ScriptManager control, UpdatePanel control.

In the example below, we use the <UpdatePanel> tag and one of its child tags <ContentTemplate> to allow to refresh the label. By using the above tags, we are leveraging the power of Ajax to refresh the label without the need to postback the entire page.

The Server-Centric programming model involves adding the UpdatePanel control and placing all Asp.net controls within it. Note that in every Asp.net Ajax page, we need to place the one ScriptManger control.
The functionality of the below code is to increament the counter of the Label control when user clicks on the PartialButton.

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />

<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode=Always ChildrenAsTriggers=true>
<ContentTemplate>
<asp:Button ID="PartialButton" runat="server" text="Partial Post Back" OnClick="InsideButton_OnClick" />
<br />
<br />
Counter (Partial):
<asp:Label ID="PartialLabel" Text="1" runat="server" /><br />
</ContentTemplate>
</asp:UpdatePanel>
   
<script runat="server">

Sub InsideButton_OnClick(ByVal sender As Object, ByVal e As System.EventArgs)
  PartialLabel.Text += 1
End Sub
   
</script>

Client-centric programming model

The client-centric model is chosen when there is a compelling need to provide rich user experience in your application. In this programming model, both application logic and UI is implemented in the browser. The rich user experience is implemented using JavaScript, DHTML. Web service calls are used to retrieve the data from the server.

To learn more on creation of web services click here : Create a Web Service

So, the client-centric programming model requires a high level of Javascript expertise and atleast one team member should posses the knowledge of security issues of a web application.

In the example given below, we will add a new web service called myservice.asmx. this web service takes the string as input and returns the same. Note that in every client-centric application, a web service has to be used to retrieve the data from the server. As the given example is only for demonstration purposes, the input and returning value is the same and the example is straight forward. As the programs become sophisticated the input and return values will be varied.

In  the below code, we have used namespace System.Web.Script.Services namespace, which 
is part of the core ASP.NET AJAX framework.

Note that the two new attributes, [ScriptService],   [ScriptMethod]. The attribute [ScriptService] is the attribute of the class myservice and [ScriptMethod] is the attribute of the web method GetData(). These attributes are parsed by the ASP.NET AJAX framework and is used to determine what portions of the service are exposed in the JavaScript proxies.

Next we add a new web form called client-centricexample.aspx. the first step is to include ScriptManager control. Next, we declare a service reference to the local web service myService.asmx.  In the web form, we use two regular Html elements two textbox controls and one button. Whenever user clicks on the button in the page, the GetResult() javascript function is called. In this function we call the web service to display the text enetered by the user in another textbox control. In the statement, myService.GetData(document.form1.Text1.value,onComplete); 

The first  parameter is the data entered in the first textbox control and the second parameter is the name

of the callback function onComplete that is  called when the method returns succesfully. When the call return is completed, the changes to be made in the user interface is mentioned here.

In the statement document.form1.Text2.value = result; 

the control text2 is assigned the result of the web service. So, whenever user click the button, the textbox control is updated dynamically.

WebService/WebMethod code:

<%@ WebService Language="C#" Class="myService" %>

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;

[ScriptService]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class myService : System.Web.Services.WebService
{

    [ScriptMethod]
    [WebMethod]

public string GetData(string myString)
    {
        return myString;
    }
}

HTML code:

<form id="form1" runat="server">

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
    <asp:ServiceReference Path="myService.asmx" />
    </Services>
    </asp:ScriptManager>

<input type=text id=Text1 name=Text1 /> 
<input type=text id=Text2 name=Text2 />    
<input type=button id="btnGet" value="Getdata" onclick="GetResult();" />

JavaScript code:

<script type="text/javascript">

function GetResult()
{
      myService.GetData(document.form1.Text1.value,onComplete);
}

function onComplete(result)
{
    document.form1.Text2.value = result;
}

</script>
</form>

February 20, 2008

Free software from Microsoft !

Back in 1995-97 i was indirectly involved with a product which was a successor to Clipper. During a freewheeling discussion session, i suggested that the product competing with VB and Delphi, be given free of cost to all universities. The idea was not accepted. Today i feel somewhat vindicated. When you cannot sell something to someone, you simply give it away, provided the manufacturing (here copying) costs are negligible.

Microsoft today announced, Free software tools to Universities and schools in an effort to kick start innovation based on its windows platform and to promote more usage. All universities are pitching in for Linux and IBM's eclipse as they are open source and free. This move is seen as a strategy to keep open source at bay.

This offer will include Visual Studio the suite - which includes VB, ASP, C# and C++. With this students of colleges and Universities can learn all the tools at college level and be better prepared when they step out for entering the Job market.

Microsoft has sought to plug one easy entry point for free open source software. While, this offer does not include - open source it includes only free tools.

Twitter Updates

    follow me on Twitter
    AddThis Social Bookmark Button
    Blog powered by TypePad
    My Photo