Page V2.0

File Name: WebControl.asp
Class Name: cPage
Overview:
The page object is used to represent a CLASP Page. The page object offers a rich set of functions to facilitate the development of a page. It is also used as a container for all WebControls, ViewState, Script functions, Trace functions, Libraries, Debugging, etc. It is also the responsible for the managment the life cicle of the page (event capturing and notification).



Public Constructors
New cPage

This is part of the CLASP Framework and should not be directly used. The CLASP Framework automatically creates an global instance of this class named Page. You should always use the Page instance.


Public Properties
Control WebControl

Inherits attributes from the WebControl class. For more information go to the WebControl help. This is part of the CLASP Framework and should not be directly used.

Controls ControlsCollection Wrapper to Control.Controls. This collection maintains the hierarchy of controls in the page. This is part of the CLASP Framework and should not be directly used (unless you are a control developer and know what you are doing)
CompressFactor Integer Number of bytes to exeed if you want the viewstate to be compressed. Requires the use of ASPFramework.dll and the zlib.dll.
IsCompressed Boolean Read-Only. True if the Viewstate is compressed.
IsRedirectedPostBack Boolean True if the Page is being loaded as the result of a posback from another page . This value can only be examined before any subsequent postback.
IsPostBack Boolean True if the page is being loaded for the first time is is being loaded as the result of a postback.
Action String Translated to the EventName. (Try to use GetPostBackEvent to return a ClientEvent object is possible)
ActionSource String The CLASP object target of the event. (Try to use GetPostBackEvent to return a ClientEvent object is possible)
ActionSourceInstance String Multiple-interpretation. The purpose of this value is determined by the target of the event.(Try to use GetPostBackEvent to return a ClientEvent object is possible)
ActionXMessage String Multiple-interpretation. The purpose of this value is determined by the target of the event.(Try to use GetPostBackEvent to return a ClientEvent object is possible)
DebugEnabled Boolean If true, then Trace methods will record data and at the end of the page debug information will be displayed.
DebugLevel Int 1-3. 1 Captures the less information whereas 3 captures all debug information.
ViewStateMode Int

[0] ,  [1] , [3]. 0 Stores the viewstate in a hidden form field named "__VIEWSTATE" , 1 stores the viewstate in the session object. Mode 3 uses SQL Server. (VIEW_STATE_MODE_SQL_SERVER ). There are more modes. CLASP uses 1 and 2 natively  unless another one is plugged.

ViewState ViewState Access of an object that supports the viewstate interface. There are currently two objects implemeting this inteface: ASPFramework.ViewState (in ASPFramework.dll) and cASPViewState found in Server_ASPViewState.asp. The former uses a custom code to encode/decode base64 string where as the ASP implementation relies on CAPICOM.
PageFormAction String Can be used to override the default form target page. This will cause the page to be posted to another page.
AutoResetFocus Boolean If true, then the page will render Javascript code to reset the focus to the control that caused the page to be submited, if possible.
AutoResetScrollPosition Boolean If true, then the vertical possition of the browser will be retained in between postbacks.
OnSubmitStatement String Used to specify the name of a Javascript function that will be called before the page is posted back to the server. If the function returns false, then the page will not be posted.
ShowRenderTime Boolean If true then the framework will render the time in ms it took to process the time (from Page.Execute until the page is being destroyed by IIS)
IsTemplatePresent Boolean True if a page template/skin object is present. The developer must set this property to true if control skin functions are present.
IsViewStateLoaded Boolean True if the viewstate was loaded. Used internally or by webcontrols.
IsViewStateSaved Boolean True if the viewstate was already calculated and saved. Used internally or by webcontrols.

Public Methods
(default) Render Renders the control to the page.
GetNextTabIndex Gets the next tab inded. The page object keeps a tabindex counter. Everytime a control asks for the next tab index, the counter increments. This is normally used by control developers, but it can be used directly as well.
GetEventScript(ClientTrigger, ObjectName, EventName, ByVal Instance, ExtraMessage)

Returns  JavaScript code to call the doPostBack javascript function. This is part of the core of CLASP and is how events are sent down to the server. CLASP only understands PostBacks generated by the doPostBack function.

This version of GetEventScript will postback to the same page.

