Infolink

 

Search This Blog

Aug 30, 2012

ASP.Net Repeater dynamically using C# code

ASP.Net Repeater Databound Control can be generated dynamically using C# code. You can render the data items in dynamically generated Repeater Control. ASP.Net Panel Control can be used to add Repeater Control dynamically inside it as a child control. Method of database connectivity and Databinding using DataSource object of Repeater Control is same as we discussed in the previous article about ASP.Net Repeater Control Databinding using DataSource. While creating a dynamic Repeater control, you also have to generate its ItemTemplate, SeparatorTemplate and HeaderTemplate dynamically to display the data items retrieved from the database. In C# code behind use the DataSource object to bind the data with dynamic Repeater Control and add it as a child control of ASP.Net Panel to render all stuff on the web page.

HTML Code to Generate ASP.Net Repeater Control Dynamically

<asp:Panel ID="Panel1" runat="server">  
</asp:Panel> 

C# Code to Generate ASP.Net Repeater Control Dynamically


// Repeater Control Databinding using Datasource  
Repeater Repeater1 = new Repeater();  
Repeater1.DataSource = myDataSet;  
Repeater1.DataBind();  
  
foreach (RepeaterItem repeatItem in Repeater1.Items)  
{  
    // if condition to add HeaderTemplate Dynamically only Once  
    if (repeatItem.ItemIndex == 0)  
    {  
        RepeaterItem headerItem = new RepeaterItem(repeatItem.ItemIndex, ListItemType.Header);  
        HtmlGenericControl hTag = new HtmlGenericControl("h4");  
        hTag.InnerHtml = "Employee Names";  
        repeatItem.Controls.Add(hTag);  
    }  
  
    // Add ItemTemplate DataItems Dynamically  
    RepeaterItem repeaterItem = new RepeaterItem(repeatItem.ItemIndex, ListItemType.Item);  
    Label lbl = new Label();  
    lbl.Text = string.Format("{0} {1} <br />", myDataSet.Tables[0].Rows[ repeatItem.ItemIndex ]

    [ "FirstName" ], myDataSet.Tables[0].Rows[ repeatItem.ItemIndex ][ "LastName" ]);  
    repeatItem.Controls.Add(lbl);  
  
    // Add SeparatorTemplate Dynamically  
    repeaterItem = new RepeaterItem(repeatItem.ItemIndex, ListItemType.Separator);  
    LiteralControl ltrlHR = new LiteralControl();  
    ltrlHR.Text = "<hr />";  
    repeatItem.Controls.Add(ltrlHR);  
}  
  
// Add Repeater Control as Child Control  
// of Panel Control  
Panel1.Controls.Add(Repeater1);


Aug 28, 2012

General Page Life-Cycle Stages

When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering.


In general terms, the page goes through the stages outlined in the following :

1 Page request   : The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.
 

2 Start :  In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property.

3  Initialization : During page initialization, controls on the page are available and each control's UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.
4  Load : During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

5  Validation : During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

6 Postback event handling  : if the request is a postback, any event handlers are called.

 7 Rendering : Before rendering, view state is saved for the page and all controls. During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page's Response property.

8  Unload :  Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed.

Aug 26, 2012

ASP.NET GridView UI using jQuery

Set up an ASP.NET GridView as you usually do, binding it to a datasource. For demonstration purposes, here’s some sample markup where I am using the Northwind database and a GridView bound to the SQLDataSource to pull data from the database.
<form id="form1" runat="server">
<div>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
        SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City] FROM [Customers]">
    </asp:SqlDataSource>   
    <br />          
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"
        DataSourceID="SqlDataSource1" AllowPaging="False" AllowSorting="True" >
        <Columns>                          
            <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />
            <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
            <asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />
            <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
            <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
        </Columns>
    </asp:GridView>
</div>
</form>
The <connectionStrings> element in the web.config will look similar to the following:
      <connectionStrings>
            <add name="NorthwindConnectionString" connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
      </connectionStrings>
Note: In most of the tips shown here, I am using a complex jQuery row ‘filter’ suggested by Karl Swedberg to a user in a jQuery forum. This filter is required due to the fact that a GridView does not render (accessibility tags) a <thead> and a <tfoot> by default(read this article of mine to learn how to make the GridView generate a <thead>). For the header, the GridView generates <th>’s inside <tr>. Similarly for the footer, the GridView generates a <table> inside a <tr> and so on. Hence it is required to use additional filters to exclude header and footer rows while adding UI effects on the GridView. These tips have been tried out on a GridView where paging is not enabled. When the paging is enabled, the pager however gets highlighted. I am still working on a solution to prevent the UI effects from being applied on the pager. I will update this article, once I find a solution. If you have a solution that works cross browser, please share it with me.
 
