Thursday 24 May, 2007

Working of Global Variable using asp.net

If you need to carry a variable from one page to another, you have a few options with asp.net. The method best suited for you depends on the way the data will be used. The first option is to use session variables. Session variables allow you to keep the information hidden from the user by storing the data in server memory or in an SQL Database (see web.config). To store the value type:
Session("FirstName") = "Todd"
And to retrieve the value, type:
Dim firstname As String = CStr(Session("firstName"))
This variable will be available to you as long as a user's session exists. When their session expires, asp.net will release the data from memory.

You can also accomplish the same task by carrying the value in the URL. This is generally not recommended for user information as it can be seen by the user and easily hacked. However it is recommended in cases where you want a user to be able to link to a specific instance of your asp.net page (i.e. having an articleID on a generic page to display articles).
Dim articleid As Integer = CInt(Request.QueryString("articleid"))
If you only need to retain a variable when posting a page back to itself, you should use the viewstate. It works similarly to a hidden input field in html by placing the value in html code that is not displayed. However, items in the viewstate are encoded so that they cannot be easily deciphered by users. Syntax is similar to sessions, to place in viewstate:
viewstate("FirstName") = "Todd"
To get from viewstate:
Dim fname As String = CStr(viewstate("FirstName"))
If you would like to have a global variable that is static, for example, an sql connection string, I recommend creating a class, and creating the value as a public property of that class. This way you can return your values as a specific data type to enforce better programming.
Public Class Globals     Public ReadOnly Property connstring() As String         Get             Return "server=WebSqlServer; database=Authors; uid=sa; pwd=abcdefg;"         End Get     End Property End Class	
If you need a dynamic variable that spans across individual user sessions (ie keeping a count of active users on your site), you must store the variable in the application object.
Application("usercount") = CInt(Application("usercount")) + 1

Application Settings using [web.config]

The web.config file associated with asp.net projects acts as an application wide variable container. It is an XML file with specific elements that describe how application wide events such as authentication, debugging, and sessions should be handled. You can also place your own static variables here and access them throughout your code (However, I recommend creating a class to do this. Read Global Variables for an explanation.) Below is a complete web.config file from an asp.net project, and below that you'll find a breakdown of what each section means.
 
<?xml version="1.0" encoding="utf-8" ?> <configuration>        <system.web>      <!--  DYNAMIC DEBUG COMPILATION           Set compilation debug="true" to insert debugging symbols (.pdb information)           into the compiled page. Because this creates a larger file that executes           more slowly, you should set this value to true only when debugging and to           false at all other times. For more information, refer to the documentation about           debugging ASP.NET files.     -->     <compilation defaultLanguage="vb" debug="true" />      <!--  CUSTOM ERROR MESSAGES           Set customErrors mode="On" or "RemoteOnly" to enable custom error messages, "Off" to disable.            Add <error> tags for each of the errors you want to handle.     -->     <customErrors mode="RemoteOnly" />      <!--  AUTHENTICATION            This section sets the authentication policies of the application. Possible modes are "Windows",            "Forms", "Passport" and "None"     -->     <authentication mode="Windows" />        <!--  AUTHORIZATION            This section sets the authorization policies of the application. You can allow or deny access           to application resources by user or role. Wildcards: "*" mean everyone, "?" means anonymous            (unauthenticated) users.     -->     <authorization>         <allow users="*" /> <!-- Allow all users -->              <!--  <allow     users="[comma separated list of users]"                              roles="[comma separated list of roles]"/>                   <deny      users="[comma separated list of users]"                              roles="[comma separated list of roles]"/>             -->     </authorization>      <!--  APPLICATION-LEVEL TRACE LOGGING           Application-level tracing enables trace log output for every page within an application.            Set trace enabled="true" to enable application trace logging.  If pageOutput="true", the           trace information will be displayed at the bottom of each page.  Otherwise, you can view the            application trace log by browsing the "trace.axd" page from your web application           root.      -->     <trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" />       <!--  SESSION STATE SETTINGS           By default ASP.NET uses cookies to identify which requests belong to a particular session.            If cookies are not available, a session can be tracked by adding a session identifier to the URL.            To disable cookies, set sessionState cookieless="true".     -->     <sessionState              mode="InProc"             stateConnectionString="tcpip=127.0.0.1:42424"             sqlConnectionString="data source=127.0.0.1;user id=sa;password="             cookieless="false"              timeout="20"      />      <!--  GLOBALIZATION           This section sets the globalization settings of the application.      -->     <globalization requestEncoding="utf-8" responseEncoding="utf-8" />       </system.web>  </configuration>

 
<compilation defaultLanguage="vb" debug="true" />
defaultLanguage="vb": This specifies the default code language.
debug="true": This specifies that the application should be run in debug mode. If set to false it will disable Debug class members, ignore breakpoints, and it will not place the .pdb file in the bin folder used for debugging. This should match the build option you have set in the Visual Studio environment. Changing one does not automatically change the other.


 
<customErrors mode="RemoteOnly" />
This specifies how HTTP response errors should be handled. If set to "Off" they will not be handled and generic error messages will be displayed to the user. If set to "On" you should add nodes in the following manner to redirect based on the HTTP error:
      <customErrors defaultRedirect="Error.htm"                     mode="RemoteOnly">          <error statusCode="404"                 redirect="notfound.htm"/>       </customErrors> 