GetEventScriptRedirect(ClientTrigger, ObjectName, EventName, ByVal Instance, ExtraMessage,Action) Same as above but it post back the page the page specified in the <action> parameter. In addition, the IsRedirectedPostback hidden field will be set to 1. The called page can then inspect the Page.IsRedirectedPostback property (only when the page is first rendered) to determined if it was called as a result of a postback from another CLASP page. If so, then the developer can get the event information by checking the ActionXXX properties or by getting a reference to the event object using Page.GetPostBackEvent
GetEventScriptNewWindow(ClientTrigger, ObjectName, EventName, ByVal Instance, ExtraMessage,Action,TargetWindow) Same as above but the page will be oppened in a separate window.
TraceRender(FromStart,ToEnd,varControl) Adds a trace line to the trace reporting the time it took a control to render. The control itself is responsible for capturing the times. If DebugEnabled is set to True then the line will be added and at the end of the page a trace will be rendered.
TraceCall(obj,msg) Same as above, but the purpose is to trace a method call.
TraceMsg(method,msg) Same as above but the purpose is to add a simple message.
TraceImportantCall(obj,msg) Same as above but the message is red-colored.
TraceError(Control,Message,Severity) Adds a line to the Error trace only if Err.Number <> 0. In addition, the developer can specify more information using the Message and Severity parameters.
RegisterClientScript(ScriptName,ScriptText) Adds code (javascript, vbscript, html, etc) to the Scripts collection. Right before the page is rendered everything is rendered. Each script has an unique id (ScriptName). If you call this function more than once with the same script name the latest wich overwrite the previous.
DataBind(DataSource, WebControl) Navigates through the Controls hierarchy and invokes the  SetValueFromDataSource event for those WebControls with a value in the DataTextField property.
GetPostBackEvent Gets an ClientEvent object with the data from the PostBack. For more info see the ClientEvent object
ShowMessageShowMessage(strTitle,strMessage,x,y,w,h) Shows a dhtml div in the page as soon as its rendered.
SetDefaultFocus(WebControl) Renders some JavaScript code to set the focus to the control specified in the parameter.
SetDefaultObject(TheControl,JSEvent) Renders some JavaScript code to execute the function JSEvent for the control TheControl when the "Enter" key is pressed.
Execute Executes the page. (Same as calling Main() )
RegisterEventListener(object,eventName,fncName)

Reisgters a Script that will execute the function <fncName> on JS Event  <EventName> for object <object>. i.e.

If function in "fncName"  returns true then the original event handler (if any) will be invoked. The events are "linked" so you can have multiple event listeners for the same object for the same event. They will be called from last to first (LIFO)

RegisterPostBackEventHandler(Control,EventHandlerName,Parameters)

Registers the Event for the control which will be raised during a PostBack right after the Page_Load and before handling the postback event. This is mainly used by webcontrols. For instance, the checkbox control uses it to enlisten the OnChange event (i.e. on the process postback)

Checked = (Request.Form(Control.ControlID)<>"")
If RaiseOnChanged Then
If Checked <> CBool( Control.ViewState.Read("S")) Then
   Call Page.RegisterPostBackEventHandler (Me,"OnChanged","")
End If
End If
RegisterLibrary(LibName) Registers a library with the framework. This is mainly used by control developers. Every control should make use of this function. i.e. Page.RegisterLibrary("ServerTextBox")
IsLibraryLoaded(LibName) Returns true if a library was registered/is present.
CheckLibDependency(LibName,RequiredBy)

Used to assert if a library is present. For instance, suppose a custom controls needs to use the checkbox and textboxe controls it can do something like this:

Page.CheckLibDependency("ServerTextBox","LoginControl")

ApplySkin Uses internally to apply a theme/skin if present.
OpenForm Opens the CLASP form. VERY IMPORTANT. Always do it before rendering any control that renders input controls or any html iput control.
CloseForm IMPORTANT.This closes the form tag and adds any extra hidden field,as needed.

Public Events
Page_Authenticate_Request Can override. You can place your authentication code in here, if any. You can look at the PageControler class for an implementation example.
Page_Authorize_Request Can override. You can place your authorization code in here, if any. You can look at the PageControler class for an implementation example.
Page_Init Can override. Here is where you instanciate all your WebControl objects (Set txtfirstName = New_ServerTextBox("txtFirstName"), etc). Note: You should not set control properties here (other than the name) on WebControls that support viewstate because these values will be overwriten when the Page is restoring the viewstate.  VIEWSTATE is not available yet.
Page_Controls_Init