1. Highlight an ASP.NET GridView row by clicking on it
 
This tip lets you highlight a row when you click anywhere on the row. Clicking back on a highlighted row, removes the highlight.
<head id="Head1" runat="server">
<title>Highlight Row on Click</title>
 
<script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>
 
<script type="text/javascript">
    $(document).ready(function() {
        $("tr").filter(function() {
            return $('td', this).length && !$('table', this).length
        }).click(function() {
            $(this).toggleClass('currRow');
        });
    });
</script>
 
<style type="text/css">
    .currRow
    {
        background-color:Gray;
        cursor:pointer;
    }   
</style>
 
</head>
After applying the filter on the rows (to prevent the user from highlighting the Header and Footer row), we use the toggleClass to highlight/remove highlight on the row.
Output:
 
 2. Remove/Hide the Highlighted rows of an ASP.NET GridView  
 
If you want to remove/hide the highlighted rows from the GridView, then here’s how to do so. I have added a HTML button control (Button1) to the form
<input id="Button1" type="button" value="Remove Rows" />
The jQuery is as shown below:
<head id="Head1" runat="server">
    <title>Hide Highlighted Rows>/title>
 
    <script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>
   
    <script type="text/javascript">
        $(document).ready(function() {
            $("tr").filter(function() {
                return $('td', this).length && !$('table', this).length
            }).click(function() {
                $(this).toggleClass('currRow');
            });
 
 
            $("#Button1").click(function() {               
                var hideRows = $("tr").hasClass("currRow");
                if (hideRows == true) {                   
                    $("tr.currRow").remove();
                }
            });
        });
       
    </script>
   
   
    <style type="text/css">
        .currRow
        {
            background-color:Gray;
            cursor:pointer;
        }   
    </style>
   
</head>
Here the user first highlights the rows and then clicks on the ‘Remove Rows’ button to remove the highlighted rows
 
 3. Remove/Hide ASP.NET GridView Rows on Mouse Click
In our previous sample, we were following a two step process of first highlighting multiple rows and then removing them. Let’s say if we want to remove the rows as the user clicks on them, then follow this approach:
    <script type="text/javascript">
        $(document).ready(function() {
                $("tr").filter(function() {
                    return $('td', this).length && !$('table', this).length
                }).click(function() {
                    $(this).remove();
                });
        });       
    </script>
 
4. Highlight an ASP.NET GridView row on Mouse Hover  
 
In case you do not want to define a separate style for the row and want to highlight a row on mouse over (instead of the click), follow this tip:
<head id="Head1" runat="server">
    <title>Highlight Row on Hover</title>
 
    <script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>
   
    <script type="text/javascript">
        $(document).ready(function() {
            $("tr").filter(function() {
                return $('td', this).length && !$('table', this).length
            }).css({ background: "ffffff" }).hover(
                function() { $(this).css({ background: "#C1DAD7" }); },
                function() { $(this).css({ background: "#ffffff" }); }
                );
        });
    </script>
   
</head>
Output:
 
5. Drag and Drop Rows of an ASP.NET GridView
This tip comes very handy when you are presenting a set of data in a GridView and want to rearrange rows at runtime. I am using the Table Drag and Drop Plugin for this example and it’s as simple as calling tableDnD() on the table. This plugin enables drag/drop on a table.
<head runat="server">
    <title>Drag Drop Rows</title>
 
    <script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.tablednd_0_5.js" type="text/javascript"></script>
   
    <script type="text/javascript">
        $(document).ready(function() {
            $("#GridView1").tableDnD();
        });
</script>
 
</head>
Output:
Before Drag
 
After Drop - dragging row with Customer ID ‘ANATR’ below ‘BLONP’
 
That’s it for now. We saw some UI tips that can be applied to an ASP.NET GridView using jQuery. Stay tuned to see some more in the forthcoming articles. I am also planning to write an article to store these UI changes when the user paginates through the Grid or a postback occurs. 
 

Hide a Parent Node

I have a TreeView and SiteMapDatasource on my .aspx page. Web.config has siteMapProvider settings and a SiteMap file (Web.sitemap). 

