From 654a9cae43358c7eecf3b522e9876aa7815e2453 Mon Sep 17 00:00:00 2001
From: Fabio Bas
-Assets are resource files (such as images, sounds, videos, CSS stylesheets, javascripts, etc.) that belong to specific component classes. Assets are meant to be provided to Web users. For better reusability and easier deployment of the corresponding component classes, assets should reside together with the component class files . For example, a toggle button may use two images, stored in file down.gif and up.gif, to show different toggle states. If we require the image files be stored under images directory under the Web server document root, it would be inconvenient for the users of the toggle button component, because each time they develop or deploy a new application, they would have to manually copy the image files to that specific directory. To eliminate this requirement, a directory relative to the component class file should be used for storing the image files. A common strategy is to use the directory containing the component class file to store the asset files.
-
-Because directories containing component class files are normally inaccessible by Web users, PRADO implements an asset publishing scheme to make available the assets to Web users. An asset, after being published, will have a URL by which Web users can retrieve the asset file.
-
-PRADO provides several methods for publishing assets or directories containing assets:
-
-BE AWARE: Be very careful with assets publishing, because it gives Web users access to files that were previously inaccessible to them. Make sure that you do not publish files that do not want Web users to see.
-
-Asset publishing is managed by the System.Web.TAssetManager module. By default, all published asset files are stored under the [AppEntryPath]/assets directory, where AppEntryPath refers to the directory containing the application entry script. Make sure the assets directory is writable by the Web server process. You may change this directory to another by configuring the BasePath and BaseUrl properties of the TAssetManager module in application configuration,
-
-PRADO uses caching techniques to ensure the efficiency of asset publishing. Publishing an asset essentially requires file copy operation, which is expensive. To save unnecessary file copy operations, System.Web.TAssetManager only publishes an asset when it has a newer file modification time than the published file. When an application runs under the Performance mode, such timestamp checking is also omitted.
-
-ADVISORY: Do not overuse asset publishing. The asset concept is mainly used to help better reuse and redistribute component classes. Normally, you should not use asset publishing for resources that are not bound to any component in an application. For example, you should not use asset publishing for images that are mainly used as design elements (e.g. logos, background images, etc.) Let Web server to directly serve these images will help improve the performance of your application.
-
-We now use the toggle button example to explain the usage of assets. The control uses two image files up.gif and down.gif, which are stored under the directory containing the control class file. When the button is in Up state, we would like to show the up.gif image. This can be done as follows,
-
-In the above, the call $this->getAsset('up.gif') will publish the up.gif image file and return a URL for the published image file. The URL is then rendered as the src attribute of the HTML image tag.
-
-To redistribute ToggleButton, simply pack together the class file and the image files. Users of ToggleButton merely need to unpack the file, and they can use it right away, without worrying about where to copy the image files to.
-
-Autenticación es un proceso de verificacion de alguna persona cuando esta dice ser quien es. Usualmente se utiliza para esto un nombre de usuario y un contraseña, pero podría incluir otros métodos para demostrar su identidad, tales como tarjetas inteligentes, huellas digitales, etc.
-
-Autorización es el proceso de saber si la persona, una vez indetificada, esta permitida a manipular recursos especificos. Esto es comunmente determinado conociendo si la persona tiene un rol especifico que le da acceso a los recursos solicitados.
-
-PRADO proporciona una capa extensible de autenticacion/autirizacion. Como esta descrito en el Ciclo de vida de una aplicacion PRADO, TApplication reserva diversos modulos del ciclo de vida, responsables de la autenticacion y la autorizacion. PRADO proporciona el modulo TAuthManager para este propósito. Los desarrolladores pueden incorporar sus propios modulos de autenticacion/autorizacion (auth) facilmente.
-TAuthManager esta diseñado para ser usado en conjunto con el modulo TUserManager, el cual implementa una base de datos de usuarios de solo lectura (read-only).
-
-When a page request occurs, TAuthManager will try to restore user information from session. If no user information is found, the user is considered as an anonymous or guest user. To facilitate user identity verification, TAuthManager provides two commonly used methods: login() and logout(). A user is logged in (verified) if his username and password entries match a record in the user database managed by TUserManager. A user is logged out if his user information is cleared from session and he needs to re-login if he makes new page requests.
-
-During Authorization application lifecycle, which occurs after Autenticación lifecycle, TAuthManager will verify if the current user has access to the requested page according to a set of authorization rules. The authorization is role-based, i.e., a user has access to a page if 1) the page explicitly states that the user has access; 2) or the user is of a particular role that has access to the page. If the user does not have access to the page, TAuthManager will redirect user browser to the login page which is specified by LoginPage property.
-
-To enable PRADO auth framework, add the TAuthManager module and TUserManager module to application configuration,
-
-In the above, the UserManager property of TAuthManager is set to the users module which is TUserManager. Developers may replace it with a different user management module that is derived from TUserManager.
-
-Authorization rules for pages are specified in page configurations as follows,
-
-An authorization rule can be either an allow rule or a deny rule. Each rule consists of four optional properties:
-
-When a page request is being processed, a list of authorization rules may be available. However, only the first effective rule matching the current user will render the authorization result.
-
-In the above example, anonymous users will be denied from posting to PageID1 and PageID2, while User1 and User2 and all users of role Role1 can access the two pages (in both get and post methods).
-
-Since version 3.1.1, the pages attribute in the authorization rules can take relative page paths with wildcard '*'. For example, pages="admin.Home" refers to the Home page under the admin directory, and pages="admin.*" would refer to all pages under the admin directory and subdirectories.
-
-Also introduced in version 3.1.1 are IP rules. They are specified by a new attribute ips in authorization rules. The IP rules are used to determine if an authorization rule aplies to an end-user according to his IP address. One can list a few IPs together, separated by comma ','. Wildcard '*' can be used in the rules. For example, ips="192.168.0.2, 192.168.1.*" means the rule applies to users whose IP address is 192.168.0.2 or 192.168.1.*. The latter matches any host in the subnet 192.168.1. If the attribute 'ips' is empty, not set or wildcard '*', the corresponding rule will apply to requests coming from any host address.
-
-As aforementioned, TUserManager implements a read-only user database. The user information are specified in either application configuration or an external XML file.
-
-We have seen in the above example that two users are specified in the application configuration. Complete syntax of specifying the user and role information is as follows,
-
-where the roles attribute in user element is optional. User roles can be specified in either the user element or in a separate role element.
-
-TDbUserManager is introduced in v3.1.0. Its main purpose is to simplify the task of managing user accounts that are stored in a database. It requires developers to write a user class that represents the necessary information for a user account. The user class must extend from TDbUser.
-
-To use TDbUserManager, configure it in the application configuration like following:
-Assets
-Asset Publishing
-
-
-Customization
-Performance
-A Toggle Button Example
-Autenticación y Autorizacion
-Funcionamiento de la Autenticación y Autorizacion en PRADO
-Using PRADO Auth Framework
-
-
-
-
-
-Using TUserManager
-Using TDbUserManager
-
-In the above, UserClass specifies what class will be used to create user instance. The class must extend from TDbUser. ConnectionID refers to the ID of a TDataSourceConfig module which specifies how to establish database connection to retrieve user information. -
--The user class has to implement the two abstract methods in TDbUser: validateUser() and createUser(). Since user account information is stored in a database, the user class may make use of its DbConnection property to reach the database. -
--Since 3.1.1, TAuthManager provides support to allow remembering login by setting AllowAutoLogin to true. Accordingly, TDbUser adds two methods to facilitate the implementation of this feature. In particular, two new methods are introduced: createUserFromCookie() and saveUserToCookie(). Developers should implement these two methods if remembering login is needed. Below is a sample implementation: -
--Collection is a basic data structure in programming. In traditional PHP programming, array is used widely to represent collection data structure. A PHP array is a mix of cardinal-indexed array and hash table. -
--To enable object-oriented manipulation of collections, PRADO provides a set of powerful collection classes. Among them, the TList and TMap are the most fundamental and usually serve as the base classes for other collection classes. Since many PRADO components have properties that are of collection type, it is very important for developers to master the usage of PRADO collection classes. -
- --A TList object represents a cardinal-indexed array, i.e., an array (object) with the index 0, 1, 2, ... -
--TList may be used like a PHP array. For example, -
--To obtain the number of items in the list, use the Count property. Note, do not use count($list), as it always returns 1. -
- --In addition, TList implements a few commonly used convenient methods for manipulating the data in a list. These include -
--As aforementioned, many PRADO component properties are based on TList or TList-derived collection classes. These properties all share the above usages. -
--For example, TControl (the base class for all PRADO controls) has a property called Controls which represents the collection of child controls. The type of Controls is TControlCollection which extends TList. Therefore, to append a new child control, we can use the following, -
--To traverse through the child controls, we can use, -
--Another example is the Items property, available in list controls, TRepeater, TDataList and TDataGrid. In these controls, the ancestor class of Items is TList. -
- --Often, we want to extend TList to perform additional operations for each addition or removal of an item. The only methods that the child class needs to override are insertAt() and removeAt(). For example, to ensure the list only contains items that are of TControl type, we can override insertAt() as follows, -
--A TMap object represents a hash table (or we say string-indexed array). -
--Similar to TList, TMap may be used like an array, -
--The Count property gives the number of items in the map while the Keys property returns a list of keys used in the map. -
- --The following methods are provided by TMap for convenience, -
--TAttributeCollection is a special class extending from TMap. It is mainly used by the Attributes property of TControl. -
-Besides the normal functionalities provided by TMap, TAttributeCollection allows you to get and set collection items like getting and setting properties. For example, - --Note, in the above $collection does NOT have a Label property. -
--Unlike TMap, keys in TAttributeCollection are case-insensitive. Therefore, $collection->Label is equivalent to $collection->LABEL. -
--Because of the above new features, when dealing with the Attributes property of controls, we may take advantage of the subproperty concept and configure control attribute values in a template as follows, -
--which adds an attribute named onclick to the TButton control. -
--PRADO provides a complete error handling and reporting framework based on the PHP 5 exception mechanism. -
- --Errors occur in a PRADO application may be classified into three categories: those caused by PHP script parsing, those caused by wrong code (such as calling an undefined function, setting an unknown property), and those caused by improper use of the Web application by client users (such as attempting to access restricted pages). PRADO is unable to deal with the first category of errors because they cannot be caught in PHP code. PRADO provides an exception hierarchy to deal with the second and third categories. -
--All errors in PRADO applications are represented as exceptions. The base class for all PRADO exceptions is TException. It provides the message internationalization functionality to all system exceptions. An error message may be translated into different languages according to the user browser's language preference. -
--Exceptions raised due to improper usage of the PRADO framework inherit from TSystemException, which can be one of the following exception classes: -
--Errors due to improper usage of the Web application by client users inherit from TApplicationException. -
- --Raising exceptions in PRADO has no difference than raising a normal PHP exception. The only thing matters is to raise the right exception. In general, exceptions meant to be shown to application users should use THttpException, while exceptions shown to developers should use other exception classes. -
- --Exceptions raised during the runtime of PRADO applications are captured by System.Exceptions.TErrorHandler module. Different output templates are used to display the captured exceptions. THttpException is assumed to contain error messages that are meant for application end users and thus uses a specific group of templates. For all other exceptions, a common template shown as follows is used for presenting the exceptions. -
- - --Developers can customize the presentation of exception messages. By default, all error output templates are stored under framework/Exceptions/templates. The location can be changed by configuring TErrorHandler in application configuration, -
--THttpException uses a set of templates that are differentiated according to different StatusCode property value of THttpException. StatusCode has the same meaning as the status code in HTTP protocol. For example, a status code equal to 404 means the requested URL is not found on the server. The StatusCode value is used to select which output template to use. The output template files use the following naming convention: -
--where status code refers to the StatusCode property value of THttpException, and language code must be a valid language such as en, zh, fr, etc. When a THttpException is raised, PRADO will select an appropriate template for displaying the exception message. PRADO will first locate a template file whose name contains the status code and whose language is preferred by the client browser window. If such a template is not present, it will look for a template that has the same status code but without language code. -
--The naming convention for the template files used for all other exceptions is as follows, -
--Again, if the preferred language is not found, PRADO will try to use exception.html, instead. -
-Many web application built with PHP will not have internationalization in mind when it was first written. It may be that it was not intended for use in languages and cultures. Internationalization is an important aspect due to the increase adoption of the Internet in many non-English speaking countries. The process of internationalization and localization will contain difficulties. Below are some general guidelines to internationalize an existing application.
- -Identify and separate data that varies with culture. The most obvious are text/string/message. Other type of data should also be considered. The following list categorize some examples of culture sensitive data -
- -If possible all manner of text should be isolated and store in a persistence format. These text include, application error messages, hard coded strings in PHP files, emails, static HTML text, and text on form elements (e.g. buttons).
- -To enable the localization features in PRADO, you need to add a few configuration options in your application configuration. -First you need to include the System.I18N.* namespace to your paths. -
-Then, if you wish to translate some text in your application, you need to add one translation message data source.
-Where source in translation is the dot path to a directory -where you are going to store your translate message catalogue. The autosave -attribute if enabled, saves untranslated messages back into the message catalogue. -With cache enabled, translated messages are saved in the application runtime/i18n directory. -The marker value is used to surround any untranslated text. -
- -With the configuration complete, we can now start to localize your application. If you have autosave enabled, after running your application with some localization activity (i.e. translating some text), you will see a directory and a messages.xml created within your source directory.
- -The translation message catalogue file, if using type="XLIFF", is a standardized translation message interchange XML format. You can edit the XML file using any UTF-8 aware editor. The format of the XML is something like the following.
- -Once globalization is enabled, you can access the globalization settings, such as, Culture, Charset, etc, using
-You also change the way the culture is determined by changing the class attribute in the module configuration. For example, to set the culture that depends on the browser settings, you can use the TGlobalizationAutoDetect class.
-
You may also provide your own globalization class to change how the application culture is set. -Lastly, you can change the globalization settings on page by page basis using template control tags. For example, changing the Culture to "zh".
-The localize function searches for a translated string that matches original from your translation source. First, you need to locate all the hard coded text in PHP that are displayed or sent to the end user. The following example localizes the text of the $sender (assuming, say, the sender is a button). The original code before localization is as follows.
-
The hard coded message "Hello, world!" is to be localized using the localize function.
-Compound messages can contain variable data. For example, in the message "There are 12 users online.", the integer 12 may change depending on some data in your application. This is difficult to translate because the position of the variable data may be difference for different languages. In addition, different languages have their own rules for plurals (if any) and/or quantifiers. The following example can not be easily translated, because the sentence structure is fixed by hard coding the variable data within message.
-Where the second parameter in localize takes an associative array with the key as the substitution to find in the text and replaced it with the associated value. -The localize function does not solve the problem of localizing languages that have plural forms, the solution is to use TChoiceFormat.
- -The following sample demonstrates the basics of localization in PRADO.
-Messages and strings can be localized in PHP or in templates. -To translate a message or string in the template, use TTranslate.
- -TTranslate can also perform string substitution.
-The Parameters property can be use to add name values pairs for substitution. Substrings in the translation enclosed with "{" and "}" are consider as the
- parameter names during substitution lookup. The following example will substitute the substring "{time}" with the value of the parameter attribute "Parameters.time=<%= time() %>".
-
A short for TTranslate is also provided using the following syntax.
-where string will be translated to different languages according to the end-user's language preference. This syntax can be used with attribute values as well.
-Formatting localized date and time is straight forward.
-The Pattern property accepts 4 predefined localized date patterns and 4 predefined localized time patterns.
--The predefined can be used in any combination. If using a combined predefined pattern, -the first pattern must be the date, followed by a space, and lastly the time pattern. -For example, full date pattern with short time pattern. The actual ordering of the -date-time and the actual pattern will be determine automatically from locale data specified -by the Culture property.
- -You can also specify a custom pattern using the following sub-patterns.
-The date/time format is specified by means of a string time pattern. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following:
-
The count of pattern letters determine the format.
- -(Text): 4 letters uses full form, less than 4, use short or abbreviated form -if it exists. (e.g., "EEEE" produces "Monday", "EEE" produces "Mon")
- -(Number): the minimum number of digits. Shorter numbers are zero-padded - to this amount (e.g. if "m" produces "6", "mm" produces "06"). Year is - handled specially; that is, if the count of 'y' is 2, the Year will be - truncated to 2 digits. (e.g., if "yyyy" produces "1997", "yy" produces "97".) - Unlike other fields, fractional seconds are padded on the right with zero.
- -(Text and Number): 3 or over, use text, otherwise use number. (e.g., -"M" produces "1", "MM" produces "01", "MMM" produces "Jan", and "MMMM" -produces "January".)
- -Any characters in the pattern that are not in the ranges of ['a'..'z'] -and ['A'..'Z'] will be treated as quoted text. For instance, characters -like ':', '.', ' ', and '@' will appear in the resulting time text -even they are not embraced within single quotes.
- -Examples using the US locale:
-
-
If the Value property is not specified, the current date and time is used.
- -PRADO's Internationalization framework provide localized currency formatting and number formatting. Please note that the TNumberFormat component provides formatting only, it does not perform current conversion or exchange.
- -Numbers can be formatted as currency, percentage, decimal or scientific -numbers by specifying the Type attribute. The valid types are:
-Culture and Currency properties may be specified to format locale specific numbers.
- -If someone from US want to see sales figures from a store in
-Germany (say using the EURO currency), formatted using the german
- currency, you would need to use the attribute Culture="de_DE" to get
-the currency right, e.g. 100,00$. The decimal and grouping separator is
-then also from the de_DE locale. This may lead to some confusion because
-people from US uses the "," (comma) as thousand separator. Therefore a Currency
-attribute is available, so that the output from the following example results in $100.00
-
The Pattern property determines the number of digits, thousand grouping -positions, the number of decimal points and the decimal position. The actual characters that -are used to represent the decimal points and thousand points are culture specific -and will change automatically according to the Culture property. The valid -Pattern characters are:
--For example, consider the Value="1234567.12345" and -with Culture="en_US" (which uses "," for thousand point separator and "." for decimal separators). -
-Compound messages, i.e., string substitution, can be accomplished with TTranslateParameter.
-In the following example, the strings "{greeting}" and "{name}" will be replace
-with the values of "Hello" and "World", respectively.The substitution string must be enclose with "{" and "}". The parameters can be further translated by using TTranslate.
-
-
Using the localize function or TTranslate component to translate messages does not inform the translator the cardinality of the data required to determine the correct plural structure to use. It only informs them that there is a variable data, the data could be anything. Thus, the translator will be unable to determine with respect to the substitution data the correct plural, language structure or phrase to use . E.g. in English, to translate the sentence, "There are {number} of apples.", the resulting translation should be different depending on the number of apples.
- -The TChoiceFormat component performs message/string choice translation. The following example demonstrated a simple 2 choice message translation.
- -In the above example, the Value "1" (one), thus the translated string -is "One Apple". If the Value was "2", then it will show "Two Apples".
- -The message/string choices are separated by the pipe "|" followed by a set notation of the form.
-Any non-empty combinations of the delimiters of square and round brackets are acceptable. -The string chosen for display depends on the Value property. The Value is evaluated for each set until the Value is found to belong to a particular set.
- - --PRADO provides a highly flexible and extensible logging functionality. Messages logged can be classified according to log levels and message categories. Using level and category filters, the messages can be further routed to different destinations, such as files, emails, browser windows, etc. The following diagram shows the basic architecture of PRADO logging mechanism, -
- - --The following two methods are provided for logging messages in PRADO, -
--The difference between Prado::log() and Prado::trace() is that the latter automatically selects the log level according to the application mode. If the application is in Debug mode, stack trace information is appended to the messages. Prado::trace() is widely used in the core code of the PRADO framework. -
- --Messages logged using the above two functions are kept in memory. To make use of the messages, developers need to route them to specific destinations, such as files, emails, or browser windows. The message routing is managed by System.Util.TLogRouter module. When plugged into an application, it can route the messages to different destination in parallel. Currently, PRADO provides three types of routes: -
--To enable message routing, plug in and configure the TLogRouter module in application configuration, -
--In the above, the Levels and Categories specify the log and category filters to selectively retrieve the messages to the corresponding destinations. -
- --Messages can be filtered according to their log levels and categories. Each log message is associated with a log level and a category. With levels and categories, developers can selectively retrieve messages that they are interested on. -
--Log levels defined in System.Util.TLogger include : DEBUG, INFO, NOTICE, WARNING, ERROR, ALERT, FATAL. Messages can be filtered according log level criteria. For example, if a filter specifies WARNING and ERROR levels, then only those messages that are of WARNING and ERROR will be returned. -
--Message categories are hierarchical. A category whose name is the prefix of another is said to be the ancestor category of the other category. For example, System.Web category is the ancestor of System.Web.UI and System.Web.UI.WebControls categories. Messages can be selectively retrieved using such hierarchical category filters. For example, if the category filter is System.Web, then all messages in the System.Web are returned. In addition, messages in the child categories, such as System.Web.UI.WebControls, are also returned. -
--By convention, the messages logged in the core code of PRADO are categorized according to the namespace of the corresponding classes. For example, messages logged in TPage will be of category System.Web.UI.TPage. -
- --Pages in a Web application often share common portions. For example, all pages of this tutorial application share the same header and footer portions. If we repeatedly put header and footer in every page source file, it will be a maintenance headache if in future we want to something in the header or footer. To solve this problem, PRADO introduces the concept of master and content. It is essentially a decorator pattern, with content being decorated by master. -
--Master and content only apply to template controls (controls extending TTemplateControl or its child classes). A template control can have at most one master control and one or several contents (each represented by a TContent control). Contents will be inserted into the master control at places reserved by TContentPlaceHolder controls. And the presentation of the template control is that of the master control with TContentPlaceHolder replaced by TContent. -
--For example, assume a template control has the following template: -
--which uses MasterControl as its master control. The master control has the following template, -
--Then, the contents are inserted into the master control according to the following diagram, while the resulting parent-child relationship can be shown in the next diagram. Note, the template control discards everything in the template other than the contents, while the master control keeps everything and replaces the content placeholders with the contents according to ID matching. -
- alt="Master and Content" /> - alt="Parent-child relationship between master and content" /> - --Master is very similar to external templates which are introduced since version 3.0.5. A special include tag is used to include an external template file into a base template. -
--Both master and external template can be used to share common contents among pages. A master is a template control whose template contains the common content and whose class file contains the logic associated with the master. An external template, on the other hand, is a pure template file without any class files. -
--Therefore, use master control if the common content has to be associated with some logic, such as a page header with search box or login box. A master control allows you to specify how the common content should interact with end users. If you use external templates, you will have to put the needed logic in the page or control class who owns the base template. -
--Performancewise, external template is lighter than master as the latter is a self-contained control participating the page lifecycles, while the former is used only when the template is being parsed. -
- --Performance of Web applications is affected by many factors. Database access, file system operations, network bandwidth are all potential affecting factors. PRADO tries in every effort to reduce the performance impact caused by the framework. -
- --PRADO provides a generic caching technique used by in several core parts of the framework. For example, when caching is enabled, TTemplateManager will save parsed templates in cache and reuse them in the following requests, which saves time for parsing templates. The TThemeManager adopts the similar strategy to deal with theme parsing. -
--Enabling caching is very easy. Simply add the cache module in the application configuration, and PRADO takes care of the rest. -
--Developers can also take advantage of the caching technique in their applications. The Cache property of TApplication returns the plugged-in cache module when it is available. To save and retrieve a data item in cache, use the following commands, -
--where $keyName should be a string that uniquely identifies the data item stored in cache. -
- --Since v3.1.0, a new control called TOutputCache has been introduced. This control allows users to selectively cache parts of a page's output. When used appropriately, this technique can significant improve pages' performance because the underlying controls are not created at all if the cached versions are hit. -
- --Including many PHP script files may impact application performance significantly. PRADO classes are stored in different files and when processing a page request, it may require including tens of class files.To alleviate this problem, in each PRADO release, a file named pradolite.php is also included. The file is a merge of all core PRADO class files with comments being stripped off and message logging removed. -
--To use pradolite.php, in your application entry script, replace the inclusion of prado.php with pradolite.php. -
- --Application mode also affects application performance. A PRADO application can be in one of the following modes: Off, Debug, Normal and Performance. The Debug mode should mainly be used during application development, while Normal mode is usually used in early stage after an application is deployed to ensure everything works correctly. After the application is proved to work stably for some period, the mode can be switched to Performance to further improve the performance. -
--The difference between Debug, Normal and Performance modes is that under Debug mode, application logs will contain debug information, and under Performance mode, timestamp checking is not performed for cached templates and published assets. Therefore, under Performance mode, application may not run properly if templates or assets are modified. Since Performance mode is mainly used when an application is stable, change of templates or assets are not likely. -
--To switch application mode, configure it in application configuration: -
--By default, PRADO stores page state in hidden fields of the HTML output. The page state could be very large in size if complex controls, such as TDataGrid, is used. To reduce the size of the network transmitted page size, two strategies can be used. -
--First, you may disable viewstate by setting EnableViewState to false for the page or some controls on the page if they do not need user interactions. Viewstate is mainly used to keep track of page state when a user interacts with that page/control. -
--Second, you may use a different page state storage. For example, page state may be stored in session, which essentially stores page state on the server side and thus saves the network transmission time. The StatePersisterClass property of the page determines which state persistence class to use. By default, it uses System.Web.UI.TPageStatePersister to store persistent state in hidden fields. You may modify this property to a persister class of your own, as long as the new persister class implements the IPageStatePersister interface. You may configure this property in several places, such as application configuration or page configuration using <pages> or <page> tags, -
--Note, in the above the SpecialPage will use MyPersister2 as its persister class, while the rest pages will use MyPersister1. Therefore, you can have different state persister strategies for different pages. -
- --Server caching techniques are proven to be very effective in improving the performance of PRADO applications. For example, we have observed that by using Zend Optimizer, the RPS (request per second) of a PRADO application can be increased by more than ten times. Of course, this is at the cost of stale output, while PRADO's caching techniques always ensure the correctness of the output. -
- -- If you are a web developer and come from the same place I do, you have probably - used quite a bit of Javascript in your web pages, mostly as UI glue. -
-- - Until recently, I knew that Javascript had more OO capabilities than I was employing, - but I did not feel like I needed to use it. As the browsers started to support a more - standardized featureset of Javascript and the DOM, it became viable to write more - complex and functional code to run on the client. That helped giving birth to the - AJAX phenomena. -
-- As we all start to learn what it takes to write our cool, AJAX applications, we begin - to notice that the Javascript we used to know was really just the tip of the iceberg. - We now see Javascript being used beyond simple UI chores like input validation and frivolous - tasks. The client code now is far more advanced and layered, much like a real desktop - application or a client-server thick client. We see class libraries, object models, - hierarchies, patterns, and many other things we got used to seeing only in our server - side code. -
-- In many ways we can say that suddenly the bar was put much higher than before. It takes - a heck lot more proficiency to write applications for the new Web and we need to improve - our Javascript skills to get there. - If you try to use many of the existing javascript libraries out there, like - Prototype.js, - Scriptaculous, - moo.fx, - Behaviour, - YUI, - etc you'll eventually find yourself reading the JS code. Maybe because you want - to learn how they do it, or because you're curious, or more often because that's the - only way to figure out how to use it, since documentation does not seem to be highly - regarded with most of these libraries. Whatever the case may be, you'll face some - kung-fu techniques that will be foreign and scary if you haven't seen anything like - that before. -
- -- The purpose of this article is precisely explaining the types of constructs that - many of us are not familiar with yet. -
- - -- JavaScript Object Notation (JSON,) is one of the new - buzzwords popping up around the AJAX theme. JSON, simply put, is a way of - declaring an object in Javascript. Let's see an example right away and note - how simple it is. -
-- Let's just add little bit of formatting so it looks more like how we usually find out there: -
-- Here we created a reference to an object with two properties (color - and legCount) and a method (communicate.) - It's not hard to figure out that the object's properties and methods - are defined as a comma delimited list. Each of the members is introduced by name, followed - by a colon and then the definition. In the case of the properties it is easy, just the value - of the property. The methods are created by assigning an anonymous function, which we will - explain better down the line. - After the object is created and assigned to the variable myPet, - we can use it like this: -
- -- You'll see JSON used pretty much everywhere in JS these days, as arguments to functions, - as return values, as server responses (in strings,) etc. -
- -- This might be unusual to developers that never thought about that, but in JS a function is - also an object. You can pass a function around as an argument to another function just like - you can pass a string, for example. This is extensively used and very handy. -
- -- Take a look at this example. We will pass functions to another function that will use them. -
-- Note that we pass myDog.bark and myCat.meow without appending parenthesis - "()" to them. If we did that we would not be passing - the function, rather we would be calling the method and passing the return value, - undefined in both cases here. -
- -- If you want to make my lazy cat start barking, you can easily do this: -
-- The following two lines in JS do the same thing. -
- -- As I'm sure you already know, you can access individual items in an array - by using the square brackets: -
-- - But you are not limited to numeric indices. You can access any member of a JS - object by using its name, in a string. The following example creates an empty - object, and adds some members by name. -
-- The above code has identical effect as the following: -
-- In many ways, the idea of objects and associative arrays (hashes) in JS are not - distiguishable. The following two lines do the same thing too. -
-- - The great power of object oriented programming languages derive from the use - of classes. I don't think I would have guessed how classes are defined in JS - using only my previous experience with other languages. Judge for yourself. -
-- Let's see how we add a method to our Pet class. We will be using the - prototype property that all classes have. The prototype - property is an object that contains all the members that any object of the class will have. - Even the default JS classes, like String, Number, - and Date have a prototype object that we - can add methods and properties to and make any object of that class automatically gain this new member. -
- -- That's when a library like prototype.js comes in - handy. If we are using prototype.js, we can make our code look cleaner (at least in my opinion.) -
-- If you have never worked with languages that support closures - you may find the following idiom too funky. -
-- - Whoa! Let's explain what is going on here before you decide I've gone too - far and navigate to a better article than this one. -
-- First of all, in the above example we are using the prototype.js library, which - adds the each function to the Array class. The each function accepts one - argument that is a function object. This function, in turn, will be called once - for each item in the array, passing two arguments when called, the item and the index - for the current item. Let's call this function our iterator function. - We could have also written the code like this. -
-- But then we would not be doing like all the cool kids in school, right? - More seriously, though, this last format is simpler to understand but causes - us to jump around in the code looking for the myIterator function. It's nice - to have the logic of the iterator function right there in the same place - it's called. Also, in this case, we will not need the iterator function anywhere - else in our code, so we can transform it into an anonymous function without penalty. -
- -- - One of the most common troubles we have with JS when we start writing our code - it the use of the this keyword. It could be a real - tripwire. -
-- As we mentioned before, a function is also an object in JS, and sometimes we - do not notice that we are passing a function around. -
-- Take this code snippet as an example. -
-- Because the buttonClicked function is defined outside any object we may tend to - think the this keyword will contain a reference to - the window or document - object (assuming this code is in the middle of an HTML page viewed in a browser.) -
- -- But when we run this code we see that it works as intended and displays the id of - the clicked button. What happened here is that we made the onclick method of each button contain the - buttonClicked object reference, replacing whatever was there before. Now - whenever the button is clicked, the browser will execute something similar to the following line. -
-- - That isn't so confusing afterall, is it? But see what happens you start having other - objects to deal with and you want to act on these object upon events like the button's click. -
-- So you think, nice, now I can click the Clear button on my page and those three text boxes - will be emptied. Then you try clicking the button only to get a runtime error. The error - will be related to (guess what?) the this keyword. - The problem is that this.formFields is not defined if - this contains a referece to the button, which is - precisely what's happening. One quick solution would be to rewrite our last line of code. -
- -- That way we create a brand new function that calls our helper method within the helper object's context. -
-The javascript libraries distributed with Prado can be found in the -framework/Web/Javascripts/source directory. The packages.php -file in that directory defines a list of available package names available -to be loaded. They can be loaded as follows. -
-The dependencies for each library are automatically resolved. Components -that require a particular library will also automatically load the necessary libraries. -For example, if you add a TDatePicker component on the page, the datepicker -and its dependencies will be automatically included on the page.
- -See TClientScript for options of adding - your custom Javascript code to the page.
- --Viewstate lies at the heart of PRADO. Viewstate represents data that can be used to restore pages to the state that is last seen by end users before making the current request. By default, PRADO uses hidden fields to store viewstate information. -
--It is extremely important to ensure that viewstate is not tampered by end users. Without protection, malicious users may inject harmful code into viewstate and unwanted instructions may be performed when page state is being restored on server side. -
--To prevent viewstate from being tampered, PRADO enforces viewstate HMAC (Keyed-Hashing for Message Authentication) check before restoring viewstate. Such a check can detect if the viewstate has been tampered or not by end users. Should the viewstate is modified, PRADO will stop restoring the viewstate and return an error message. -
--HMAC check requires a private key that should be secret to end users. Developers can either manually specify a key or let PRADO automatically generate a key. Manually specified key is useful when the application runs on a server farm. To do so, configure TSecurityManager in application configuration, -
--HMAC check does not prevent end users from reading the viewstate content. An added security measure is to encrypt the viewstate information so that end users cannot decipher it. To enable viewstate encryption, set the EnableStateEncryption of pages to true. This can be done in page configurations or in page code. Note, encrypting viewstate may degrade the application performance. A better strategy is to store viewstate on the server side, rather than the default hidden field. -
- --Cross site scripting (also known as XSS) occurs when a web application gathers malicious data from a user. Often attackers will inject JavaScript, VBScript, ActiveX, HTML, or Flash into a vulnerable application to fool other application users and gather data from them. For example, a poorly design forum system may display user input in forum posts without any checking. An attacker can then inject a piece of malicious JavaScript code into a post so that when other users read this post, the JavaScript runs unexpectedly on their computers. -
--One of the most important measures to prevent XSS attacks is to check user input before displaying them. One can do HTML-encoding with the user input to achieve this goal. However, in some situations, HTML-encoding may not be preferable because it disables all HTML tags. -
--PRADO incorporates the work of SafeHTML and provides developers with a useful component called TSafeHtml. By enclosing content within a TSafeHtml component tag, the enclosed content are ensured to be safe to end users. In addition, the commonly used TTextBox has a SafeText property which contains user input that are ensured to be safe if displayed directly to end users. -
- --Protecting cookies from being attacked is of extreme important, as session IDs are commonly stored in cookies. If one gets hold of a session ID, he essentially owns all relevant session information. -
--There are several countermeasures to prevent cookies from being attacked. -
--PRADO implements a cookie validation scheme that prevents cookies from being modified. In particular, it does HMAC check for the cookie values if cookie validation is enable. -
--Cookie validation is disabled by default. To enable it, configure the THttpRequest module as follows, -
--To make use of cookie validation scheme provided by PRADO, you also need to retrieve cookies through the Cookies collection of THttpRequest by using the following PHP statements, -
--To send cookie data encoded with validation information, create new THttpCookie objects and add them to the Cookies collection of THttpResponse, -
--Web applications often need to remember what an end user has done in previous page requests so that the new page request can be served accordingly. State persistence is to address this problem. Traditionally, if a page needs to keep track of user interactions, it will resort to session, cookie, or hidden fields. PRADO provides a new line of state persistence schemes, including view state, control state, and application state. -
- --View state lies at the heart of PRADO. With view state, Web pages become stateful and are capable of restoring pages to the state that end users interacted with before the current page request. Web programming thus resembles to Windows GUI programming, and developers can think continuously without worrying about the round trips between end users and the Web server. For example, with view state, a textbox control is able to detect if the user input changes the content in the textbox. -
--View state is only available to controls. View state of a control can be disabled by setting its EnableViewState property to false. To store a variable in view state, call the following, -
--where $this refers to the control object, Caption is a unique key identifying the $caption variable stored in viewstate. To retrieve the variable back from view state, call the following, -
--Control state is like view state in every aspect except that control state cannot be disabled. Control state is intended to be used for storing crucial state information without which a page or control may not work properly. -
--To store and retrieve a variable in control state, use the following commands, -
--Application state refers to data that is persistent across user sessions and page requests. A typical example of application state is the user visit counter. The counter value is persistent even if the current user session terminates. Note, view state and control state are lost if the user requests for a different page, while session state is lost if the user session terminates. -
--To store and retrieve a variable in application state, use the following commands, -
--PRADO encapsulates the traditional session management in THttpSession module. The module can be accessed from within any component by using $this->Session, where $this refers to the component object. -
- --Themes in PRADO provide a way for developers to provide a consistent look-and-feel across an entire web application. A theme contains a list of initial values for properties of various control types. When applying a theme to a page, all controls on that page will receive the corresponding initial property values from the theme. This allows themes to interact with the rich property sets of the various PRADO controls, meaning that themes can be used to specify a large range of presentational properties that other theming methods (e.g. CSS) cannot. For example, themes could be used to specify the default page size of all data grids across an application by specifying a default value for the PageSize property of the TDataGrid control. -
- --A theme is a directory consists of skin files, javascript files and CSS files. Any javascript or CSS files contained in a theme will be registered with the page that the theme is applied to. A skin is a set of initial property values for a particular control type. A control type may have one or several skins, each identified by a unique SkinID. When applying a theme to a page, a skin is applied to a control if the control type and the SkinID value both match to those of the skin. Note, if a skin has an empty SkinID value, it will apply to all controls of the particular type whose SkinID is not set or empty. A skin file consists of one or several skins, for one or several control types. A theme is the union of skins defined in all skin files. -
- --To use a theme, you need to set the Theme property of the page with the theme name, which is the theme directory name. You may set it in either page configurations or in the constructor or onPreInit() method of the page. You cannot set the property after onPreInit() because by that time, child controls of the page are already created (skins must be applied to controls right after they are created.) -
--To use a particular skin in the theme for a control, set SkinID property of the control in template like following, -
--This will apply the 'Blue' skin to the button. Note, the initial property values specified by the 'Blue' skin will overwrite any existing property values of the button. Use stylesheet theme if you do not want them to be overwritten. To use stylesheet theme, set the StyleSheetTheme property of the page instead of Theme (you can have both StyleSheetTheme and Theme). -
--To use the Javascript files and CSS files contained in a theme, a THead control must be placed on the page template. This is because the theme will register those files with the page and THead is the right place to load those files. -
--It is possible to specify media types of CSS files contained in a theme. By default, a CSS file applies to all media types. If the CSS file is named like mystyle.print.css, it will be applied only to print media type. As another example, mystyle.screen.css applies to screen media only, and mystyle.css applies to all media types. -
- --All themes by default must be placed under the [AppEntryPath]/themes directory, where AppEntryPath refers to the directory containing the application entry script. If you want to use a different directory, configure the BasePath and BaseUrl properties of the System.Web.UI.TThemeManager module in application configuration, -
--Creating a theme involves creating the theme directory and writing skin files (and possibly Javascript and CSS files). The name of skin files must be terminated with .skin. The format of skin files are the same as that of control template files. Since skin files do not define parent-child presentational relationship among controls, you cannot place a component tag within another. And any static texts between component tags are discarded. To define the aforementioned 'Blue' skin for TButton, write the following in a skin file, -
--As aforementioned, you can put several skins within a single skin file, or split them into several files. A commonly used strategy is that each skin file only contains skins for one type of controls. For example, Button.skin would contain skins only for the TButton control type. -
-