Can override. This event is called only when the page is load for the first time. This an is ideal place to put the code to set the default properties of your WebControls. You can alson execute code here that you want to run only when the page is loaded for the first time (IsPostBack = False). VIEWSTATE is not available yet.

Page_LoadViewState

Can override. This event occurs right after the viewstate is restored by all the WebControls with EnableViewState = True. This event only occurs on PostBacks. This is the perfect event to restore any variables added to the viewstate.

Page_Load Can override. This event occurs when all the WebControls have been initialized and viewstate fully restored. Posted data was also applied to all controls, as appropriate.
Page_PreRender Can override. This event occurs when the Page is about to be ready to be rendered. You can use it to
Page_SaveViewState Can override. This event is invoked right after the viewstate is saved by all WebControls with EnableViewState = True. This event is also very useful to persist variables: Page.ViewState.Add "variableName", value . The variable can be modified during the page execution and then here you just save the last value.
Page_Terminate This happens LITERALLY when the page is about to be destroyed. It will execute even if the page execution ends abruptly due to an error. 

Protected Properties
Many used to store the traces, validations, scripts, etc. -- --

Protected Methods
WriteProperties(bag) Not used by the Page object.
ReadPropertied(bag) Not used by the Page object.
Page_WriteViewState(obj,node) Used by the CLASP to notifiy each WebControl in the hierarchy of controls that the viewstate is to be persisted. It will pass to each webcontrol its corresponding "node" in the viewstate were to write to. This method also prepares the PropertyBag object and passes it to the implementing control so it can write control-specific data to the viewstate.
Page_ReadViewState(obj,node) Used by the CLASP to notifiy each WebControl in the hierarchy of controls that the viewstate is to be restored. It will pass to each webcontrol its corresponding "node" in the viewstate were to read from This method also prepares the PropertyBag object and passes it to the implementing control so it can read control-specific data from the viewstate.
LoadViewState Used internally. This method is used to load the viewstate and determines whether or not a custom handler is present (Page_LoadPageStateFromPersistenceMedium). If true then it will delegate to that function, otherwise it will use Session or Client side viewstate, depending on the ViewstateMode setting.
SaveViewState Used internally. This method is used to persist the viewstate and also determines whether or not a custom handler is present (Page_LoadPageStateFromPersistenceMedium). If true then it will delegate to that function, otherwise it will use Session or Client side viewstate, depending on the ViewstateMode setting
PropagateEvent(WebControl,Event) Propagates the event <Event> starting at <WebControl>.
PropagateOnInit

Propagates the OnInit event to WebControls with the ImplementsOnInit flag set to true. This event is executed after the Page_Init.

PropagateOnLoad Propagates the OnLoad event to WebControls with the ImplementsOnLoad flag set to true. This event ocurrs right after the Page_Load
RenderClientScripts Renders all the registered client scripts.
HandleServerEvent(Event) This methodis used by the CLASP to raise a server event. This function should not be manually executed.
HandleClientEvent(ClientEvent) This method is invoked by the CLASP so the Page object can identify the target of the event and make sure it handles it.
HandlePostBackHandlers Raises any event registered with the RegisterPostBackEventHandler.
GetControlSkin(ctrl,cache) Used internally by CLASP. This method is used by the ApplySkin method and its purpose is to determine wheter or not there is a fuction available to modify the appereance of a type of webcontrol (TypeName(ctrl.Owner) ). It will cache the pointers to these functions to speed up the process.

Protected Events
-- --

Sequence of Events in CLASP

Looking at the Main() routine in WebControl.asp will give you a very good idea of how CLASP process a request. A high level look at the life cycle of a CLASP page looks like this:


Structure of a Page