.aspx file:
<asp:TreeView ID="TreeView1" runat="server" AutoGenerateDataBindings="False" DataSourceID="SiteMapDataSource1" ontreenodedatabound="TreeView1_TreeNodeDataBound">
</asp:TreeView>
<br />
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
Above is .aspx file with controls for this example. You should note we have a event handler for OnTreeNodeDataBound event of TreeView.
Web.config:
<siteMap defaultProvider="XmlSiteMapProvider" enabled="true"> <providers> <add name="XmlSiteMapProvider" type="System.Web.XmlSiteMapProvider"
siteMapFile="Web.siteMap" securityTrimmingEnabled="true"/> </providers> </siteMap>
Part of web.config is shown above with SiteMapProvider. Note we have siteMapFile="Web.sitemap"  and securityTrimmingEnabled="true" for Roles to be applied to the sitemap.
Web.SiteMap:
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" > <siteMapNode url="~/Default.aspx" title="Home" description="Home">
<siteMapNode url="~/Level1.aspx" title="Level 1" description="" > <siteMapNode url="~/Page1.aspx" title="Page1" description="" />
<siteMapNode url="~/Page2.aspx" title="Page2" description="" /> </siteMapNode>
<siteMapNode url="~/NoChilde.aspx" title="Level 2" description="" /> <siteMapNode url="~/Level3.aspx" title="Level 3" description="" >
<siteMapNode url="~/Page3.aspx" title="Page3" description="" /> </siteMapNode>
</siteMapNode> </siteMap>
The above sitemap is not very realistic looking but will serve the purpose for our demonstration. We see that siteMapNode "Level 2" does not have any childnode. So we want to hide it and not show in our TreeView. In real case scenario it might have few child nodes with Roles attribute set. If user is not in particular role the SiteMapProvider will hide those node.
Without the code-behind which we are going to see in a moment the TreeView will look like below:



We now want to hide "Level 2" node as it does not have any child node.

.aspx.cs file (code-behind):
protected void TreeView1_TreeNodeDataBound(object sender, TreeNodeEventArgs e) {
SiteMapNode node = (SiteMapNode)e.Node.DataItem;
if(node.HasChildNodes ==false && e.Node.Depth ==1) {
TreeView1.Nodes[0].ChildNodes.Remove(e.Node);

}
}
In the above code what we are doing is first getting the DataItem for the CurrentNode that is being DataBound. For this we have to use SiteMapNode.
1: we check if the node has Child with node.HasChildNodes ==false.
2: "Home" is at Depth 0 while Level 1,2 and 3 are at Depth 1 and Page1,Page2 and so on are at Depth=2. So to make sure that we are not hiding Home or any leaf nodes (page1,Page2 etc) we are checking that depth of current Node is 1.
If the above two conditions are met then we will remove the current node (i.e. e.Node) from TreeView1.
For this we first get the NodesCollection for TreeView1. i.e. TreeView1.Nodes[0], Here 0 is because we have all Nodes under "Home" parent Node.
After that we call the ChildNodes.Remove method to remove the current Node.
That is it. Now if we run the code we will get the following output for TreeView:





ShowStartingNode=False set for SiteMapDataSource:

 If you set the ShowStartingNode=False for SiteMapDataSource then you might want to chage the Depth=0 and also make little change on how to remove node.
The code should look like below:

protected void TreeView1_TreeNodeDataBound(object sender, TreeNodeEventArgs e) {
SiteMapNode node = (SiteMapNode)e.Node.DataItem;
if(node.HasChildNodes ==false && e.Node.Depth ==0) {
TreeView1.Nodes.Remove(e.Node);
}
}
Thats it. Thanks for reading this article.

Improve reference efficiency in JavaScript files inside a web project

In Visual Studio 2010 you can reference other JavaScript files inside current JavaScript file like the following, to get the IntelliSense.

/// <reference path="YourScript.js" />

What if you have many JavaScript files and you have to reference many project wide JavaScript files inside each file?  You can put the following block in each of the JavaScript files that need the reference like following:

/// <reference path="YourScript1.js" />
/// <reference path="YourScript2.js" />
/// <reference path="YourScript3.js" />
/// <reference path="YourScript4.js" />


But this would not be efficient especially some referencing file name is going to change, such as when JQuery library version changes.  The trick is to create a project wide reference JavaScript file, and explicitly reference this file from other JavaScript files.  For example, we can create a file called reference.js which contains the above code.  Then for other JavaScript files, we can reference it by dragging and drop the reference.js file into the JavaScript editor, which will generate the following:

/// <reference path="Scripts/AppJsReference.js" />

Basically, Visual Studio 2010 recursively check the references included in the referenced JavaScript files to find the current JavaScript file's references.  I hope this can ease some pain in the development.

Aug 24, 2012

Levels Of Abstraction In An MVC View

Working on a dashboard I came across a view arranged like the following diagram:




The scenario is simplified because there is more to do inside of one block than just @SomeOutput, but focus on the structure of the view. I needed to add some more behaviors to the dashboard using CSS and script code, but it only took a few minutes to achieve frustration. Sometimes the view would delegate to a partial view for a specific section of the dashboard, and sometimes the view would inline all the markup and code for a section. Then there was also the odd case of having one partial view responsible for two entire sections of the dashboard, which threw me off entirely. Being new to the code it took some time to figure out how the pieces worked together to produce the page.