If the status code of the current error is not found in one of the error nodes, it will redirect to Error.htm.


 
<authentication mode="Windows" />
This will set the authentication mode for the application. For further information, please read Authentication and Authorization.


 
<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" />
If tracing is enabled in the web.config file (set enabled="true" pageOutput="true") detailed information about the life of the page will be displayed at the end of every page. This can be helpful for debugging. If you set pageOutput="false" a trace.axd file will be creating in your applications root folder and trace information will be stored there. If pageOutput is set to false, the requestLimit attribute will designate the number of requests to write to the page log. Setting localonly="true" will allow you to view the trace file from a remote computer. Tracemode has two valid values: SortByTime and SortByCategory. These define how the trace information should be displayed.


 
    <sessionState              mode="InProc"             stateConnectionString="tcpip=127.0.0.1:42424"             sqlConnectionString="data source=127.0.0.1;user id=sa;password="             cookieless="false"              timeout="20"      /> 
Asp.net supports three methods of saving session information: In-process (on the server hosting the application), a state server (on a remote server), or in an sql database. If your application will be hosted among multiple servers, you will not be able to use in-process because page requests from the same user may be handled by different servers. To use these methods set mode="InProc", "StateServer", or "SQLServer" respecively. If you use State server you will need to specify stateConnectionString. If you use SQLServer you will need to specify sqlConnectionString. By default asp.net will place a cookie on the client's computer to associate that user with their particular session. If you need to avoid using cookies, you can set cookieless="true", however, this will place a lengthy string in the url to retain the user's identification. The timeout attribute sets the length in minutes before a session will expire.

ASP.NET Application Level Settings with [Global.asax]

The global.asax file is used to handle application wide events. Below you will see a sample global.asax file along with comments about what each section is used for.

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the application is started
' This Sub is called when an application begins. An application begins when
' any resource in the application is requested. You could use this sub to
' create an application wide variable such as a counter by typing the line
' below:
Application("CurrentUsers") = 0
End Sub

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the session is started
' Each time a new user requests a page, a new session is started
' You would use the sub to increment the CurrentUser count
Application("CurrentUsers")= cint(appication("CurrentUsers")) + 1
End Sub

Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
' Fires at the beginning of each request
' This sub is called any time a browser request a page in the application
End Sub

Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
' Fires upon attempting to authenticate the user
End Sub

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Fires when an error occurs
' You can use this sub to handle errors on an application wide basis
' instead of using the web.config. This sub does not always want to fire,
' so I have found that adding "Handles Mybase.Error" with fix this.
' Follow the example below to send an email and redirect to a generic page
' on errors (note: you must import the System.web.mail namespace)
Dim objErr As Exception = Server.GetLastError().GetBaseException()
Dim err As String = ""
err = err & "Error in:" & Request.Url.ToString() & vbCrLf
err = err & "Error Message:" & objErr.Message.ToString () & vbCrLf
err = err & "Stack Trace:" & objErr.StackTrace.ToString() & vbCrLf
Server.ClearError()
Dim mailMsg As New MailMessage()
mailMsg.From = ""
mailMsg.To = AddressEmailIsGoingTo
mailMsg.Subject = "Error in Application"
mailMsg.Body = err
SmtpMail.Send(mailMsg)
Server.Transfer(" error.aspx")
End Sub

Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the session ends
' When a user's session expires, this sub is called
Application("CurrentUsers")= cint(appication("CurrentUsers")) - 1
End Sub

Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the application ends
' When there are no more active sessions, the application will terminate
Application("CurrentUsers") = Nothing
End Sub


--
Prakash Samariya (IT Professional, HDSE)
Mob: 9879074678 Res: +91-79-32924610
http://ps-india.blogspot.com/
http://psamariya.googlepages.com/
Below Nelson's School, Opp SBI, Punit Ahram Road, Maninagar, Ahmedabad - 380008, Gujarat, India.

Hits4Pay