Every CLASP page has to have a predefined structure. The use of the PageControler class simplifies the generation of CLASP pages a great deal. However it is important to understand how to structure a page.

  1. Include the WebControl.asp page
  2. Include any WebControl file to be used by the page (i.e. Server_TextBox.asp)
  3. Include any extra file that your page will make use of (such as data access, skins, etc)
  4. Execute the following ASP Code: Page.Execute.
  5. Put all your HTML code in here. You MUST start the section where you will be rendering your HTML Form and where WebControls that translate to HTML input controls by callin : Page.OpenForm and end it with Page.CloseForm. This is critical as these two functions will wrap the form and include all the hidden fields that CLASP make use of.
  6. Your Code-Behind or Server Code is next and should be in a separate file or at the bottom of the page.
  7. Include your WebControl variable declarations (i.e. Dim txtFirstName, txtLastName)
  8. Add Public Function Page_Init() and initialize all the WebControls there (I.e. Set txtFirstName = New_ServerTextBox("txtFirstName"),  you can also register postback events and the such at this stage.
  9. Add any other Page event that you want override such as Page_Controls_Init , Page_Load, etc.
  10. Write your event handlers such as cmdSave_OnClick, txtFirstName_OnTextChange.
  11. Write your supporting functions.
  12. That is it!, you are done!.

And what about te doPostBack JavaScript function?

This Client-Side JavasSript function is a critical part of the CLASP Framework and is used by all the controls to post events back to the server. This function centralized the way postbacks are handled. The prototype of this function is (which is part of clasp.form)
function doPostBack(action,object,instance,xmsg,frmaction,frameName)
  • Action: this is the Event Name (i.e. OnClick)
  • Object: is the object name/id (i.e. txtName, cmdButton)
  • Instance: is any value that you want to pass along with the message.
  • Xmsg: same as above
  • FrmAction: if supplied, then the form action will be replaced with this value
  • FrameName: if supplied, then the form target will be replaced with this value

    Page Configuration Options

    You have a few configuration alternatives when working with CLASP.

    Too much talking and explanation .... It is time for an Example!:


    <!--#Include File = "Controls\WebControl.asp"    -->
    <!--#Include File = "Controls\Server_Button.asp" -->
    <!--#Include File = "Controls\Server_Label.asp"    -->
    <%Page.Execute%> 
    <HTML>
    <HEAD>
    < META NAME="GENERATOR"Content="Microsoft Visual Studio 6.0">
    <TITLE>Server Buttons Example</TITLE>
    <LINKrel="stylesheet"type="text/css"href="/PageFrameworkV2/Samples.css"> 
    </HEAD>
    <BODY
    <SpanClass="Caption">BUTTONS EXAMPLE</Span>
    <HR>

    <%lblMessage%><HR>
    <% Page.OpenForm() %>

    <%cmdLinkButton%> | <%cmdButton%> | <%cmdImageButton%>

    <% Page.CloseForm() %>

    </BODY>
    </HTML>
     
    <%  '############ SERVER CODE
     
    'VARIABLE DECLARATIONS
     Dim lblMessage
     Dim cmdLinkButton
     Dim cmdButton
     Dim cmdImageButton 
     
     
    'PAGE EVENT HANDLERS   
     Public Function Page_Init()    
            'Page.DebugEnabled = True ' Want to see the trace and session objects and app. 
            Set lblMessage = New_ServerLabel("lblMessage")
            Set cmdLinkButton = New_ServerLinkButton("cmdLinkButton")    
            Set cmdButton = New_ServerButton("cmdButton")    
            Set cmdImageButton = New_ServerImageButton("cmdImageButton")        
      End Function
     
     Public Function Page_Controls_Init()                               
            cmdButton.Text = "Normal Button"
            cmdLinkButton.Text = "Link Button"
     
            cmdImageButton.Image = "images/book.gif"
            cmdImageButton.RollOverImage = "images/clear_all.gif"
            lblMessage.Control.Style = "border:1px solid blue;background-color:#AAAAAA"
      End Function
     
     Public Function Page_Load() 
      End Function
     
    'WEBCONTROLS POSTBACK EVENT HANDLERS 
     Public Function cmdButton_OnClick()
            lblMessage.Text = "You Clicked a normal button"  
      End Function
     
     Public Function cmdLinkButton_OnClick()
            lblMessage.Text = "You Clicked  Link Button"
      End Function
     
     Public Function cmdImageButton_OnClick()
            lblMessage.Text = "You Clicked on a Image Button"
      End Function
     
    'SUPPORTING FUNCTIONS (IF ANY)
    %>