Before I started making my own changes, I did a little refactoring to structure the view like so ...



... and then development life was easier. The mental model of how to map from implementation to output was simplified, and I instantly knew where to go to make different changes.

There are a number of ways you could spin this story. You could argue how the original view violated the single responsibility principle since it was taking responsibility for providing the structure of the dashboard and rendering some of the details. I'd agree with this argument. You could also argue the original view violated the single level of abstraction principle, and I'd agree with that argument, too.

In the end I simply liked the solution better because it seemed simple and symmetrical. Not many people talk about the aesthetic qualities of balance and symmetry in code, but I think it is a sign of craftsmanship that can benefit software by making code easier to understand and maintain. I bet the dashboard changes again in 3 months, and hopefully the next person has an easier time making those changes.

 

Aug 20, 2012

google-site-verification: google67603bc9a438546b.html

Aug 15, 2012

Session Object

Session Object (IIS)
You can use the Session object to store information needed for a particular user session. Variables stored in the Session object are not discarded when the user jumps between pages in the application; instead, these variables persist for the entire user session.
The Web server automatically creates a Session object when a Web page from the application is requested by a user who does not already have a session. The server destroys the Session object when the session expires or is abandoned.
One common use for the Session object is to store user preferences. For example, if a user indicates that they prefer not to view graphics, you could store that information in the Session object. For more information about using the Session object, see Managing Sessions in the Active Server Pages & Web Application Guide section.
Note:
Session state is only maintained for browsers that support cookies. 

Methods 
The Session object defines the following methods.
Method
Description
This method destroys a Session object and releases its resources.
This method deletes an item from the Contents collection.
This method deletes all items from the Contents collection.

Abandon
The Abandon method destroys a user session.
        Note: When this method is called, the current Session object is not deleted until all of the script on the current page have been processed. This means that it is possible to access session variables on the same page as the call to Abandon, but not from another Web page.

      Syntax

Session.Abandon

    Examples

        File1.asp:
<%
Session("name")="abcd"
Session.Abandon
Response.Write(Session("name"))
%>

Output:

abcd
        File2.asp:
<%
Response.Write(Session("name"))
%>

Output:

(none)

The Session object defines the following properties.
Property
Description
Returns the session identification for this user.
Contains the objects created by using the <OBJECT> tag and given session scope.
The time-out period for the session state for this application, in minutes.

        Events 

  The Session object defines the following events.

Event
Description
Occurs when a session is abandoned or times out.
Occurs when the server creates a  session.

<% 
Session("username") = "Janine"
Session("age") = 24
%>


However, if you store an object in the Session object and use VBScript as your primary scripting language, you must use the Set keyword, as illustrated in the following script.
VBScript
<% Set Session("Obj1") = Server.CreateObject("MyComponent.class1") %>
You can then use the methods and properties exposed by MyComponent.class1 on subsequent Web pages, by using the following:
VBScript

<% Session("StoredArray")(3) = "new value" %>
The preceding script does not work because the Session object is implemented as a collection. The array element StoredArray(3) does not receive the new value. Instead, the value is indexed into the collection, overwriting any information stored at that location.
It is strongly recommended that if you store an array in the Session object, you retrieve a copy of the array before retrieving or changing any of the elements of the array. When you are finished using the array, you should store the array in the Session object again, so that any changes you made are saved, as demonstrated in the following example:
VBScript 

 --- File1.asp --- 

<%
'Creating and initializing the array
Dim MyArray()
Redim MyArray(5)
MyArray(0) = "hello"
MyArray(1) = "some other string"

'Storing the array in the Session object.
Session("StoredArray") = MyArray

Response.Redirect("file2.asp")
%>

--- File2.asp ---
<%
'Retrieving the array from the Session Object
'and modifying its second element.
LocalArray = Session("StoredArray")
LocalArray(1) = " there"

'Printing out the string "hello there."
Response.Write(LocalArray(0)&LocalArray(1))

'Re-storing the array in the Session object.
'This overwrites the values in StoredArray with the new values.
Session("StoredArray") = LocalArray
%>

Example Code 

The following code assigns the string "MyName" to a session variable named name, assigns a value to a session variable named year, and assigns an instance of the some.Obj component to a variable named myObj:

VBScript

<%
Session("name") = "MyName" 
Session("year") = 96 
Set Session("myObj") = Server.CreateObject("someObj") 
%>

Session_OnStart Event
The Session_OnStart event occurs when the server creates a session. The server processes this script before executing the requested page. It is a good practice to set any session-wide variables with the Session_OnStart event because the variables would be set before any pages are accessed. All the built-in objects (Application Object, ObjectContext Object, Request Object, Response Object, Server Object, and Session Object) are available and can be referenced in the Session_OnStart event script.
<SCRIPT LANGUAGE=ScriptLanguage RUNAT=Server>
Sub Session_OnStart
. . .
End Sub
</SCRIPT>
http://i.msdn.microsoft.com/Global/Images/clear.gif Parameters 

ScriptLanguage
 
Specifies the scripting language used to write the event script. It can be any supported scripting language, such as VBScript or JScript. If more than one event uses the same scripting language, they can be combined under a single set of <SCRIPT> tags.

Remarks 

You should note that any Session_OnStart event script that follows a call to the Response.Redirect method is not executed. For this reason, you should call the Redirect method last in your event script, as shown in the following example.

Example Code 

Although the Session object persists if the Session_OnStart event contains a call to the Response.Redirect or Response.End methods, the server stops processing the script in both the Global.asa file and in the file that triggered the Session_OnStart event.
You can call the Response.Redirect method in the Session_OnStart event, for example, to ensure that users always start a session at a particular Web page. When the user initially opens the application, the server creates a session for that user and processes the Session_OnStart event script. You can include script in this event to check whether the page opened by the user is the starting page and, if not, direct the user to the starting page by calling the Response.Redirect method, as shown in the following example.
Note:
This example only works for browsers that support cookies. Because a browser that does not support cookies does not return the SessionID cookie, the server creates a new session each time the user requests a page. Thus, for each request, the server processes the Session_OnStart script and redirects the user to the starting page. If you use the following script, it is recommended that you put a notice on your starting page to inform users that the site requires a browser that is enabled to use cookies.

<SCRIPT RUNAT=Server Language=VBScript>
Sub Session_OnStart
  'Make sure that new users start on the correct
  'page of the ASP application.

  'Replace the value given to startPage below
  'with the virtual path to your application's
  'start page.

  startPage = "file1.asp"
  currentPage = Request.ServerVariables("SCRIPT_NAME")

  'Do a case-insensitive comparison, and if they
  'don't match, send the user to the start page.

  If strcomp(currentPage,startPage,1) then
    Response.Redirect(startPage)
  End If
End Sub
</SCRIPT>
Session_OnEnd Event

The Session_OnEnd event occurs when a session is abandoned or times out. Of the Server built-in objects, only the Application Object, Server Object, and Session Object objects are available.

<SCRIPT LANGUAGE=ScriptLanguage RUNAT=Server>
Sub Session_OnEnd. . . End Sub
</SCRIPT>
http://i.msdn.microsoft.com/Global/Images/clear.gif Parameters
ScriptLanguage
Specifies the scripting language used to write the event script. It may be any supported scripting language, such as VBScript or JScript. If more than one event uses the same scripting language, they can be combined under a single set of <SCRIPT> tags.
Application Object (IIS)

You can use the Application object to share information among all users of a given application. An ASP-based application is defined as all the .asp files in a virtual directory and its subdirectories. Because the Application object can be shared by more than one user, there are Lock and Unlock methods to ensure that multiple users do not try to alter a property simultaneously.

Methods
The Application object defines the following methods.
Method
Description
Deletes an item from the Application object's Contents collection.
Deletes all items from the Application object's Contents collection.
Prevents other clients from modifying Application object properties.
Allows other clients to modify Application object properties

Properties 
The Application object defines the following properties.
Property
Description
Contains all of the items that have been added to the application through script commands.
Contains all of the objects added to the session with the <OBJECT> tag

Events 
The Application object defines the following events.
Event
Description
Occurs when the application quits, after the Session_OnEnd event. Only the Application Object and Server Object built-in objects are available.
Occurs before the first new session is created, that is, before the Session_OnStart event. Only the Application Object and Server Object built-in objects are available. Referencing the Session Object, Request Object, or Response Object objects in the Application_OnStart event script causes an error

Remarks 
You can store values in the Application Collections. Information stored in the Application collections is available throughout the application and has application scope. The following script demonstrates storage of two types of variables.
VBScript

<%
Application("greeting") = "Welcome to My Web World!"
Application("num") = 25
%>
Each of these variables are members of the Application.Contents Collection.
You can also assign a component instance to a variable that has application scope. If you assign a component instance to a variable with the Server.CreateObject method, the variable will be a member of the Application.Contents collection. If the variable is assigned with the <OBJECT> tag, the variable will be a member of the Application.StaticObjects Collection.
You should be careful about assigning component instances to variables with application scope because some components are not designed to be given application scope. For more information, see the Platform Software Development Kit (SDK).
If you assign a component instance to a variable in the Application.Contents Collection and use Microsoft ® Visual Basic ® Scripting Edition (VBScript) as your primary scripting language, you must use the Set keyword, as illustrated in the following script.
VBScript

<% Set Application("Obj1") = Server.CreateObject("MyComponent") %>
You can then reference the methods and properties of MyComponent on subsequent Web pages by using the following script:
Another way to create objects with application scope is by using the <OBJECT> tag in the Global.asa file. For more information, see Global.asa Syntax.
If you store an array in an Application object, you should not attempt to alter the elements of the stored array directly. For example, the following script does not work:
VBScript

<% Application("StoredArray")(3) = "new value" %>
The preceding script does not work because the Application object is implemented as a collection. The array element StoredArray(3) does not receive the new value. Instead, the value is included in the Application object collection and overwrites any information that had previously been stored at that location.
It is strongly recommended that if you store an array in the Application object, you retrieve a copy of the array before retrieving or changing any of the elements of the array. When you are done with the array, you should store the array in the Application object again, so that any changes you made are saved, as shown in the following scripts.
VBScript

--- File1.asp ---
<%
'Creating and initializing the array.
dim MyArray()
Redim MyArray(5)
MyArray(0) = "hello"
MyArray(1) = "some other string"

'Storing the array in the Application object.
Application.Lock
Application("StoredArray") = MyArray
Application.Unlock

Server.Transfer("file2.asp")
%>

--- File2.asp ---
<%
'Retrieving the array from the Application Object
'and modifying its second element.
LocalArray = Application("StoredArray")
LocalArray(1) = " there"

'Printing out the string "hello there."
Response.Write(LocalArray(0)&LocalArray(1))

'Re-storing the array in the Application object.
'This overwrites the values in StoredArray with the new values.
Application.Lock
Application("StoredArray") = LocalArray
Application.Unlock
%>
http://i.msdn.microsoft.com/Global/Images/clear.gif Example Code
The following example uses the application variable NumVisits to store the number of times that a particular page has been accessed. The Lock method is called to ensure that only the current client can access or alter NumVisits. Calling the Unlock method then enables other users to access the Application object.
VBScript

<%
Application.Lock
Application("NumVisits") = Application("NumVisits") + 1
Application.Unlock
%> 

This application page has been visited 
<%= Application("NumVisits") %> times!

Application.Contents.Remove Method
The Contents.Remove method for ASP deletes an item from the Application.Contents collection.
Contents.Remove(
   id
)
http://i.msdn.microsoft.com/Global/Images/clear.gif Parameters
id
A string or an integer identifying the item in the colleciton to be removed. If id is a string, the method searches the contents collection for an item with that name and removes it. If id is an integer, the method counts that number of items from the start of the collection and removes the corresponding item.

http://i.msdn.microsoft.com/Global/Images/clear.gif Return Values
This method has no return values.
http://i.msdn.microsoft.com/Global/Images/clear.gif Remarks
Although ASP collections are similar to the Visual Basic Collection object, there are some differences. ASP collections support the Count property and the Item, Remove, and RemoveAll methods. They do not support the Add method.

Example Code
The following example adds three items to the Application.Contents collection and removes two. At the end of the example, Application(str3) is the first item instead of the third.
VBScript

<%@ Language="VBScript" %>
<%
  Response.Write("<br/>Before Remove<br/>")
  Application.Lock
  Application.Contents.Item("str1") = ("First thing")
  Application.Contents("str2") = ("Second thing")
  Application("str3") = ("Third thing")
  Application.Unlock
  For Each Key in Application.Contents
    Response.Write Key + " = " + Application(Key) + "<br/>"
  Next
  Response.Write("<br/>After Remove<br/>")
  Application.Lock
  Application.Contents.Remove("str1")
  Application.Contents.Remove("str2")
  Application.Unlock
  For Each Key in Application.Contents
    Response.Write Key + " = " + Application(Key) + "<br/>"
  Next
%>

<%@ Language="JScript" %>
<%
  Response.Write("<br/>Before Remove<br/>");
  Application.Lock();
  Application.Contents.Item("str1") = ("First thing");
  Application.Contents("str2") = ("Second thing");
  Application("str3") = ("Third thing");
  Application.Unlock();
  e = new Enumerator(Application.Contents);
  for (; !e.atEnd(); e.moveNext()) {
    Response.Write(e.item() + " = " + Application(e.item()) + "<br/>"); 
  }
  Response.Write("<br/>After Remove<br/>");
  Application.Lock();
  Application.Contents.Remove("str1");
  Application.Contents.Remove("str2");
  Application.Unlock();
  e = new Enumerator(Application.Contents);
  for (; !e.atEnd(); e.moveNext()) {
    Response.Write(e.item() + " = " + Application(e.item()) + "<br/>"); 
  }
%>

Application.Contents.RemoveAll Method
The Contents.RemoveAll method removes all items that have been added to the Application.Contents collection.
Contents.RemoveAll(
)
http://i.msdn.microsoft.com/Global/Images/clear.gif Parameters
This method has no parameters.
http://i.msdn.microsoft.com/Global/Images/clear.gif Return Values
This method has no return values.
Application.Lock Method
The Lock method blocks other clients from modifying the variables stored in the Application object, ensuring that only one client at a time can alter or access the Application variables. If you do not call the Application.Unlock method explicitly, the server unlocks the locked Application object when the .asp file ends or times out.
Lock(
)
http://i.msdn.microsoft.com/Global/Images/clear.gif Parameters
This method has no parameters.
http://i.msdn.microsoft.com/Global/Images/clear.gif Return Values
This method has no return values.
http://i.msdn.microsoft.com/Global/Images/clear.gif Remarks
A lock on the Application object persists for a very short time because the application object is unlocked when the page completes processing or times out.
If one page locks the application object and a second page tries to do the same while the first page still has it locked, the second page will wait for the first to finish, or until the Server.ScriptTimeout limit is reached. If the Server.ScriptTimeout limit is reached, the following ASP error is returned which cannot be captured:

To reduce the possibility of having an ASP page time out, write a COM+ object that uses the COM+ ObjectContext object to update the Application collection, and then call the COM+ object from an ASP page. COM+ objects execute slightly faster than ASP pages. For more information, see Using the COM+ ObjectContext Object to Access the ASP Built-in Objects
NoteNote:
A page does not need to lock the application object to edit the application collection. If one page tries to edit the application collection without locking and a second page also tries to edit the collection, no error is sent by IIS and the Application object ends up in an inconsistent state.
Applies To
http://i.msdn.microsoft.com/Global/Images/clear.gif Example Code
In the following example, the Lock method prevents more than one client at a time from accessing the variable NumVisits. If the application had not been locked, two clients could simultaneously try to increment the variable NumVisits.
VBScript

<%@ Language="VBScript" %>
<%
Application.Lock 
Application("NumVisits") = Application("NumVisits") + 1 
Application("datLastVisited") = Now() 
Application.Unlock 
%> 

This application page has been visited 
<%= Application("NumVisits") %>  times

Application.Unlock Method
The Unlock method enables other clients to modify the variables stored in the Application object after it has been locked using the Application.Lock method. If you do not call this method explicitly, the Web server unlocks the Application Object when the .asp file ends or times out.
Unlock(
)
http://i.msdn.microsoft.com/Global/Images/clear.gif Parameters
This method has no parameters.
http://i.msdn.microsoft.com/Global/Images/clear.gif Return Values
This method has no return values.
http://i.msdn.microsoft.com/Global/Images/clear.gif Remarks
The application Lock method is cumulative, meaning that if the same script calls Lock several times, it must also call Unlock the same number of times to fully release the application. If this does not occur, the application lock will be held until the script is finished running.
A lock on the Application object persists for a very short time because the application object is unlocked when the page completes processing or times out.
If one page locks the application object and a second page tries to do the same while the first page still has it locked, the second page will wait for the first to finish, or until the Server.ScriptTimeout limit is reached. If the Server.ScriptTimeout limit is reached, the following ASP error is returned which cannot be captured:

To reduce the possibility of having an ASP page time out, write a COM+ object that uses the COM+ ObjectContext object to update the Application collection, and then call the COM+ object from an ASP page. COM+ objects execute slightly faster than ASP pages. For more information, see Using the COM+ ObjectContext Object to Access the ASP Built-in Objects
NoteNote:
A page does not need to lock the application object to edit the application collection. If one page tries to edit the application collection without locking and a second page also tries to edit the collection, no error is sent by IIS and the Application object ends up in an inconsistent state.
Applies To
http://i.msdn.microsoft.com/Global/Images/clear.gif Example Code
In the following example, the Unlock method releases the locked object so that the next client can increment NumVisits.
VBScript

<%@ Language="VBScript" %>
<% 
Application.Lock
Application("NumVisits") = Application("NumVisits") + 1
Application("datLastVisited") = Now() 

Application.Unlock
%> 

This application page has been visited 
<%= Application("NumVisits") %>  times!

Application.Contents Collection
The Contents collection contains all the items that have been added to the application through a script command. You can use the Contents collection to obtain a list of items that have been given application scope or to specify a particular item to be the target of an operation. You can also remove items from the collection by using the Remove and RemoveAll methods.
http://i.msdn.microsoft.com/Global/Images/clear.gif Syntax
Application.Contents( Key)
http://i.msdn.microsoft.com/Global/Images/clear.gif Parameters
Key
Specifies the name of the item to retrieve.
http://i.msdn.microsoft.com/Global/Images/clear.gif Methods
Deletes an item from the collection.
Deletes all items from the collection.
http://i.msdn.microsoft.com/Global/Images/clear.gif Remarks
The Contents collection contains those items that have been declared at the application level without using the <OBJECT> tags. This would include both objects created by using Server.CreateObject, as well as scalar variables established through an Application declaration. In the following script, for example, both "strHello" and objCustom would be members of the Contents collection.

<% 
 Application("strHello") = "Hello"
 Set Application("objCustom") = Server.CreateObject("MyComponent") %>


The Contents collection supports For...Each and For...Next iteration. The following script illustrates each of these methods of iterating through the Contents collection:

<%
  Application("strText1") = "1234567890"
  Application("strText2") = "ABCDEFGHIJ"
  Application("strText3") = "A1B2C3D4E5"
%>

<%
  For Each Key in Application.Contents
    Response.Write Key + " = " + Application(Key) + "<BR>"
  Next
%>

<%
  For intItem = 1 to Application.Contents.Count
    Response.Write CStr(intItem) + " = "  
    Response.Write Application.Contents(intItem) + "<BR>"
  Next
%>

Application.StaticObjects Collection
The StaticObjects collection contains all of the objects created by using the <OBJECT> tags within the scope of the Application object. You can use the collection to determine the value of a specific property for an object or to iterate through the collection and retrieve all properties for all static objects.
http://i.msdn.microsoft.com/Global/Images/clear.gif Syntax
Application.StaticObjects( Key)
http://i.msdn.microsoft.com/Global/Images/clear.gif Parameters
Key
Specifies the name of the item to retrieve.
http://i.msdn.microsoft.com/Global/Images/clear.gif Remarks
You can use an iterating control structure to loop through the keys of the StaticObjects collection, as shown in the following example.

<%
  Dim strKey

  For Each strKey In Application.StaticObjects
    Response.Write strKey & " = <i>(object)</i><BR>"
  Next
%>

Application_OnStart Event
The Application_OnStart event occurs before the first new session is created, that is, before the Session_OnStart event. Only the Application Object and Server Object built-in objects are available. Referencing the Session Object, Request Object, or Response Object objects in the Application_OnStart event script causes an error.
<SCRIPT LANGUAGE=ScriptLanguage RUNAT=Server>
Sub Application_OnStart. . . End Sub
</SCRIPT>
http://i.msdn.microsoft.com/Global/Images/clear.gif Parameters
ScriptLanguage
Specifies the scripting language used to write the event script. It may be any supported scripting language, such as VBScript or JScript. If more than one event uses the same scripting language, they can be combined under a single set of <SCRIPT> tags.
http://i.msdn.microsoft.com/Global/Images/clear.gif Example Code

Sub Application_OnStart
  Application("NumberofVisitors") = 0
End Sub

You do not need to use Application.Lock and Application.Unlock methods in the Application_OnStart event, as this event can be called only once, by the first session that starts the application.
Application_OnEnd Event
The Application_OnEnd event occurs when the application quits, after the Session_OnEnd event. Only the Application Object and Server Object built-in objects are available.
<SCRIPT LANGUAGE=ScriptLanguage RUNAT=Server>
Sub Application_OnEnd. . . End Sub
</SCRIPT>
http://i.msdn.microsoft.com/Global/Images/clear.gif Parameters
ScriptLanguage
Specifies the scripting language used to write the event script. It can be any supported scripting language, such as VBScript or JScript. If more than one event uses the same scripting language, they can be combined under a single set of <SCRIPT> tags.
http://i.msdn.microsoft.com/Global/Images/clear.gif Remarks
You cannot call the Server.MapPath method in the Application_OnEnd script. By default, Application_OnEnd runs as the Anonymous User, as defined for the application. In the event that there isn't an Anonymous user, or the Logon for the Anonymous user fails, the OnEnd function will not be called, and an event will be logged.

Examples

Global.asa:
<script language="vbscript" runat="server">

Sub Application_OnEnd()
Application("totvisitors")=Application("visitors")
End Sub

Sub Application_OnStart
Application("visitors")=0
End Sub

Sub Session_OnStart
Application.Lock
Application("visitors")=Application("visitors")+1
Application.UnLock
End Sub

Sub Session_OnEnd
Application.Lock
Application("visitors")=Application("visitors")-1
Application.UnLock
End Sub

</script>
To display the number of current visitors in an ASP file:
<html>
<head>
</head>
<body>
<p>
There are <%response.write(Application("visitors"))%>
online now!
</p>
</body>
</html>

Related Posts Plugin for WordPress, Blogger...