Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials - Web Development

1802 Articles
article-image-rendering-web-pages-pdf-using-railo-open-source
Packt
01 Apr 2010
6 min read
Save for later

Rendering web pages to PDF using Railo Open Source

Packt
01 Apr 2010
6 min read
As a pre-requisite for this tutorial, you should be familiar with html, css and web technologies in general. You do not need to know any CFML (ColdFusion Markup Language). You should have an understanding of databases, particularly MySQL, which we will use in this example. Server environment For this tutorial, we are using a virtual machine (using VirtualBox) running Windows 2003 Server Standard, IIS, MySQL 5.1, and Railo 3.1. The code we will be writing is not platform specific. You can just as easily implement this on Linux or Mac OSX Server with MySQL and Apache. Website architecture Lets assume that we have the HTML layout code provided to us for our website, and that we need to make it “work” on the web server, pulling its page content from a MySQL database. In addition, we will add the capability for any page to render itself as a PDF for printing purposes. You will want to make sure you have done a few things first: Make sure Railo and MySQL are running on your server (or VM) Make sure you created a MySQL database, and a user that has permission to use your database For development (as opposed to production web servers), try running Railo Express, which runs in a terminal window. This allows you to see the templates it is running, and the full stack trace of errors when they occur. Setting up the Railo datasource The first thing we need to do is setup a Railo datasource. This named datasource will define our database credentials for our website. Open a web browser to the Railo Server Administrator, which is usually located at: http://your.server.com/railo-context/admin/server.cfm. Check the Railo documentation if you have trouble opening up the administrator. Enter your password to login. Once logged in, click on the Services / Datasource link in the left navigation. At the bottom of this page is where you can create a new datasource. Enter a datasource name (Letters and numbers only, no spaces, and start with a letter) and select MySQL as the database type. On the next screen, enter the MySQL server host name or ip address, and username and password for the user you created. All of the other settings can be kept with their default values. Scroll to the bottom and click on the “Create” button to complete the datasource configuration. Railo Administrator will test your connection, so you can confirm that it is setup properly. We created the datasource in the “server” context. When you deploy an application on a production server, you should create your datasources in the “web” context, so that it is only available to the website that needs it. Datasources created in the server context are accessible from any website on the same server. Setting up the website structure In the document root of your website (or in the directory you choose for this tutorial), you will need a couple of files. index.cfm – this is the default document, like index.html or default.htm header.cfm – this is the top portion of web pages, what appears above your page content. This is where you would put your html “design” code. footer.cfm – this is the bottom portion of your web pages, what shows up after your page content. This is where you would put your html “design” code. layout.css – the basic CSS layout for our pages styles.css – the CSS styles for your page content Let's look first at header.cfm: This file contains what you would expect to see at the top of a standard HTML web page, including head, title, meta tags, etc. There are a few different tags included in the content however. Any tags that begin with <cf…> are CFML language tags, that are processed by Railo and removed from the source code before the page is sent to your web browser. Just like PHP or ASP.net code, if somebody views the source of your web page, they won’t see your CFML code, but rather, they will see the html code, and any code that your CFML tags generate. <cfparam name="title" default="Untitled" /> This tag defines and sets a default value for a variable named “title.” This value can be overridden using a <cfset …> tag which we will see later. #title#</cfoutput> Any content inside <cfoutput>…</cfoutput> tags will be included in the output to your web browser. In this case, the title variable is written to the page output. As with all <cf..> tags, the <cfoutput> tags themselves will be removed from the web page output. Anything inside # characters will be evaluated as an expression. So if your code was <cfoutput>title</cfoutput>, then the literal word “title” would be included in your page output. When you put # characters around it, Railo will evaluate the expression and replace it with the result.</cfoutput></cf..> header.cfm also includes the two .css files we need for our layout and styles. These are standard css which should be familiar to you, and won’t be covered in this article. Let's next look at index.cfm <cfset title="Home Page"> This first tag sets a local variable called “title” and sets its value to “Home Page.” <cfinclude template="header.cfm"> This tag includes the file “header.cfm” into the current page, which means that any page output (the html, head, title, etc. tags) will be included in this page’s output. Notice that we set the local variable title in our page, and it gets used in the header.cfm file. Local variables are available to any pages that are included in the requested web page. The “Hello World” content is the main textual content of this web page, and can be any html or CFML generated content you want. After the main content, another <cfinclude…> tag includes footer.cfm, which includes the expected end of page tags such as </body> and </html> Take a look If you open your web browser and browse to index.cfm, you will see your basic web page layout, with a page title, and Hello World content. If you view the page source, you should see the combined content of the header.cfm, index.cfm and footer.cfm, with no <cf…> tags in the output, only pure HTML. You can easily organize and create static web pages like this, and like many other programming languages, structuring your website like this has many benefits. If you make a change to your header or footer, then all your pages inherit the change immediately. Likewise if you design a new layout or style for your site, applying it once to your header and footer then applies it to your entire website.
Read more
  • 0
  • 0
  • 11663

article-image-managing-data-mysql
Packt
01 Apr 2010
8 min read
Save for later

Managing Data in MySQL

Packt
01 Apr 2010
8 min read
Exporting data to a simple CSV file While databases are a great tool to store and manage your data, you sometimes need to extract some of the data from your database to use it in another tool (a spreadsheet application being the most prominent example for this). In this recipe, we will show you how to utilize the respective MySQL commands for exporting data from a given table into a fi le that can easily be imported by other programs. Getting ready To step through this recipe, you will need a running MySQL database server and a working installation of a SQL client (like MySQL Query Browser or the mysql command line tool). You will also need to identify a suitable export target, which has to meet the following requirements: The MySQL server process must have write access to the target file The target file must not exist The export target file is located on the machine that runs your MySQL server, not on the client side! If you do not have file access to the MySQL server, you could instead use export functions of MySQL clients like MySQL Query Browser. In addition, a user with FILE privilege is needed (we will use an account named sample_install for the following steps; see also Chapter 8 Creating an installation user). Finally, we need some data to export. Throughout this recipe, we will assume that the data to export is stored in a table named table1 inside the database sample. As export target, we will use the file C:/target.csv (MySQL accepts slashes instead of backslashes in Windows path expressions). This is a file on the machine that runs the MySQL server instance, so in this example MySQL is assumed to be running on a Windows machine. To access the results from the client, you have to have access to the file (for example, using a fi le share or executing the MySQL client on the same machine as the server). How to do it... Connect to the database using the sample_install account. Issue the following SQL command: mysql> SELECT * FROM sample.table1 INTO OUTFILE 'C:/target.csv'FIELDS ENCLOSED BY '"' TERMINATED BY ';' ESCAPED BY '"' LINESTERMINATED BY 'rn'; Please note that when using a backslash instead of a slash in the target file's path, you have to use C:target.csv (double backslash for escaping) instead. If you do not give a path, but only a fi le name, the target fi le will be placed in the data directory of the currently selected schema of your MySQL server. How it works... In the previous SQL statement, a file C:/target.csv was created, which contains the content of the table sample.table1. The file contains a separate line for each row of the table, and each line is terminated by a sequence of a carriage return and a line feed character. This line ending was defined by the LINES TERMINATED BY 'rn' portion of the command. Each line contains the values of each column of the row. The values are separated by semicolons, as stated in the TERMINATED BY ';' clause. Every value is enclosed by a double quotation mark ("), which results from the FIELDS ENCLOSED BY '"' option. When writing the data to the target fi le, no character conversion takes place; the data is exported using the binary character set. This should be kept in mind especially when importing tables with different character sets for some of its values. You might wonder why we chose the semicolon instead of a comma as the field separator. This is simply because of a greatly improved Microsoft Excel compatibility (you can simply open the resulting files), without the need to import external data from the fi les. But you can, however, open these fi les in a different spreadsheet program (like OpenOffice.org Calc) as well. If you think the usage of semicolons is in contradiction to the notion of a CSV file, think of it as a Character Separated File. The use of double quotes to enclose single values prevents problems when field values contain semicolons (or generally the field separator character). These are not recognized as field separators if they are enclosed in double quotes. There's more... While the previous SELECT … INTO OUTFILE statement will work well in most cases, there are some circumstances in which you still might encounter problems. The following topics will show you how to handle some of those. Handling errors if the target fi le already exists If you try to execute the SELECT … INTO OUTFILE statement twice, an error File 'C:/target.csv' already exists occurs. This is due to a security feature in MySQL that makes sure that you cannot overwrite existing fi les using the SELECT … INTO OUTFILE statement. This makes perfect sense if you think about the consequences. If this were not the case, you could overwrite the MySQL data files using a simple SELECT because MySQL server needs write access to its data directories. As a result, you have to choose different target files for each export (or remove old files in advance). Unfortunately, it is not possible to use a non-constant file name (like a variable) in the SELECT … INTO OUTFILE export statement. If you wish to use different file names, for example, with a time stamp as part of the file name, you have to construct the statement inside a variable value before executing it:   mysql> SET @selInOutfileCmd := concat("SELECT * FROM sample.table1 INTOOUTFILE 'C:/target-", DATE_FORMAT(now(),'%Y-%m-%d_%H%i%s'), ".csv' FIELDSENCLOSED BY '"' TERMINATED BY ';' ESCAPED BY '"' LINES TERMINATED BY'rn';");mysql> PREPARE statement FROM @selInOutfileCmd;mysql> EXECUTE statement; The first SET statement constructs a string, which contains a SELECT statement. While it is not allowed to use variables for statements directly, you can construct a string that contains a statement and use variables for this. With the next two lines, you prepare a statement from the string and execute it. Handling NULL values Without further handling, NULL values in the data you export using the previous statement would show up as "N in the resulting file. This combination is not recognized, for example, by Microsoft Excel, which breaks the file (for typical usage). To prevent this, you need to replace NULL entries by appropriate values. Assuming that the table sample.table1 consists of a numeric column a and a character column b, you should use the following statement: mysql> SELECT IFNULL(a, 0), IFNULL(b, "NULL") FROM sample.table1 INTOOUTFILE 'C:/target.csv' FIELDS ENCLOSED BY '"' TERMINATED BY ';' ESCAPEDBY '"' LINES TERMINATED BY 'rn'; The downside to this approach is that you have to list all fi elds in which a NULL value might occur. Handling line breaks If you try to export values that contain the same character combination used for line termination in the SELECT … INTO OUTFILE statement, MySQL will try to escape the character combination with the characters defined by the ESCAPED BY clause. However, this will not always work the way it is intended. You will typically define rn as the line separators. With this constellation, values that contain a simple line break n will not cause problems, as they are exported without any conversion and can be imported to Microsoft Excel flawlessly. If your values happen to contain a combination of carriage return and line feed, the rn characters will be prepended with an escape character ("rn), but still the target file cannot be imported correctly. Therefore, you need to convert the full line breaks to simple line breaks: mysql> SELECT a, REPLACE(b, 'rn', 'n') FROM sample.table1 INTO OUTFILE'C:/target.csv' FIELDS ENCLOSED BY '"' TERMINATED BY ';' ESCAPED BY '"'LINES TERMINATED BY 'rn'; With this statement, you will export only line breaks n, which are typically accepted for import by other programs. Including headers For better understanding, you might want to include headers in your target fi le. You can do so by using a UNION construct: mysql> (SELECT 'Column a', 'Column b') UNION ALL (SELECT * FROM sample.table1 INTO OUTFILE 'C:/target.csv' FIELDS ENCLOSED BY '"' TERMINATED BY';' ESCAPED BY '"' LINES TERMINATED BY 'rn'); The resulting file will contain an additional first line with the given headers from the first SELECT clause.
Read more
  • 0
  • 0
  • 5928

article-image-configuring-mysql
Packt
01 Apr 2010
14 min read
Save for later

Configuring MySQL

Packt
01 Apr 2010
14 min read
Let's get started. Setting up a fixed InnoDB tablespace When using the InnoDB storage engine of MySQL, the data is typically not stored in a per-database or per-table directory structure, but in several dedicated files, which collectively contain the so-called tablespace. By default (when installing MySQL using the configuration wizard) InnoDB is confi gured to have one small file to store data in, and this file grows as needed. While this is a very fl exible and economical confi guration to start with, this approach also has some drawbacks: there is no reserved space for your data, so you have to rely on free disk space every time your data grows. Also, if your database grows bigger, the file will grow to a size which makes it hard to handle—a dozen files of 1 GB each are typically easier to manage than one clumsy 12 GB file. Large data files might, for example, cause problems if you try to put those files into an archive for backup or data transmission purposes. Even if the 2 GB limit is not present any more for the current file systems, many compression programs still have problems dealing with large files. And finally, the constant adaptation of the file in InnoDB's default configuration size will cause a (small, but existent) performance hit if your database grows. The following recipe will show you how to define a fixed tablespace for your InnoDB installation, by which you can avoid these drawbacks of the InnoDB default configuration. Getting ready To install a fixed tablespace, you will have to reflect about some aspects: how much tablespace should be reserved for your database, and how to size the single data files which in sum constitute the tablespace. Note that once your database completely allocates your tablespace, you will run into table full errors (error code 1114) when trying to add new data to your database. Additionally, you have to make sure that your current InnoDB tablespace is completely empty. Ideally, you should set up the tablespace of a freshly installed MySQL instance, in which case this prerequisite is given. To check whether any InnoDB tables exist in your database, execute the following statement and delete the given tables until the result is empty: SELECT TABLE_SCHEMA, TABLE_NAME FROM information_schema.tables WHERE engine="InnoDB"; If your database already contains data stored in InnoDB tables that you do not want to lose, you will have to create a backup of your database and recover the data from it when you are done with the recipe. Please refer to the chapter Backing Up and Restoring MySQL Data for further information on this. And finally, you have to make sure that the InnoDB data directory (as defined by the innodb_data_home_dir variable) features sufficient free disk space to store the InnoDB data files. For the following example, we will use a fixed tablespace with a size of 500 MB and a maximal file size of 200 MB. How to do it... Open the MySQL configuration file (my.ini or my.cnf) in a text editor. Identify the line starting with innodb_data_file_path in the [mysqld] section. If no such line exists, add the line to the file. Change the line innodb_data_file_path to read as follows: innodb_data_file_path=ibdata1:200M;ibdata2:200M;ibdata3:100M Save the changed configuration file. Shut down your database instance (if running). Delete previous InnoDB data files (typically called ibdata1, ibdata2, and so on) from the directory defined by the innodb_data_home_dir variable. Delete previous InnoDB logfiles (named ib_logfile0, ib_logfile1, so on) from the directory defined by the innodb_log_group_home_dir variable. If innodb_log_group_home_dir is not configured explicitly, it defaults to the datadir directory. Start your database. Wait for all data and log files to be created. Depending on the size of your tablespace and the speed of your disk system, creation of InnoDB data fi les can take a significant amount of time (several minutes is not an uncommon time for larger installations). During this initialization sequence, MySQL is started but it will not accept any requests. How it works... Steps 1 through 4—and particularly 3—cover the actual change to be made to the MySQL configuration, which is necessary to adapt the InnoDB tablespace settings. The value of the innodb_data_file_path variable consists of a list of data file definitions that are separated by semicolons. Each data file definition is constructed of a fi le name and a file size with a colon as a separator. The size can be expressed as a plain numeric value, which defines the size of the data file in bytes. If the numeric value has a K, M, or G postfix, the number is interpreted as Kilobytes, Megabytes, or Gigabytes respectively. The list length is not limited to the three entries of our example; if you want to split a large tablespace into relatively small files, the list can easily contain dozens of data file definitions. If your tablespace consists of more than 10 files, we propose naming the first nine files ibdata01 through ibdata09 (instead of ibdata1 and so forth; note the zero), so that the files are listed in a more consistent order when they are displayed in your file browser or command line interface. Step 5 is prerequisite to the steps following after it, as deletion of vital InnoDB files while the system is still running is obviously not a good idea. In step 6, old data files are deleted to prevent collision with the new files. If InnoDB detects an existing file whose size differs from the size defined in the innodb_data_file_path variable, it will not initialize successfully. Hence, this step ensures that new, properly saved files can be created during the next MySQL start. Note that deletion of the InnoDB data files is only suffi cient if all InnoDB tables were deleted previously (as discussed in the Getting ready section). Alternatively, you could delete all *.frm files for InnoDB tables from the MySQL data directory, but we do not encourage this approach (clean deletion using DROP TABLE statements should be preferred over manual intervention in MySQL data directories whenever possible). Step 7 is necessary to prevent InnoDB errors after the data files are created, as the InnoDB engine refuses to start if the log files are older than the tablespace files. With steps 8 and 9, the new settings take effect. When starting the database for the first time after changes being made to the InnoDB tablespace configuration, take a look at the MySQL error log to make sure the settings were accepted and no errors have occurred. The MySQL error log after the first start with the new settings will look similar to this:   InnoDB: The first specified data file E:MySQLInnoDBTestibdata1 didnot exist:InnoDB: a new database to be created!091115 21:35:56 InnoDB: Setting file E:MySQLInnoDBTestibdata1 sizeto 200 MBInnoDB: Database physically writes the file full: wait...InnoDB: Progress in MB: 100 200...InnoDB: Progress in MB: 100091115 21:36:19 InnoDB: Log file .ib_logfile0 did not exist: new tobe createdInnoDB: Setting log file .ib_logfile0 size to 24 MBInnoDB: Database physically writes the file full: wait......InnoDB: Doublewrite buffer not found: creating newInnoDB: Doublewrite buffer createdInnoDB: Creating foreign key constraint system tablesInnoDB: Foreign key constraint system tables created091115 21:36:22 InnoDB: Started; log sequence number 0 0091115 21:36:22 [Note] C:Program FilesMySQLMySQL Server 5.1binmysqld: ready for connections.Version: '5.1.31-community-log' socket: '' port: 3306 MySQLCommunity Server (GPL)   There's more... If you already use a fixed tablespace, and you want to increase the available space, you can simply append additional files to your fixed tablespace by adding additional data file definitions to the current innodb_data_file_path variable setting. If you simply append additional files, you do not have to empty your tablespace first, but you can change the confi guration and simply restart your database. Nevertheless, as with all changes to the confi guration, we strongly encourage creating a backup of your database first.   Setting up an auto-extending InnoDB tablespace The previous recipe demonstrates how to define a tablespace with a certain fixed size. While this provides maximum control and predictability, you have to block disk space based on the estimate of the maximum size required in the foreseeable future. As long as you store less data in your database than the reserved tablespace allows for, this basically means some disk space is wasted. This especially holds true if your setting does not allow for a separate file system exclusively for your MySQL instance, because then other applications compete for disk space as well. In these cases, a dynamic tablespace that starts with little space and grows as needed could be an alternative. The following recipe will show you how to achieve this. Getting ready When defining an auto-extending tablespace, you should first have an idea about the minimum tablespace requirements of your database, which will set the initial size of the tablespace. Furthermore, you have to decide whether you want to split your initial tablespace into files of a certain maximum size (for better file handling). If the above settings are identical to the current settings and you only want to make your tablespace grow automatically if necessary, you will be able to keep your data. Otherwise, you have to empty your current InnoDB tablespace completely (please refer to the previous recipe Setting up a fixed InnoDB tablespace for details). As with all major confi guration changes to your database, we strongly advise you to create a backup of your data first. If you have to empty your tablespace, you can use this backup to recover your data after the changes are completed. Again, please refer to the chapter Backing Up and Restoring MySQL Data for further information on this. And as before, you have to make sure that there is enough disk space available in the innodb_data_home_dir directory—not only for the initial database size, but also for the anticipated growth of your database. The recipe also requires you to shut down your database temporarily; so you have to make sure all clients are disconnected while performing the required steps to prevent conflicting access. As the recipe demands changes to your MySQL confi guration file (my.cnf or my.ini), you need write access to this file. For the following example, we will use an auto-extending tablespace with an initial size of 100 MB and a file size of 50 MB. How to do it... Open the MySQL configuration file (my.ini or my.cnf) in a text editor. Identify the line starting with innodb_data_file_path in the [mysqld] section. If no such line exists, add the line to the file. Change the line innodb_data_file_path to read as follows: innodb_data_file_path=ibdata1:50M;ibdata2:50M:autoextend Note that no file defi nition except the last one must have the :autoextend option; you will run into errors otherwise. Save the changed confi guration file. Shut down your database instance (if running). Delete previous InnoDB data files (typically called ibdata1, ibdata2, and so on) from the directory defi ned by the innodb_data_home_dir variable. Delete previous InnoDB logfiles (named ib_logfile0, ib_logfile1, and so on) from the directory defined by the innodb_log_group_home_dir variable. If innodb_log_group_home_dir is not configured explicitly, it defaults to the datadir directory Start your database. Wait for all data and log files to be created. Depending on the size of your tablespace and the speed of your disk system, creation of InnoDB data files can take a signifi cant amount of time (several minutes is not an uncommon time for larger installations). During this initialization sequence, MySQL is started but will not accept any requests. When starting the database for the first time after changes being made to the InnoDB tablespace configuration, take a look at the MySQL error log to make sure the settings were accepted and no errors have occurred. How it works... The above steps are basically identical to the steps of the previous recipe Setting up a fixed InnoDB tablespace, the only difference being the definition of the innodb_data_file_path variable. In this recipe, we create two files of 50 MB size, the last one having an additional :autoextend property. If the innodb_data_file_path variable is not set explicitly, it defaults to the value ibdata1:10M:autoextend. As data gets inserted into the database, parts of the tablespace will be allocated. As soon as the 100 MB of initial tablespace is not sufficient any more, the file ibdata2 will become larger to match the additional tablespace requirements. Note that the :autoextend option causes the tablespace files to be extended automatically, but they are not automatically reduced in size again if the space requirements decrease. Please refer to the Decreasing InnoDB tablespace recipe for instructions on how to free unused tablespace. There's more... The recipe only covers the basic aspects of auto-extending tablespaces; the following sections provide insight into some more advanced topics. Making an existing tablespace auto-extensible If you already have a database with live data in place and you want to change your current fixed configuration to use the auto-extension feature, you can simply add the :autoextend option to the last file definition. Let us assume a current configuration like the following: innodb_data_file_path=ibdata1:50M;ibdata2:50M The respective configuration with auto-extension will look like this: innodb_data_file_path=ibdata1:50M;ibdata2:50M:autoextend In this case, do not empty the InnoDB tablespace first, you can simply change the configuration file and restart your database, and you should be fine. As with all configuration changes, however, we strongly recommend to back up your database before editing these settings even in this case. Controlling the steps of tablespace extension The amount by which the size of the auto-extending tablespace file is increased is controlled by the innodb_autoextend_increment variable. The value of this variable defines the number of Megabytes by which the tablespace is enlarged. By default, 8 MB are added to the file if the current tablespace is no longer sufficient. Limiting the size of an auto-extending tablespace If you want to use an auto-extending tablespace, but also want to limit the maximum size your tablespace will grow to, you can add a maximum size for the auto-extended tablespace file by using the :autoextend:max:[size] option. The [size] portion is a placeholder for a size definition using the same notation as the size description for the tablespace file itself, which means a numeric value and an optional K, M, or G modifier (for sizes in Kilo-, Mega-, and Gigabytes). As an example, if you want to have a tiny initial tablespace of 10 MB, which is extended as needed, but with an upper limit of 2 GB, you would enter the following line to your MySQL configuration file: innodb_data_file_path=ibdata1:10M:autoextend:max:2G Note that if the maximum size is reached, you will run into errors when trying to add new data to your database. Adding a new auto-extending data file Imagine an auto-extending tablespace with an auto-extended file, which grew so large over time that you want to prevent the file from growing further and want to append a new auto-extending data file to the tablespace. You can do so using the following steps: Shut down your database instance. Look up the exact size of the auto-extended InnoDB data file (the last file in your current configuration). Put the exact size as the tablespace fi le size definition into the innodb_data_file_path configuration (number of bytes without any K, M, or G modifier), and add a new auto-extending data file. Restart your database. As an example, if your current confi guration reads ibdata1:10M:autoextend and the ibdata1 file has an actual size of 44,040,192 bytes, change configuration to innodb_data_file_path=ibdata1:44040192;ibdata2:10M:autoextend:max:2G.  
Read more
  • 0
  • 0
  • 4359

article-image-introduction-railo-open-source
Packt
31 Mar 2010
10 min read
Save for later

Introduction to Railo Open Source

Packt
31 Mar 2010
10 min read
What is Railo? Railo is an open source Java application server that implements CFML (ColdFusion Markup Language), a tag based language from Adobe's commercial product “ColdFusion.” Its performance is excellent, and it includes features that significantly increase productivity. Railo is a relative newcomer, but has been making some impressive ripples in the industry lately. This article is a primer on some of the critical advantages of Railo and why it is worth a serious look for web application development. Isn’t ColdFusion dead? A few years back, an article was published naming 10 technologies that were dead or dying, and to many people's surprise, ColdFusion was in that list. That caused a lot of waves. One thing about CFML developers – they are passionate about their programming language! ColdFusion has seen moderate success in specific vertical markets, but has been notably well accepted by the US Government. In comparison to dominant development languages, CFML never seemed to find real favor with the masses. Since ColdFusion was re-engineered to run entirely on Java, and with the arrival of Adobe Flex a few years ago which integrates Flash and ColdFusion, this has changed quite a bit. Adobe's ColdFusion product integrates so well with Flex that it has spawned new interest. One of the largest complaints about Adobe ColdFusion has always been the price. It’s been my experience that CFML developers consider themselves to be industry peers of LAMP (Linux, Apache, MySQL, PHP) developers, who use all open source tools. The majority of LAMP developers consider their skills much higher than that of CFML developers. This has only fed the fury over the years of CFML developers who claim that the investment in purchasing ColdFusion is a quick return on investment since CFML is so much more productive. Now along comes Railo, offering a free and open source solution to the CFML developers' dreams. Not only is it free, but also it performs fantastic, is stable, and is updated reasonably frequently. This is good news for CFML, which is, in my opinion, highly underrated, mostly due to poor marketing and sales price points over the years. CFML is actually quite a powerful and surprisingly productive language, and was designed to be a RAD (Rapid Application Development) tool. It has grown into a significantly better product, and certainly does deserve more respect than it has had. But enough about CFML, let’s talk about why I find Railo is so impressive and what distinguishes itself from the competition. What can you do with Railo? Perhaps the best way to answer this is to say, “What CAN'T you do with Railo?” The CFML language is essentially a big java tag library. CFML has grown into an impressive library over the years and Railo supports everything that Adobe's product supports that is in mainstream use. (There is some difference between the support as both Railo and Adobe release new versions of their products). The core features of Railo's language provide easy to learn tags for everything from database queries to sending dynamic email messages to scripting connections with ftp and Amazon s3 storage. Pretty much anything you can do with PHP you can do with Railo. Here's the catch – generally speaking, it takes less time to implement a solution using CFML than it does with PHP, ASP.net or pure Java. Use CFML for the basics; Extend using Java. While Railo gives you a LOT of built in functions, the real truth of the situation is that it is Java under the hood. All the tags and functions ultimately get compiled and run as Java byte code. The language is well designed, however, so that you can mix and match your CFML and Java code. For instance, if you wanted to read in a text file, you can use the built in tag CFFILE: <cffile action="read" file="c:webmessage.txt" variable="strContent"></cffile> This reads in the contents of the text file, and stores it in the specified variable. To display that content in the web browser, you would output it like so: <cfoutput>#strContent#</cfoutput> To illustrate how Java can be used directly in your code, this same task can be done using Java objects instead of the built in CFML tags like so: <cfobject type="Java" class=" java.io.FileReader" Action="Create" name="myFileReader"> <cfset Result = fileReader.init("c:webmessage.txt"); <cfoutput>#strContent#</cfoutput> These two small pieces of code achieve the same goals. My point is that the CFML language isn't limited to just CFML, you can instantiate and use any Java object anywhere within your code. This makes the language incredibly flexible, since you can use the CFML tags for quick and easy tasks, and use Java for heavy lifting where needed. Deployment and Development Environments All versions of Railo can be downloaded either as an “express,” “server” or “custom” deployment. The express edition is extremely easy for developers to get up and running and usually involves just decompressing a zip file onto your local system and starting it up. The server package comes along with Caucho Resin, a very high performance java application server. (Side note – some of the tools included with Resin are pretty impressive as well, including their all-java implementation of PHP!). The custom deployment package is for launching Railo on other Java servlet containers like Tomcat or Weblogic. Setting up Railo on a production server wasn't difficult, granted it is a bit more involved than installing RPMs of your favorite PHP version, but documentation was easily found on Railo's site and other sites found through Google. Like Adobe's product, Railo comes with web administration tools to manage the server and application-specific settings and resources. This is a big step up from the PHP and Linux world, where you normally need to configure a lot of your application's settings (data sources for example) in configuration files. The Railo administrator goes a few steps beyond Adobe as well, and makes context specific administration consoles available, so individual applications and websites can define their own sandboxed data sources, virtual mappings, and more. This is a really nice touch, and has been a requested feature for a long time. Where Railo Shines I have already reviewed some of the reasons why Railo is impressive. Aside from being a very powerful RAD, with performance that rivals or beats Adobe, Railo distinguishes itself further with some impressive features. Virtual File systems and Mappings As developers, we have all had to deal with managing remote or compressed files at one time or another. This feature in Railo does in a few mouse clicks what takes hundreds of lines of code. Railo lets you map remote file systems, like FTP, drive shares, and even Amazon S3 buckets and assign them to a virtual path in your application! This means that you can use the simple built in functions for file manipulation, and treat those files as if they were sitting right on the local file system. The support goes even further, and lets you map Java jar files and .zip files, so you can dynamically reference and run code sitting inside compressed archives. Setting up new mappings is a point-and-click affair in the Railo administrator or can be done programmatically. Application Distribution and Source Code Security The Java world has always been a step (alright, several steps) ahead of web application developers in packaging and distribution of applications. Many developers have their own home-grown methods for deploying a site and many web development applications, like Dreamweaver, have an FTP based method of deployment. Ultimately, it usually means handing over unprotected source code. CFML development has been the same way (yes, Adobe did have a way to compile .cfm templates, but my research shows it is both clumsy to use and not very popular). Railo brings “Java world” package deployment to CFML development. You can compile a whole application to Java byte code, compress it to a jar file and deploy it on any other Railo server. Railo is even smart enough to let you map a remote jar file on an FTP site and run it as a local web application. This means you have all the tools you need to deploy web applications and not expose your source. Built in AMF Support for Flex/Flash Applications Since Adobe open-sourced their BlazeDS AMF tools, Railo has integrated them making an easy to use system that “just works” with Flash applications. Inter-Application Integration, PDF and Video Manipulation CFML already has great capability for integrating with a huge number of database systems and can be expanded to use any of the huge number of open source Java projects. Railo can be used to talk to Amazon Web Services, like EC2 and S3 for cloud computing applications. Railo also has built in features for file conversions, such as dynamically generating PDFs, and programmatic editing and format conversions of digital video. A few simple lines of code can convert your video files to different formats, extract thumbnails for web previews, and then you could have them dropped on Amazon S3 to be served from the cloud. Very cool stuff, and worth looking at some of the examples on the Railo website. As you look over code that uses these features, it looks quite simple and it is amazing that Railo makes them look like child’s play, but there is serious inter-system integration going on behind the scenes. Railo makes it so very easy to add these capabilities to any web application. Infinitely Expandable with Java As mentioned above, it is easy to invoke Java classes from within CFML pages. Since Railo itself runs in a Java container, that means that any classes or code from the Java world can be integrated and used with a Railo application. My Experience Building a Railo Project My company has used ColdFusion for several projects. One of our commercial products is built on it and was originally designed for Adobe ColdFusion. Our product does a lot of heavy lifting with databases, internationalization, document format conversions, PDF previews and a lot more. Early in 2009 we did a complete conversion of the source to be compatible with Railo. There were only minor areas where our code needed to change, and most of them were with custom Java code that we wrote that simply needed updated to compatible with Railo's Java libraries. The pleasant surprise came when we were done and noticed a significant performance increase running on Railo. Summary In summary, I have been very impressed with Railo. It is community-driven; the people at Railo are responsive and truly care about the developer community, and the product really delivers what it claims. They have provided an application development platform that is both industry compatible and innovative. I think all seasoned web application developers will be able to appreciate what Railo has to offer. I believe that such powerful integration done so easily with only a few lines of code will draw a lot of attention. This is definitely a technology you should keep an eye on.
Read more
  • 0
  • 0
  • 4830

article-image-interactive-page-regions-drupal-6-part-2
Packt
31 Mar 2010
5 min read
Save for later

Interactive Page Regions with Drupal 6: Part 2

Packt
31 Mar 2010
5 min read
Activity 3-4–Adding CAPTCHA to the Contact form These days, there's a factor of spam form completion to legitimate that seems like 10:1. To prevent that, we're going to add a CAPTCHA to the form. This activity requires that the CAPTCHA module be installed and configured. Information about this can be found at http://drupal.org/project/captcha. CAPTCHA is a means of ensuring that the author of information being submitted is a human and not a 'robot' or 'web crawler.' Sometimes the user is asked to identify characters that appear in a graphic, sometimes they must identify the object shown in an image,or complete a simple math problem, and so on. We can begin by navigating to the CAPTCHA settings page (admin/user/captcha). The page lists the contact_mail_page and contact_user_page as forms that can have CAPTCHA set for them, but neither applies in this case, since we're using a form in a block in a view. We'll enable the CAPTCHA challenge for the user from the user form itself, but here we need to turn on the admin link to do so, so check the box labeled Add CAPTCHA administration links to forms which will provide a link on the form for us as long as we're logged in as the administrator. Having saved that change, return to our form. There, find a new link that opens as shown in the following screenshot: This brings up a dialog that allows us to choose the CAPTCHA type. Choose the type that provides an easy math equation. The result is the link changing on the form, to show us that CAPTCHA will be enabled. Why can't we see the CAPTCHA challenge, though? Because admins don't have to submit to a CAPTCHA challenge, so log out and look at the form. Adding a Contact info Attachment view With our contact form complete, it's time to complete our Contact Us page. We're going to add an attachment display to the Contact Us view that will provide other contact options. Actually, we have other options available to us. We could create this display as a block, or, since our current view has no node to display and the additional contact information will be a node, we could just have it shown by the existing Page display. We'll use an Attachment display instead of a block display simply because we don't want to use one of the block regions for the output, and we're already using the Content region for a block (the form). We've chosen not to use the Page display because it's easier to theme the output with one part of the content being a separate display. Then, its content is provided in a separate variable for us, so we'll use an Attachment display. Activity 3-5–Creating the contact-us Attachment view We need to create the content for the Attachment view. We'll be using a custom content type, Location, for this. Let's create the content (node/add/location). We'll give the content a title, Guild Builders Contact Information. For the body, we'll create a <div> and put the contact information in it. This step requires the embed_gmap module. Information about this module can be found at http://drupal.org/project/embed_gmap. Next, we'll get to the field that makes this content type different, the map. The embed_gmap module takes the content of the map field and uses it to produce and embed a Google map. Enter the address in this field. We'll save the content, which is shown in the following screenshot. With our content created, we're ready to create our Attachment display. Edit our Contact us view (admin/build/views/edit/contact_us). Create a title for the view, and name it Guild Builders Contact Information, also create the header information, to appear beneath the title. The next thing to do is create an Attachment display for our view. That takes us to the View control panel. We'll start with the Filters pane. Click on the Node: Post date filter we have, and click Override, so that our changes only affect the Attachment display. Then click Remove, because we don't want this filter for our Attachment. Click the + icon to add a filter. We created a piece of content, of the Location content type. Therefore, we can create a filter to select only the Node: Type of Location, and another to specify that the node is published, in case we ever have more than one version of that content, so that only the one that is published will be selected. In the settings dialog for the filter, specify that Published should be Yes. Next, we'll specify that the Attachment be attached to the Page display. The last thing we need to do is add a small entry to our CSS file, so that our map and contact information will appear side-by-side. /* Contact-Us page settings */#contact-us-info, .field-field.map { float: left}#contact-us-info { margin-right: 1em;} And with that, and two images that show our Attachment display (which is too large to fit on the page in one image), we're done! Summary We learned what the default Contact system does, and how to add just a little pizazz with an Attachment view. We learned how to add the Contact form to a view, and used Drupal's module architecture and hook mechanism to modify that form by creating a small module. Finally, we created an Attachment view to add content to our Contact page. [ 1 | 2 ] If you have read this article you may be interested to view : Interactive Page Regions with Drupal 6: Part 1 Drupal 6: Attachment Views, Page Views, and Theming
Read more
  • 0
  • 0
  • 1328

article-image-interactive-page-regions-drupal-6-part-1
Packt
31 Mar 2010
9 min read
Save for later

Interactive Page Regions with Drupal 6: Part 1

Packt
31 Mar 2010
9 min read
Lots to do—let's get started! Activity 3-1–Configuring the contact subsystem Navigate to the Contact form admin page (admin/build/contact) and click Add category. The Contact module is installed with Drupal, but is disabled by default. This step requires that the Contact module be enabled. The Contact form will open. The information that we need to provide in it is a title in the Category field, an e-mail address in the Recipients field to which the contact e-mails should be sent. We've made a contact form available. Normally, the form would be shown on a page of its own, but we need the form to be shown in a view, and will eventually point our menu choice to the view instead of the normal contact page. The contact form isn't a node, feed, or any of the typical constituents of a view. So, how do we bring it into one? There are different approaches, but the easiest will be to use another add-on module: Content form blocks. We'll navigate to its administration page under Settings (admin/settings/contact_form_blocks). This step requires that the Contact form blocks module be installed. This step requires that the Contact form blocks module be installed. Information about this module can be found at http://drupal.org/project/contact_form_blocks. The Contact module allows you to create categories of contact, such as feedback to the administrator, contact between users, and so on. On this site, the only contact that will be enabled is from users to the site owner. There's not a whole lot to configure here, since we only have one category of contact configured, but this is where you select which contact category will be available as a form inside a block. The following screenshot shows this configuration form ready to be saved. Having saved that information, the module will have created a block for our use in the contact-us view. Go to the list of blocks (admin/build/block) and see. Remember to scroll down to the Disabled section of the list to find the block, because it's not been assigned to a region yet. Because we named the contact category General, the block will be called Contact form: General. We want to assign the block to appear in the content area of our page, but the theme we are working with has not exposed Content as a region for our use. Let's change that. In the directory sites/all/themes/acquia_slate is the file acquia_slate.info. Edit it. There is no mandatory order within a theme's .info file, but they are small enough that you should be able to find what you need at a glance. Look for a group of lines that each begin with the word 'regions,' as shown below: regions[sidebar_first] = sidebar firstregions[sidebar_last] = sidebar lastregions[banner] = bannerregions[header_top] = header topregions[header_first] = header firstregions[header_middle] = header middleregions[header_bottom] = header bottomregions[preface_sidebar] = front preface sidebarregions[content_top] = inner content topregions[content_bottom] = content bottomregions[postscript_first] = postscript firstregions[postscript_middle] = postscript middleregions[postscript_last] = postscript lastregions[footer] = footerregions[node_bottom] = node bottom Each of those lines defines a region to which blocks can be assigned. We need to add one. Between the regions [content_top] and regions [content_bottom] lines insert the following: regions[content] = content Save the file, and then go to the Performance page (admin/settings/performance) and click the Clear cache button. Return to the blocks page and assign the Contact block to the Content region, as shown in the following screenshot, so that it will appear along with our View content. We need to configure the block, otherwise it will appear along with every piece of content on the site. We'll click configure, and set the block to appear only on a specific page, as shown in the following screenshot. We'll need to provide the path of that page, but it doesn't exist yet. Luckily, the block administration does not validate the path. Since we'll have to do it at some point anyway, we'll create a name for our eventual view, contact-us, and use it here. With the contact form now being hooked into a block, and the block configured to show in a single view, we need to create that view so that we can see the contact form. Activity 3-2–Creating the contact-us view The contact-us view we're going to create is simply going to be the glue for our pieces. By using a content type to provide contact information on the page, the site owner can easily have different versions of the page to use at different times of the year (like Google does on their home page) simply by creating a new node of the Location content type and having the desired one enabled. The view will make use of that content. Go to the views page (admin/build/views) click Add, and choose to create a Node view. At this point, we're not interested in configuring the view to provide any content. In fact, what we want to do is prevent it from showing content. The reason is that the block we created, which will contain the contact form, will appear in the content region of the page showing this view. We don't need any other content at this point. However, we cannot save this view as it is, because, by default, the Row style is set to Fields, and we have no fields selected. So, click on Row style and change it to Node. Having changed the Row style to Node will allow us get past the problem of not having defined any fields, and will allow us to save the view. However, that setting without any filters in place will cause the view to select every node, whereas we want it to select none, for now. There is no filter choice for Null display, but we can accomplish the equivalent easily. Select the filter Post date and set it to a date for which we know there are no posts. Lastly, we want to create a Page display and assign a path to it, so that we can access the view. Name it contact-us. The view is ready to save. The panel settings are shown in the following screenshot. With our skeletal view saved, navigate to its path (contact-us) and get a first look at the current contact form, as shown in the following screenshot: The location information isn't displayed at this time, because we have not yet created that content. The important thing here is the contact form. The site owner wants to capture when someone completes the form, which would not be available given only the form's current fields, namely Company, Street address, and Phone. There isn't an admin mechanism for adding fields to the contact form, but there is a relatively easy way to do it, once you know how, and that's by creating a module. What's a Module? A module is how we can add our own logic to what Drupal does- to add extra functionality, or to alter the behavior of Drupal's existing functionality. With some web applications, the only way to do this is to change the existing code ('core' in Drupal parlance). The problem with that is that when a new version of the application is released, not only will those changes need to be made again to the new version, but in some cases the code you originally changed will be different in the new version, so that the changes you made originally cannot be made in the same way. Fortunately, Drupal's module architecture and the ability to hook into its events remove any need to change the core code. Let's create a module! Activity 3-3–The Guild Builders module We'll go through the steps of creating our module, which will give you the basic knowledge that you need to decide whether you'd like to investigate the topic further. A module typically has up to four core files: the file core to its functionality (the .module file), a file that describes the module to Drupal (the .info file), a file that provides installation and removal instructions to Drupal (the .install file), such as for creating database tables, and sometimes included files to separate out functional parts of the module (.inc files). Our module will only require the former two. Creating the .info file. Open a text editor and add a few lines. name = GBI Custom This line defines the name of the module as it will be displayed in the modules listing in admin. package = Guild Builders Inc. We could omit this line, which would cause the module to be located in the other section of the modules listing. However, we want it to appear in a section of its own, and this line provides a title for that section. description = Custom functions The description line provides the descriptive text that appears alongside the module entry in the modules list. core = 6.x The core entry specifies which major version of Drupal the module is meant to work with, such as 5.x, 6.x, or 7.x. version = "6.x-1.0" Finally, this line specifies the version of our module. It's meant to work with Drupal 6.x and is the first version of our module, and since we will not be releasing a pre-release version (0.x), we'll make it version 1.0. Our file now looks as follows: name = GBI Custompackage = Guild Builders Inc.description = Custom functionscore = 6.xversion = "6.x-1.0" We need to create a directory in which our module will live. We already have the path sites/all/modules in which add-on modules are placed. First, create the path _custom, in which to put our own modules, so that we can find them easily. Put the underscore at the start of the name so that it appears first in the directory list. Next, add the path guildbuilders as the home for this module. So, we now have the path sites/all/modules/_custom/guildbuilders, save our text file to that path as guildbuilders.info.
Read more
  • 0
  • 0
  • 1121
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-installation-and-configuration-microsoft-content-management-server-part-2
Packt
31 Mar 2010
5 min read
Save for later

Installation And Configuration of Microsoft Content Management Server: Part 2

Packt
31 Mar 2010
5 min read
Installing MCMS 2002 Prerequisites Before we can proceed with the installation of MCMS itself, we need to install two prerequisites. Installation of MCMS will be halted if these prerequisites are not met. J# 2.0 redistributable:Elements of MCMS Site Manager require the J# redistributable. Internet Explorer Web Controls for MCMS:Portions of the MCMS Web Author make use of the Internet Explorer Web Controls (IEWC), of which a specific MCMS distribution exists for which compilation is unnecessary. These controls, unlike the standard IEWC, are supported as part of an MCMS installation. As they are a prerequisite for MCMS, IEWC can be utilized within your applications. However, ASP.NET 2.0 offers far richer controls for navigation, as we will see later in this book. J# 2.0 Redistributable We need to install the Visual J# 2.0 Redistributable to enable the installation of the MCMS Site Manager. Download and save the J# 2.0 installer from: http://www.microsoft.com/downloads/details.aspx?familyid=f72c74b3-ed0e-4af8-ae63-2f0e42501be1&displaylang=en Double-click the installer. On the Welcome to Microsoft Visual J# 2.0 Redistributable Package Setup page, click Next. On the End User License Agreement page, check the I accept the terms of the License Agreement checkbox and click Install. Wait while J# 2.0 installs, and when the Setup Complete page appears, click Finish. Internet Explorer Web Controls for MCMS Internet Explorer Web Controls (IEWC) are required by the MCMS Web Author. Download and save the IEWC installer from: http://www.microsoft.com/downloads/details.aspx?FamilyID=FAC6350C-8AD6-4BCA-8860-8A6AE3F64448&displaylang=en Double-click the installer. On the Welcome to the Microsoft Internet Explorer WebControls Setup Wizard page, click Next. On the License Agreement page, select the I Agree radio button and click Next. On the Confirm Installation page, click Next. Wait while the web controls are installed, and when the Installation Complete page appears, click Close. Installing MCMS 2002 SP1a Insert the MCMS 2002 SP1a CD-ROM, and on the splash screen, click Install Components. On the Customer Information page, enter your User Name and Organization along with your Product Key and click Next. On the License Agreement page, click Accept. On the Installation Options page, select the Custom radio button and click Next. On the Custom Installation page, deselect the Site Stager item, and click Next. On the Summary page, click Install. Wait while MCMS 2002 SP1a is installed. On the Installation Completed page, uncheck the Launch MCMS Database Configuration Application checkbox, and click Finish. Remove Temporary Items Now MCMS SP1a is installed, we can tidy up the temporary items we created earlier to trick the installer. Select Start | Run. In the Run dialog, type cmd and click OK. Execute the following commands:cd c:kb915190cscript VS2003ByPass.vbs c:VSTemp remove Use Windows Explorer to delete the folders c:VSTemp and c:kb915190. Install Visual Studio 2005 Insert the Visual Studio 2005 DVD, and on the splash screen, click Install Visual Studio 2005. On the Welcome to the Microsoft Visual Studio 2005 installation wizard page, click Next. On the Start Page, select the I accept the terms of the License Agreement checkbox, enter your Product Key and Name, and click Next. On the Options Page, select the Custom radio button, enter your desired Product install path, and click Next. On the second Options Page, select the Visual C# and Visual Web Developer checkboxes within the Language Tools section, and the Tools checkbox within the .NET Framework SDK section. Ensure that all the other options are not selected and click Install. Feel free to install any additional features you may wish to use. The above selections are all that are required for following the examples in this article. Wait (or take a coffee break) while Visual Studio 2005 is installed. When the Finish Page appears, click Finish. From the Visual Studio 2005 Setup dialog, you can install the product documentation (MSDN Library) if desired, otherwise click Exit. From the Visual Studio 2005 Setup dialog, click Check for Visual Studio Service Releases to install any updates that may be available. Click Exit. Install MCMS SP2 From the Start Menu, click Run. In the Open textbox, enter IISRESET /STOP and click OK. Wait while the IIS Services are stopped. Double-click the SP2 installation package. On the Welcome to Microsoft Content Management Server 2002 SP2 Installation Wizard page, click Next. Select I accept the terms of this license agreement radio button, and click Next. On The wizard is ready to begin the installation page, click Next. Wait while Service Pack 2 is installed. On The Installation Wizard has completed page, click Finish. If prompted, click Yes on the dialog to restart your computer, which will complete the installation. Otherwise, from the Start Menu, click Run. In the Run textbox, enter IISRESET /START and click OK to restart the IIS services. Stopping IIS prior to the installation of SP2 avoids potential problems with replacing locked files during the installation, and can prevent the requirement to reboot.
Read more
  • 0
  • 0
  • 2318

article-image-drupal-and-ubercart-2x-install-ready-made-drupal-theme
Packt
31 Mar 2010
5 min read
Save for later

Drupal and Ubercart 2.x: Install a Ready-made Drupal Theme

Packt
31 Mar 2010
5 min read
Install a ready-made Drupal theme We have to admit that Drupal was not famous for its plethora of available themes. Until recently, the Drupal community was focused on developing the backend, debugging the code, and creating new modules. The release of Drupal 6 made theming much easier and helped the theming community to grow. Now, there are not only thousands of Drupal themes, but also dozens of themes designed and customized especially for Ubercart. Basic principles when choosing a theme Choosing a theme for your online shop is not an easy task. Moreover, it can be even harder considering that you want to promote specific items from your catalog, you need to change first page items often, and you need to rapidly communicate offers and loyalty policies and other business-related stuff. Ubercart-specific themes mostly target the following special areas: Product catalog Shopping cart Product-specific views You should keep these layout regions in mind, while going through the following section on theme selection. Before you search for any kind of theme layout, provide your neurons with enough input to inspire you and help you decide. Perform a quick Google search for online shops in your target market to get some inspiration and track down sites that make you, as a customer, feel comfortable during product searching and navigation. If you decide to search for professional help, a list of existing sites will help you to communicate your preferences much more directly. What better place to search for inspiration and successful practices than Ubercart's live site repository! You will find good practices and see how mostly people like you (without any development background) have solved all the problems that might occur during your search for themes.http://www.ubercart.org/site Next we describe the main user interface components that you should keep in mind when deciding for your online shop: Number of columns: The number of columns depends on the block information you want to provide to your end customers. If you need widgets that display on every page, information about who bought what, and product or kit suggestions, go with three columns. You will find a plethora of two-column Drupal themes and many three-column Drupal themes, while some of them can alternate between two and three columns. Color scheme: From a design perspective, you should choose a color scheme that matches your company logo and business profile. For instance, if your store sells wooden toys, go with something more comic such as rounded corners, but if you are a consulting firm, you should go with something more professional. Many themes let you choose color schemes dynamically; however, always keep in mind that color is a rather easy modification from the CSS. You can get great color combination ideas from COLOURlovers online service (http://www.colourlovers.com/) that match your logo and business colors. Be careful though. If you choose a complex theme with rounded corners, lots of images, and multiple backgrounds, it may be difficult to modify it. Drupal version: Make sure the Drupal theme you choose is compatible with the version of Drupal you are running. Before using a Drupal theme, look up notes on the theme to see if there are any known bugs or problems with it. If you are not a programmer, you do not want a Drupal theme that has open issues. Extra features: Many Drupal themes expose a large set of configuration options to the end users. Various functionality such as post author's visibility or color scheme selection are welcome for managing the initial setup. Moreover, you can change appearance in non-invasive ways for your online marque. Regions available: We have discussed column layouts, but for the Drupal template engine to show its full capabilities and customization, you definitely need multiple regions. The more regions, the more choices you have for where to put blocks of content. Therefore, you can have space for customizing new affiliate ads for instance, or provide information about some special deals, or even configure your main online shop page, as we will see in the next section. Further customization and updates: When you choose your theme, don't just keep the functionality of version 1.0 in mind, but consider all of the future business plans for approaching your target market and raising sales figures. Make a three-year plan and try to visualize any future actions that should be taken into account from day one. Although you can change themes easily, you are better off choosing a more flexible theme ahead of time than having to change the theme as your website grows. Always bear in mind that the famous razor of Occam also applies to online shop theme design. Keep it simple and professional by choosing simple layouts, which allow ease of use for the end user and ease further customize designs and themes (changing colors, adding a custom image header, and so on). Before you start, clearly define your timeline, risks, total theme budget, and skills. Theming is usually 25-40% of the budget of an entire online shop project. Drupal's theming engine closely integrates with actual functionality and many features are encapsulated inside the theme itself. There are a number of different ways in which you can get yourself the best theme for your online store. We will go through all these approaches with useful comments on what options best suits your needs.
Read more
  • 0
  • 0
  • 2562

article-image-drupal-and-ubercart-2x-customizing-theme
Packt
31 Mar 2010
3 min read
Save for later

Drupal and Ubercart 2.x: Customizing a theme

Packt
31 Mar 2010
3 min read
Customizing a theme In this section, after we have elected our primary theme, we will go step-by-step customizing it and making it suit our business need. These configurations are necessary even if you choose to hire a designer or buy a ready-made theme. Changing basic elements Every Drupal theme using the template engine produces HTML code from Drupal core objects. Therefore, some content of the final HTML code generated is actually site-wide property such as site slogan, mission, and site name. We will have to change Drupal default settings and provide our business details. To do this, go to Home | Administer | Site configuration and edit the fields as we describe next. If you do not want to provide specific information, for instance if you do not have a corporate slogan, you need not fill this option. Nothing will appear if the attribute is not set to the main page of your online shop. You can edit the following elements: Name: This is your site's name and will be displayed in the site name theme section and can also be a part of the HTML <title> element. E-mail address: A valid e-mail address for your website, used by the mailer functionality during registration, new password requests, notifications, purchases, and all mail communication to your users. E-mail server details that your site uses are placed in your php.ini file. The majority of web hosting solutions have a preconfi gured mail server environment and you will not have to deal with it. Slogan: The slogan of your website. Some themes display a slogan when available. It will also display in the title bar of your user web browser, so if you decide to choose one, do it wisely. Mission: Your site's mission statement or focus. Your mission statement is enabled in your theme settings and requires that the theme supports its display. Footer: This text will be displayed at the bottom of each page. Useful for adding a copyright notice to your pages. You can also use HTML tags to include an image for instance. Anonymous user: The user name for unregistered users is "Anonymous" by default. Drupal gives you the option to change this to something different according to your target user group (for example "New Customer"). Default front page: This setting gives site administrators control over what Drupal-generated content a user sees when they visit a Drupal installation's root directory. We quote from the Drupal documentation section for site configuration: This setting tells Drupal which URL users should be redirected to. It's important to note that the URL is relative to the directory your Drupal installation is in. So, instead of"http://www.example.com/node/83"or"http://www.example.com/drupal_installation_directory/node/83,"it is only necessary to type "node/83". For those not using clean URLs, note that there is no need to type in "?q=" before typing the URL.By default, the "Default front page" is set to "node," which simply displays articles that have been "Promoted to front page." Note that when changing the "Default front page" to something other than "node", nodes that are "Promoted to front page" will no longer appear on the front page. They can however, still be viewed by visiting the relative URL path "node".If the path specified is not a valid Drupal path the user will be confronted with a "Page not found" error. It is not possible to redirect users to any web documents (e.g. a static HTML page) not created by the Drupal site.
Read more
  • 0
  • 0
  • 2001

article-image-drupal-and-ubercart-2x-creating-theme-scratch-using-zen-theme
Packt
31 Mar 2010
4 min read
Save for later

Drupal and Ubercart 2.x: Creating a Theme from Scratch Using the Zen Theme

Packt
31 Mar 2010
4 min read
In the previous article, we showed you the easy way to install and customize a ready-made theme. This solution is good enough for many shop owners, but if you want to use a unique design for your store, the only solution is to build a theme from scratch. We are going to use the Zen Theme, ma ybe the most popular theme for Drupal. Zen is actually not just a simple theme, but rather a theming framework, because it allows the creation of subthemes. Using a subtheme, we can use all of the great code of Zen and apply only our design customizations, using some simple tools and writing only a few lines of code. So, don't be afraid but enjoy the process. Just think how proud you'll feel when you will have finished your amazing frontend for your store. You don't have to be a programming Ninja, all you have to know is some HTML and CSS. If you have no programming experience at all, you can follow some very interesting tutorials at http://www.w3schools.com/. The tools We are going to use some simple and free tools, which are easy to download, install, and use. Some of them are extensions for Firefox, so if you are not using this particular browser, you have to download it first from http://www.getfirefox.com. Firebug This is the first extension for Firefox that we are going to use. It's an open source and free tool for editing, debugging, and monitoring HTML, CSS, and JavaScript in our web pages. Using Firebug, you can understand the structure of an Ubercart page and inspect and edit HTML and CSS on the fly. To install it, go to http://getfirebug.com/, skip the terrifying bug, and click on Install Firebug for Firefox. You will be transferred to the Firefox add-ons page. Click on Add to Firefox. A new window opens with a warning about possible malicious software. It's a common warning when you try to install a Firefox extension, so click on Install now. When the download is completed, click on Restart Firefox. When Firefox restarts, Firebug is enabled. You can activate it by clicking on the little bug icon at the bottom-right corner of the window. When Firebug is activated, it splits the browser window into two parts. The top part is the normal page and the bottom part shows the HTML or CSS code of the whole page, or for a selected element. There, you can inspect or edit the code, make tests, and try different alternatives. It is now possible to use Firebug in Internet Explorer, Opera, or Safari, using Firebug Lite. It's a small JavaScript file and you can download it from http://getfirebug.com/lite.html. ColorZilla ColorZilla is also a Firefox extension. It provides useful tools related to color management, such as eyedropper, color picker, or palette viewer. You can download it from http://www.colorzilla.com/firefox/. Click on Install ColorZilla. A new window opens with a warning about possible malicious software, like we saw in the Firebug installation, so click on Install now and then Restart Firefox. When Firefox restarts, ColorZilla is enabled. You can activate it by clicking on the little eyedropper icon at the bottom left corner of the window. A code editor We need it to write and edit our template and CSS files. There are many freeware applications, such as HTML Kit (http://www.chami.com/html-kit/) and Webocton (http://scriptly.webocton.de/9/34/start/englishpage.html), or commercial applications, such as Ultraedit (http://www.ultraedit.com) or Coda (http://www.panic.com/coda/).
Read more
  • 0
  • 0
  • 1837
article-image-drupal-and-ubercart-2x-new-approach-drupal-theming
Packt
31 Mar 2010
3 min read
Save for later

Drupal and Ubercart 2.x: A new Approach to Drupal Theming

Packt
31 Mar 2010
3 min read
Fusion Theming System with Skinr module At the end of this article, we're going to give you a brief reference to the Fusion Theming System. It was introduced only a few months ago and it's still under heavy development. It's a base theme, meaning that you can create your own subthemes easily, using the Fusion Starter, a commented starter theme created especially for this reason. It uses a 960px or fluid 16-column grid, and its main advantage is that, with the help of Skinr module, it creates l ayout and style confi guration options that the site administrator can control using the website's User Interface, without messing with CSS. So, let's see how to install it, and how to use it for simple customizations. First navigate to http://drupal.org/project/skinr, and right after you download the module, upload and unzip to your site folder (/sites/all/modules). Then, activate the module from Administration | Site building | Modules. Navigate to http://drupal.org/project/fusion, and right after you download the theme, upload it and unzip it to your site folder (/sites/all/themes). Then, go to Administration | Site building | Themes, enable both Fusion Core and Fusion Starter themes and set the Fusion Starter theme as the default one. Browse to admin | build | themes | settings | fusion_starter to configure the settings of Fusion Starter theme. There you will find the default settings of every Drupal theme, such as logo image settings or shortcut icon settings. However, there is also a new section, named Fusion theme settings. There, you can easily change the basic styles and the layout of your theme, such as font family, font size, fixed or fluid layout without using any CSS at all. Click on Save configuration to store your settings. Now, if you hover the cursor over any block of your site, you will see a new icon. Clicking on it allows you to configure the properties of this block. You can change the width of the block, the block position, the content alignment, and apply custom styles to the elements of the block, such as padding, border, equal heights, or multi-column menus. There are also special settings for every content type. For example, if you go to Administer | Content Management | Content Types | Product, you will see two new sections, named Skinr node settings and Skinr comment settings, where you can apply custom styles to the product page and the product comments. If you want to create your own custom styles for your theme, and present them in the User Interface, you have to study the documentation of the Skinr module, available at http://www.drupal.org/node/578574.
Read more
  • 0
  • 0
  • 4042

article-image-customizing-layout-themes-php-nuke
Packt
31 Mar 2010
23 min read
Save for later

Customizing Layout with Themes in PHP-Nuke

Packt
31 Mar 2010
23 min read
Creating a PHP-Nuke theme gives your site its own special look, distinguishing it from other PHP-Nuke-created sites and offers an effective outlet for your creative talents. Creating a theme requires some knowledge of HTML, confidence in working with CSS and PHP, but most important is some imagination and creativity! Unlike the tasks we have tackled in previous articles, where we have been working exclusively through a web browser to control and configure PHP-Nuke, working with themes is the start of a new era in your PHP-Nuke skills; editing the code files of PHP-Nuke itself. Fortunately, the design of PHP-Nuke means that our theme work won't be tampering with the inner workings of PHP-Nuke. However, becoming confident in handling the mixture of HTML and PHP code that is a PHP-Nuke theme will prepare you for the more advanced work ahead, when we really get to grips with PHP-Nuke at the code level. In this article, we will look at: Theme management Templates in themes Changing the page header Working with the stylesheet Changing blocks Changing the format of stories What Does a Theme Control? Despite the fact that we say 'themes control the look and feel of your site', a theme does not determine every aspect of the page output. PHP-Nuke is an incredibly versatile application, but it cannot produce every website imaginable. Appearance First of all, the appearance of the page can be controlled through the use of colors, fonts, font sizes, weights, and so on. This can either be done through the use of CSS styles or HTML. You can also add JavaScript for fancier effects, or even Flash animations, Java applets, or sounds—anything that you can add to a standard HTML page. Graphical aspects of the page such as the site banner, background images, and so on, are under the care of the theme. There are also some modules that allow their standard graphical icons to be overridden with images from a theme. Page Layout Roughly speaking, a PHP-Nuke page consists of three parts; the top bit, the bit in the middle, and the bit at the bottom! The top bit—the header—usually contains a site logo and such things as a horizontal navigation bar for going directly to important parts of your site. The bottom bit—the footer—contains the copyright message. In between the header and the footer, the output is usually divided into three columns. The left-hand column typically contains blocks, displayed one of top each other, the middle column contains the module output, and the right-hand column contains more blocks. The layout of these columns (their width for example) is controlled by the theme. You may have noticed that the right-hand column is generally only displayed on the homepage of a PHP-Nuke site; this too, is something that is controlled by the theme. The appearance of the blocks is controlled by the theme; PHP-Nuke provides the title of the block and its content, and the theme will generally 'frame' these to produce the familiar block look. The theme also determines how the description of stories appears on the homepage. In addition, the theme determines how the full text of the story, its extended text, is displayed. We've talked about how the theme controls the 'look' of things. The theme also allows you to add other site-related data to your page; for example the name of the site can appear, and the site slogan, and you can even add such things as the user's name with a friendly welcome message. Theme Management Basically, a theme is a folder that sits inside the themes folder in your PHP-Nuke installation. Different themes correspond to different folders in the themes folder, and adding or removing a theme is as straightforward as adding or removing the relevant folder from the themes folder. By default, you will find around 14 themes in a standard PHP-Nuke installation. DeepBlue is the default theme. Themes can be chosen in one of two ways: By the administrator: You can simply select the required theme from the General Site Info panel of the Site Preferences administration menu and save the changes. The theme selected by the administrator is the default theme for the site and will be seen by all users of the site, registered or unregistered. By the user: Users can override the default theme set by the administrator from the Themes option of the Your Account module. This sets a new, personal, theme that will be displayed to that user. Note that this isn't a theme especially customized for that user; it is just one chosen from the list of standard themes installed on your site. Unregistered visitors do not have an option to choose a theme; they have to become registered users. Theme File Structure Let's start with the default theme, DeepBlue. If you open up the DeepBlue folder within the themes folder in the root of your PHP-Nuke installation, you will find three folders and two files. The three folders are: forums: This folder contains the theme for the Forums module. This is not strictly a requirement of a PHP-Nuke theme, and not every PHP-Nuke theme has a forums theme. The Forums module (otherwise known as phpBB) has its own theme 'engine'. The purpose of including a theme for the forums is that you have consistency between the rest of your PHP-Nuke display and the phpBB display. images: This folder contains the image files used by your theme. These include the site logo, background images, and graphics for blocks among others. As mentioned earlier, within this folder can be other folders containing images to override the standard icons. style: This folder contains the CSS files for your theme. Usually, there is one CSS file in the style folder, style.css. Each theme will make use of its style.css file, and this is the file into which we will add our style definitions when the time comes. Of the two files, index.html is simply there to prevent people browsing to your themes folder and seeing what it contains; visiting this page in a browser simply produces a blank page. It is a very simple security measure. The themes.php file is a PHP code file, and is where all the action happens. This file must always exist within a theme folder. We will concentrate on this file later when we customize the theme. In other themes you will find more files; we will look at these later. Installing a New Theme Installing and uninstalling themes comes down to adding or removing folders from the themes folder, and whenever a list of available themes is presented, either in the Site Preferences menu or the Your Accounts module, PHP-Nuke refreshes this list by getting the names of the folders in the themes folder. You will find a huge range of themes on the Web. For example, there is a gallery of themes at: http://nukecops.com/modules.php?set_albumName=packs&op=modload&name=Gallery& file=index&include=view_album.php Many of these are themes written for older versions of PHP-Nuke, but most are still compatible with the newer releases. There is also a live demonstration of some themes at: http://www.portedmods.com/styles/ On this page you can select the new theme and see it applied immediately, before you download it. Removing an Existing Theme To remove a theme from your PHP-Nuke site you simply remove the corresponding folder from the themes folder, and it will no longer be available to PHP-Nuke. However, you should be careful when removing themes—what if somebody is actually using that theme? If a user has that theme selected as their personal theme, and you remove that theme, then that user's personal theme will revert to the default theme selected in Site Preferences. If you remove the site's default theme, then you will break your site! Deleting the site's default theme will produce either a blank screen or messages like the following when you attempt to view your site. Warning: head(themes/NonExistentTheme/theme.php)[function.head]: failed to create stream:No such file or directory in c:nukehtmlheader.php on line 31 The only people who can continue to use your site in this situation are those who have selected a personal theme for themselves—and only if that theme is still installed. To correct such a faux pas, make a copy of one of the other themes in your themes folder (unless you happen to have a copy of the theme you just deleted elsewhere), and rename it to the name of the theme you just deleted. In conclusion, removing themes should only be a problem if you somehow manage to remove your site's default theme. For users who have selected the theme you just removed, their theme will revert to the default theme and life goes on for them. A final caveat about the names of theme folders; do not use spaces in the names of the folders in the themes folder—this can lead to strange behavior when the list of themes is displayed in the drop-down menus for users to select from. From an Existing Theme to a New Theme We'll create a new theme for the Dinosaur Portal by making changes to an existing theme. This will not only make you feel like the theme master, but it will also serve to illustrate the nature of the theme-customization problem. We'll be making changes all over the place—adding and replacing things in HTML and PHP files—but it will be worth it. Another thing to bear in mind is that we're creating a completely different looking site without making any changes to the inner parts of PHP-Nuke. At this point, all we are changing is the theme definition. The theme for the Dinosaur Portal will have a warm, tropical feel to it to evoke the atmosphere of a steaming, tropical, prehistoric jungle, and will use lots of orange color on the page. First of all, we need a theme on which to conduct our experiments. We'll work on the 3D-Fantasy theme. Starting Off The first thing we will do is to create a new theme folder, which will be a copy of the 3D-Fantasy theme. Open up the themes folder in your file explorer, and create a copy of the 3D-Fantasy folder. Rename this copy as TheDinosaurPortal. Now log into your site as testuser, and from the Your Account module, select TheDinosaurPortal as the theme. Your site will immediately switch to this theme, but it will look exactly like 3D-Fantasy, because, at the moment, it is! You will also need some images from the code download for this article; you will find them in the SiteImages folder of this article's code. Replacing Traces of the Old Theme The theme that we are about to work on has many occurrences of 3D-Fantasy in a number of files, such as references to images. We will have to remove these first of all, or else our new theme will be looking in the wrong folder for images and other resources. Open each of the files below in your text editor, and replace every occurrence of 3D-Fantasy with TheDinosaurPortal in a text editor, we'll use Wordpad. "You can use the replace functionality of your editor to do this. For example, in Wordpad, select Edit | Replace; enter the text to be replaced, and then click on Replace All to replace all the occurrences in the open file. After making all the changes, save each file: blocks.html footer.html header.html story_home.html story_page.html theme.php tables.php Templates and PHP Files We've just encountered two types of file in the theme folder—PHP code files (theme.php and tables.php) and HTML files (blocks.html, footer.html, and so on). Before we go any further, we need to have a quick discussion of what roles these types of file play in the theme construction. PHP Files The PHP files do the main work of the theme. These files contain the definitions of some functions that handle the display of the page header and how an individual block or article is formatted, among other tasks. These functions are called from other parts of PHP-Nuke when required. We'll talk about them when they are required later in the article. Part of our customization work will be to make some changes to these functions and have them act in a different way when called. Historically, the code for a PHP-Nuke theme consisted of a single PHP file, theme.php. One major drawback of this was the difficulty you would have in editing this file in the 'design' view of an HTML editor. Instead of seeing the HTML that you wished to edit, you probably wouldn't see anything in the 'design' view of most HTML editors, since the HTML was inextricably intertwined with the PHP code. This made creating a new theme, or even editing an existing theme, not something for the faint-hearted—you had to be confident with your PHP coding to make sure you were changing the right places, and in the right way. The theme.php file consists of a number of functions that are called from other parts of PHP-Nuke when required. These functions are how the theme does its work. One of the neat appearances in recent versions of PHP-Nuke is the use of a 'mini-templating' engine for themes. Not all themes make use of this method (DeepBlue is one theme that doesn't), and that is one of the reasons we are working with 3D-Fantasy as our base theme, since it does follow the 'templating' model. Templates The HTML files that we modified above are the theme templates. They consist of HTML, without any PHP code. Each template is responsible for a particular part of the page, and is called into action by the functions of the theme when required. One advantage of using these templates is that they can be easily edited in visual HTML editors, such as Macromedia's Dreamweaver, without any PHP code to interfere with the page design. Another advantage of using these templates is to separate logic from presentation. The idea of a template is that it should determine how something is displayed (its presentation). The template makes use of some data supplied to it, but acquiring and choosing this data (the logic) is not done in the template. The template is processed or evaluated by the 'template engine', and output is generated. The template engine in this case is the theme.php file. To see how the template and PHP-Nuke 'communicate', let's look at an extract from the header.html file in the 3D-Fantasy folder: <a href="index.php"> <img src="themes/3D-Fantasy/images/logo.gif" border="0" alt="Welcome to $sitename" align="left"></a> The $sitename text (shown highlighted) is an example of what we'll call a placeholder. There is a correspondence between these placeholders and PHP variables that have the same name as the placeholder text. Themes that make use of this templating process more or less replace any text beginning with $ in the template by the value of the corresponding PHP variable. This means that you can make use of variables from PHP-Nuke itself in your themes; these could be the name of your site ($sitename), your site slogan, or even information about the user. In fact, you can add your own PHP code to create a new variable, which you can then display from within one of the templates. To complete the discussion, we will look at how the templates are processed in PHP-Nuke. The code below is a snippet from one of the themeheader() function in the theme.php file. This particular snippet is taken from the 3D-Fantasy theme. function themeheader(){ global $user, $banners, $sitename, $slogan, $cookie, $prefix, $anonymous, $db;... code continues ....$tmpl_file = "themes/3D-Fantasy/header.html";$thefile = implode("", file($tmpl_file));$thefile = addslashes($thefile);$thefile = "$r_file="".$thefile."";";eval($thefile);print $r_file;... code continues .... The processing starts with the line where the $tmpl_file variable is defined. This variable is set to the file name of the template to be processed, in this case header.html. The next line grabs the content of the file as a string. Let's suppose the header.html file contained the text You're welcomed to $sitename, thanks for coming!. Then, continuing in the code above, the $thefile variable would eventually hold this: $r_file = " You're welcomed to $sitename, thanks for coming!"; This looks very much like a PHP statement, and that is exactly what PHP-Nuke is attempting to create. The eval() function executes the statement; it defines the variable $r_file as above. This is equivalent to putting this line straight into the code: $r_file = " You're welcomed to $sitename, thanks for coming!"; If this line were in the PHP code, the value of the $sitename variable will be inserted into the string, and this is exactly how the placeholders in the templates are replaced with the values of the corresponding PHP variables. This means that the placeholders in templates can only use variables accessible at the point in the code where the template is processed with the eval() function. This means any parameters passed to the function at the time—global variables that have been announced with the global statement or any variables local to the function that have been defined before the line with the eval() function. This does mean that you will have to study the function processing the template to see what variables are available. In the examples in this article we'll look at the most relevant variables. The templates do not allow for any form of 'computation' within them; you cannot use loops or call PHP functions. You do your computations 'outside' the template in the theme.php file, and the results are 'pulled' into the template and displayed from there. Now that we're familiar with what we're going to be working with, let's get started. Changing the Page Header The first port of call will be creating a new version of the page header. We will make these customizations: Changing the site logo graphic Changing the layout of the page header Adding a welcome message to the user, and displaying the user's avatar Adding a drop-down list of topics to the header Creating a navigation bar Time For Action—Changing the Site Logo Graphic Grab the <>ilogo.gif file from the SiteImages folder in the code download. Copy it to the themes/TheDinosaurPortal/images folder, overwriting the existing logo.gif file. Refresh the page in your browser. The logo will have changed! What Just Happened? The logo.gif file in the images folder is the site logo. We replaced it with a new banner, and immediately the change came into effect. Time For Action—Changing the Site Header Layout In the theme folder is a file called header.html. Open up this file in a text editor, we'll use Wordpad. Replace all the code in this file with the following: <!-- Time For Action—Changing the Site Header Layout --><table border="0" cellspacing="0" cellpadding="6" width="100%" bgcolor="#FFCC33"> <tr valign="middle"> <td width="60%" align="right" rowspan="2"> <a href="index.php"><img src="themes/$GLOBALS[ThemeSel]/images/logo.gif" border="1" alt="Welcome to $sitename"> </a></td> <td width="40%" colspan="2"> <p align="center"><b>WELCOME TO $sitename!</b></td> </tr> <tr> <td width="20%">GAP</td> <td width="20%">GAP</td> </tr></table><!-- End of Time for Action -->$public_msg<br><table cellpadding="0" cellspacing="0" width="99%" border="0" align="center" bgcolor="#ffffff"><tr><td bgcolor="#ffffff" valign="top"> Save the header.html file. Refresh your browser. The site header now looks like this: What Just Happened? The header.html file is the template responsible for formatting the site header. Changing this file will change the format of your site header. We simply created a table that displays the site logo in the left-hand column, a welcome message in the right-hand column, and under that, two GAPs that we will add more to in a moment. We set the background color of the table to an orange color (#FFCC33). We used the $sitename placeholder to display the name of the site from the template. Note that everything after the line: <!-- End of Time for Action --> in our new header.html file is from the original file. (The characters here denote an HTML comment that is not displayed in the browser). This is because the end of the header.html file starts a new table that will continue in other templates. If we had removed these lines, the page output would have been broken. There was another interesting thing we used in the template, the $GLOBALS[ThemeSel] placeholder: <a href="index.php"><img src="themes/$GLOBALS[ThemeSel]/images/logo.gif" ThemeSel is a global variable that holds the name of the current theme—it's either the default site theme or the user's chosen theme. Although it's a global variable, using just $ThemeSel in the template would give a blank, this is because it has not been declared as global by the function in PHP-Nuke that consumes the header.html template. However, all the global variables can be accessed through the $GLOBALS array, and using $GLOBALS[ThemeSel] accesses this particular global variable. Note that this syntax is different from the way you may usually access elements of the $GLOBALS array in PHP. You might use $GLOBALS['ThemeSel'] or $GLOBALS["ThemeSel"]. Neither of these work in the template so we have to use the form without the ' or ". Time For Action—Fixing and Adding the Topics List Next we'll add the list of topics as a drop-down box to the page header. The visitor will be able to select one of the topics from the box, and then the list of stories from that topic will be displayed to them through the News module. Also, the current topic will be selected in the drop-down box to avoid confusion. This task involves fixing some bugs in the current version of the 3D-Fantasy theme. First of all, open the theme.php file and find the following line in the themeheader() function definition: $topics_list = "<select name="topic" onChange='submit()'>n"; Replace this line with these two lines: global $new_topic;$topics_list = "<select name="new_topic" onChange='submit()'>n"; If you move a few lines down in the themeheader() function, you will find this line: if ($topicid==$topic) { $sel = "selected "; } Replace $topic with $new_topic in this line to get: if ($topicid==$new_topic) { $sel = "selected "; } Save the theme.php file. Open the header.html file in your text editor, and where the second GAP is, make the modifications as shown below: <td width="20%">GAP</td> <td width="20%"><form action="modules.php?name=News&new_topic" method="post"> Select a Topic:<br>$topics_list</select></form></td></tr></table><!-- End of Time for Action --> Save the header.html file. Refresh your browser. You will see the new drop-down box in your page header: What just Happened? The themeheader() function is the function in theme.php responsible for processing the header.html template, and outputting the page header. The $topics_list variable has already been created for us in the themeheader() function, and can be used from the header.html template. It is a string of HTML that defines an HTML select drop-down list consisting of the topic titles. However, the first few steps require us to make a change to the $topics_list variable, correcting the name of the select element and also using the correct variable to ensure the current topic (if any) is selected in the drop-down box. The select element needs to have the name of new_topic, so that the News module is able to identify which topic we're after. This is all done with the changes to the theme.php file. First, we add the global statement to access the $new_topic variable, before correcting the name of the select element: global $new_topic;$topics_list = "<select name="new_topic" onChange='submit()'>n"; The next change we made is to make sure we are looking for the $new_topic variable, not the $topic variable, which isn't even defined: if ($topicid==$new_topic) { $sel = "selected "; } Now the $topics_list variable is corrected, all we have to do is add a placeholder for this variable to the header.html template, and some more HTML around it. We added the placeholder for $topics_list to display the drop-down list, and a message to go with it encouraging the reader to select a topic into one of the GAP table cells we created in the new-look header. The list of topics will be contained in a form tag, and when the user selects a topic, the form will be posted back to the server to the News module, and the stories in the selected topic will be displayed. (The extra HTML that handles submitting the form is contained with the $topics_list variable.) <form action="modules.php?name=News" method="post">Select a Topic:<br>$topics_list All that remains now is to close the select tag—the tag was opened in the $topics_list variable but not closed—and then close the form tag: </select></form> When the page is displayed, this is the HTML that PHP-Nuke produces for the topics drop-down list: <form action="modules.php?name=News&new_topic" method="post">Select a Topic:<br><select name="topic" onChange='submit()'><option value="">All Topics</option><option value="1">The Dinosaur Portal</option><option value="2">Dinosuar Hunting</option></select></form>
Read more
  • 0
  • 0
  • 6792

article-image-installation-and-configuration-microsoft-content-management-server-part-1
Packt
31 Mar 2010
10 min read
Save for later

Installation And Configuration of Microsoft Content Management Server: Part 1

Packt
31 Mar 2010
10 min read
In this first article of the series we walk you through the installation and configuration of MCMS 2002 Service Pack 2 (SP2), along with SQL Server 2005 and Visual Studio 2005 on a single developer workstation. In addition, we will cover the changes to the SP2 development environment and a number of tips for working within it. This article assumes you are already familiar with the steps necessary to install MCMS 2002 SP1a as detailed in depth in the previous book, Building Websites with Microsoft Content Management Server from Packt Publishing, January 2005 (ISBN 1-904811-16-7). There are two approaches to setting up a development environment for SP2: upgrading from a previous SP1a installation, or starting from scratch and building a fresh installation including SP2. We will cover both approaches in this article. For example, we will be using Windows XP Professional SP2 as our development workstation. However, where there are significant differences for a Windows Server 2003 SP1 machine, those will be noted. All examples assume the logged-on user is a local machine administrator. Overview of MCMS 2002 Service Pack 2 As with other Microsoft Service Packs, one major purpose of SP2 is to provide an integrated installation for a large number of previously released hotfixes. SP2 will now be a prerequisite for any future hotfix releases. While many customers will view SP2 as a regular Service Pack, it also offers support for the latest development platform and tools from Microsoft, namely SQL Server 2005, .NET Framework 2.0 and ASP.NET 2.0, and Visual Studio 2005: SQL Server 2005: MCMS databases can be hosted by SQL Server 2005, offering numerous advantages in security, deployment, and most significantly, performance. .NET Framework 2.0 and ASP.NET 2.0: MCMS applications can be hosted within the .NET Framework 2.0 runtime, and take advantage of v2.0 language features as well as security and performance improvements. In addition, many of the new features of ASP.NET 2.0 such as master pages, themes, navigation, and Membership Providers can be used. This provides numerous opportunities to both refine and refactor MCMS applications, and is the primary focus. Visual Studio 2005: MCMS applications can be developed using Visual Studio 2005. One of the greatest advantages here is the use of the new HTML-editing and designer features in VS.NET along with improved developer productivity. If you wish, you can continue to use SQL Server 2000 for your MCMS applications. However, we recommend upgrading to SQL Server 2005 and will use it throughout the examples in this book. There are numerous versions or Stock Keeping Units (SKUs) of Visual Studio 2005, all of which are supported with SP2. Throughout the examples in this book, we will be using Visual Studio 2005 Professional Edition. Unfortunately, SP2 is not a cumulative service pack and therefore requires an existing installation of SP1a. Likewise, there is no slipstreamed distribution of SP2. The SP2 distribution is suitable for all editions of MCMS. Mainly due to the extremely fast preparation and release of SP2 following the Release to Manufacturing (RTM) of .NET 2.0, Visual Studio 2005, and SQL Server 2005, the Microsoft installation information (KB906145) isn’t particularly well documented and is somewhat confusing. Rest assured that the guidance in this article has been verified and tested for both installation scenarios covered. Obtaining MCMS Service Pack 2 MCMS SP2 can be downloaded from the following locations: English:http://www.microsoft.com/downloads/details.aspx?FamilyId=3DE1E8F0-D660-4A2B-8B14-0FCE961E56FB&displaylang=en French:http://www.microsoft.com/downloads/details.aspx?FamilyId=3DE1E8F0-D660-4A2B-8B14-0FCE961E56FB&displaylang=fr German:http://www.microsoft.com/downloads/details.aspx?FamilyId=3DE1E8F0-D660-4A2B-8B14-0FCE961E56FB&displaylang=de Japanese:http://www.microsoft.com/downloads/details.aspx?FamilyId=3DE1E8F0-D660-4A2B-8B14-0FCE961E56FB&displaylang=ja Installation Approach We cover both an in-place upgrade to SP2 and a fresh installation in this chapter. Which approach you take is down to your specific requirements and your current, if any, MCMS installation. If you wish to perform a fresh install, skip ahead to the Fresh Installation of Microsoft Content Management Server 2002 Service Pack 2 section, later in this article Upgrading to Microsoft Content Management Server 2002 Service Pack 2 This section details the steps required to upgrade an existing installation of MCMS SP1a, which includes the Developer Tools for Visual Studio.NET 2003 component. The outline process for an upgrade is as follows: Install Visual Studio 2005. Install MCMS 2002 Service Pack 2. Configure the development environment. (Optional) Prepare the MCMS database for SQL Server 2005. (Optional) Upgrade SQL Server. (Optional) Install SQL Server 2005 Service Pack 1. We will perform all steps while logged on as a local machine administrator. Installing Visual Studio 2005 Visual Studio 2005 can be installed side by side with Visual Studio.NET 2003. Once we have completed the upgrade, we can remove Visual Studio.NET 2003 if we wish to only develop MCMS applications using SP2 and ASP.NET 2.0. Insert the Visual Studio 2005 DVD, and on the splash screen, click Install Visual Studio 2005. On the Welcome to the Microsoft Visual Studio 2005 installation wizard page, click Next. On the Start Page, select the I accept the terms of the License Agreement checkbox, enter your Product Key and Name, and click Next. On the Options Page, select the Custom radio button, enter your desired Product install path, and click Next. On the second Options page, select the Visual C# and Visual Web Developer checkboxes within the Language Tools section, and the Tools checkbox within the .NET Framework SDK section. Click Install. Feel free to install any additional features you may wish to use. The above selections are all that’s required to follow the examples in this book. Wait (or take a coffee break) while Visual Studio 2005 is installed. When the Finish Page appears, click Finish. From the Visual Studio 2005 Setup dialog, you can choose to install the Product Documentation (MSDN Library) if desired. From the Visual Studio 2005 Setup dialog, click Check for Visual Studio Service Releases to install any updates that may be available. Click Exit. Installing MCMS 2002 Service Pack 2 Next, we will install MCMS Service Pack 2. From the Start Menu, click Run. In the Open textbox, enter IISRESET /STOP and click OK. Wait while the IIS Services are stopped. Double-click the SP2 installation package. On the Welcome to Microsoft Content Management Server 2002 SP2 Installation Wizard page, click Next. Select the I accept the terms of this license agreement radio button, and click Next. On the ready to begin the installation page, click Next. Wait while Service Pack 2 is installed. During installation you may be prompted for the MCMS 2002 SP1a CD-ROM. Once The Installation Wizard has completed page, click Finish. If prompted, click Yes on the dialog to restart your computer, which will complete the installation. Otherwise, from the Start Menu, click Run. In the Open textbox, enter IISRESET /START and click OK to restart the IIS services. Stopping IIS prior to the installation of SP2 avoids potential problems with replacing locked files during the installation, and can prevent the requirement to reboot. Configuring the Development Environment Before continuing, a few additional steps are required to configure the development environment. We will: Configure the shortcut that opens Site Manager to bypass the Connect To dialog. Install the MCMS website and item templates in Visual Studio. Site Manager Shortcut During the installation of SP2 the Site Manager Start-menu shortcut will be overwritten. To configure Site Manager to bypass the Connect To dialog, take the following steps: Select Start | All Programs | Microsoft Content Management Server. Right-click the Site Manager shortcut and click Properties. In the Target textbox, replace"C:Program FilesMicrosoft Content Management ServerClientNRClient.exe" http:///NR/System/ClientUI/login.aspwith"C:Program FilesMicrosoft Content Management ServerClientNRClient.exe" http://localhost/NR/System/ClientUI/login.asp. Click OK. It is possible to configure many different Site Manager shortcuts pointing to different MCMS entry points. However, for this book we will only use the entry point on localhost, which is the only supported configuration for MCMS development. Visual Studio Templates The installation of MCMS Service Pack 2 automatically registers the MCMS developer tools such as MCMS Template Explorer in Visual Studio 2005. However, before we can create MCMS applications with Visual Studio, we need to make the website and item templates available. Select Start | All Programs | Microsoft Visual Studio 2005 | Visual Studio Tools | Visual Studio 2005 Command Prompt. Execute the following commands, replacing MCMS_INSTALL_PATH with the install location of MCMS (usually C:Program FilesMicrosoft Content Management Server) and PATH_TO_MY_DOCUMENTS_FOLDER with the location of your My Documents folder: xcopy "MCMS_INSTALL_PATHDevToolsNewProjectWizards80Visual WebDeveloper" "PATH_TO_MY_DOCUMENTS_FOLDERVisual Studio 2005TemplatesProjectTemplatesVisual Web Developer"/E xcopy "MCMS_INSTALL_PATHDevToolsNewItemWizards80Visual WebDeveloper" "PATH_TO_MY_DOCUMENTS_FOLDERVisual Studio 2005TemplatesItemTemplatesVisual Web Developer"/E Execute the following command to register the templates with VisualStudio 2005: devenv /setup Close the command prompt. This completes the steps to upgrade to SP2, and our environment is now ready for development! We can test our installation by viewing the version number in the SCA, connecting with Site Manager, or by using the Web Author. Of course, any existing MCMS web applications will at this time still be hosted by.NET Framework v1.1. It is not necessary at this stage to register ASP.NET as detailed in the Microsoft Installation Instructions (KB 906145). This registration was performed by the Visual Studio 2005 installer. Additionally it is unnecessary to configure IIS to use ASP.NET 2.0 using the Internet Information Services Snap-In, as Visual Studio 2005 automatically sets this option on each MCMS website application created.However, if you are installing on Windows Server 2003, you must configure the Virtual Website root and the MCMS Virtual Directory to use ASP.NET 2.0, as it is not possible to use two versions of ASP.NET within the same Application Pool. The ActiveX controls that are part of HtmlPlaceholderControl are updated with SP2. Therefore you will be prompted to install this control when first switching to edit mode.If you have pre-installed the controls using regsvr32 or Group Policy as detailed at http://download.microsoft.com/download/4/2/5/4250f79a-c3a1-4003-9272-2404e92bb76a/MCMS+2002+-+(complete)+FAQ.htm#51C0CE4B-FC57-454C-BAAE-12C09421B57B, you might also be prompted, and you will need to update your distribution for the controls. At this stage you can also choose to upgrade SQL Server or move forward. Preparing the MCMS Database for SQL Server 2005 Before upgrading our SQL Server installation to SQL Server 2005, we need to prepare the MCMS database so that it is compatible with SQL Server 2005. Request the following MCMS hotfix from Microsoft:http://support.microsoft.com/?kbid=913401. Run the hotfix executable to extract the files to a local folder, e.g. c:913401. Copy both of the files (_dca.ini and _sp1aTosp2upgrade.sql) to the MCMS SQL install folder (typically c:Program FilesMicrosoft Content Management ServerServerSetup FilesSQL Install). Overwrite the existing files. Delete the temporary folder. Select Start | Microsoft Content Management Server | Data Configuration Application. On the splash screen, click Next. In the Stop Service? dialog, click Yes. On the Select MCMS Database page, click Next. In the Upgrade Required dialog, click Yes. On the Upgrade Database page, click Next. In the Add an Administrator dialog, click No. On the Database Configuration Application page, uncheck the Launch the SCA Now checkbox and click Finish.
Read more
  • 0
  • 0
  • 2364
article-image-making-sale-optimizing-product-pages-using-magento-13
Packt
31 Mar 2010
6 min read
Save for later

Making the Sale by Optimizing Product Pages using Magento 1.3

Packt
31 Mar 2010
6 min read
When shoppers land on a product page, you want that page to present the product in the best possible way. The product page should entice, inform, and entertain your shoppers. Adding custom options In Magento, a custom option is a field that enables your customer to specify something that he/she wants customized. For example, suppose you sell sports trophies that can be engraved with the name of the event and the winning team then you would add a custom option to that product, where the shopper enters the text to engrave. If you offer a style of shirt in different sizes and each size is a different product with its own stock number, then that is a configurable product. If you offer a style of shirt that is custom-made on demand, and the customer chooses the measurements for that shirt (chest size, sleeve length, neck size, and so on), then that is a simple product with custom options. In the following example, the customer can add his/her initials as a custom option. Selecting any of the options adds a product, with its own SKU, to the customer's order. How to do it... Let's begin with adding the custom option: Log in to your site's backend or Administrative Panel. Select Catalog | Manage Products. The Manage Products page displays. You will see a list of the products in your store. For the product that you want, select the Edit link. The Product Information page displays. The General tab will be selected for you. Select the Custom Options tab. Click the Add New Option button. A new option appears. You will need to fill in the fields to complete this option. In the Title field, add text that will appear next to the option. The text that you see in the example above, "This is an expensive machine..." and "Extra filter cups...", was entered into the Title field. Selecting the input type: Select the input type for this option. Based upon the type you select, other fields will appear. You will be required to fill in these other fields. If you select this Input type... You will also need to specify... Text The maximum number of characters the shopper can enter into the text field or text area. File   The filename extensions that you will allow the shopper to upload. For example, you might supply the shopper with a detailed form to fill out using Adobe Acrobat Reader and then have them upload the form. In that case, you would specify .pdf as the filename extension.   Select   Each of the selections that they can make. You add selections by clicking on the Add New Row button.   Date   Nothing. This just adds a field where the shopper enters a date and/or time.   Selecting the remaining options: The Is Required drop-down menu determines if the customer must select this custom option to order the product. For example, if you're selling custom-made shirts, then you might require the customer to enter measurements into the custom option fields. The Sort Order field determines the order in which the custom options are displayed. They appear from lowest to highest. The Price is a required field. If you set it to zero, then no price will display. Price Type is Fixed if you always charge the same for that option. Setting it to Percent calculates the price for the option based on the price for the product. SKU is not required, but if the option is another product (like extra parts), then you will want to use it. Save the product, and preview it in your store. How it works... Both custom options and configurable products give your customer a choice. But they are not the same. When a customer chooses a configurable product, the customer is ordering a separate product with its own stock number, price, and inventory. When a customer chooses a custom option, the customer is not choosing a different product. Instead, the customer is choosing an additional feature or part for the product. These custom additions can be free or they can have their own price. Each custom option has its own SKU number. There's more... You can get especially creative with the custom option that allows customers to upload files. For example, you can: Enable customers to upload a graphic that you add to the product, such as a graphic that is silkscreened on a laptop's case. Sell a picture printing and framing service. The customer uploads a digital picture, and you print it on high-quality photographic paper and frame it. Supply customers with a detailed form for specifying a product, and then have the customer upload the form as part of their order. Run a contest for the best picture of a customer using a product. Customers upload the picture under the product. You then add the best pictures to a static page on your site. Adding videos, links, and other HTML to product pages You enter the description for a product on the product page under the General tab: While these fields appear to accept only text, they will accept HTML code. This means that you can add almost anything to the product description that you can add to a standard web page. For example, let's embed a video into the Short Description field. How to do it... Navigate to the video site that contains the video you want to embed. In our example, we're embedding a video from YouTube: Clicking on the Embed video link selects the code that we need to put on our product page. Select and copy the code. Log in to Magento's backend, and go to the Product Information page, General tab. Paste the copied code into either of the description fields. Save the product. How it works... The HTML code that you enter into the description field is displayed when the customer views the product. Any valid HTML code will work. In our example, we embedded the video in the Short Description field, which placed it near the top of the page, under Quick Overview: There's more... Using HTML, you can: Embed videos in your product page Add links to your product page Add the manufacturer's graphic to the product description Just remain aware of how much space the Magento layout gives you for the items that you want to put on the page. For example, the code that we copied from www.youtube.com above makes the video 400 pixels wide which is too wide for our Magento page, so we had to change it to 300 pixels.
Read more
  • 0
  • 0
  • 1548

article-image-using-bean-validation-jsr-303-annotations-apache-myfaces-12
Packt
30 Mar 2010
9 min read
Save for later

Using Bean Validation (JSR 303) annotations with Apache MyFaces 1.2

Packt
30 Mar 2010
9 min read
Using annotations in JavaBeans is an elegant way of defining validation rules in a declarative way. Apart from MyFaces ExtVal there are other projects that introduced declarative validation, such as the Hibernate Validator and the Bean Validation Framework for Spring. Some framework developers realized that it would be a good idea to standardize this type of validation. This led to the Bean Validation specification that was developed as JSR 303 in the Java Community Process. Accordingly, Bean Validation will be a standard part of Java EE 6, but it can be used in Java EE 5 by manually including a Bean Validation implementation. One of the benefits of having an official standard for validation is that various user interface frameworks can implement support for this type of validation. For example, JavaServer Faces 2.0 will have support for Bean Validation embedded in it, and other UI frameworks will probably follow But at the moment, we’re still building Java EE 5 and JSF 1.2 applications. And although we can use Bean Validation in Java EE 5, JSF 1.2 doesn’t have Bean Validation support. And that’s where ExtVal comes in. We can use ExtVal to integrate JSR 303 Bean Validation into JSF 1.2 (and even JSF 1.1) projects. This section will discuss some Bean Validation basics and show how to use Bean Validation with ExtVal. Note that we can only cover some basics of Bean Validation here. As Bean Validation is a new standard, there is not much reference documentation available yet. However, some decent documentation comes bundled with Hibernate Validator—the reference implementation of JSR 303. That documentation is also available online at http://docs.jboss.org/hibernate/stable/validator/reference/. As an alternative, the official specification of JSR 303 can be used as documentation. The official specification can be found at http://jcp.org/en/jsr/summary?id=303. Setting up Bean Validation and ExtVal To use Bean Validation, we need a JSR 303 implementation, unless we’re using a Java EE 6 compliant application server. Currently, the only available JSR 303 implementation is the reference implementation, which is Hibernate Validator 4.0. Hibernate Validator can be downloaded from http://www.hibernate.org/subprojects/validator/download.html . We should make sure we download a 4.0 version, as versions before 4.0 do not implement the JSR 303 standard. At the time of writing this article, the latest release is 4.0.2 GA. After downloading Hibernate Validator, we have to add the Bean Validation libraries to our project. All libraries have to be in the shared lib directory of our EAR. We also have to add the libraries that Hibernate Validator depends on. The following table shows a list of libraries that have to be added to our project in order to be able to use the Hibernate Validator. If we had used Maven, these libraries would have been downloaded and added to our project automatically by Maven. Library Description Where to get hibernate-validator-4.0.2.GA.jar The main Hibernate Validator library. Included in the root directory of the Hibernate Validator distribution. validation-api-1.0.0.GA.jar Contains all interfaces and annotations defined by the JSR 303 standard. Included in the lib directory of the Hibernate Validator distribution. slf4j-log4j12-1.5.6.jar slf4j-api-1.5.6.jar log4j-1.2.14.jar jpa-api-2.0.Beta-20090815.jar   Runtime dependencies of Hibernate Validator. Included in the lib directory of the Hibernate Validator distribution. activation-1.1.jar jaxb-api-2.1.jar jaxb-impl-2.1.3.jar stax-api-1.0-2.jar Runtime dependencies for Hibernate Validator. These libraries are only needed if we run Hibernate Validator on a JDK 5 version. So even if we use a Java EE 5 server that runs on a JDK 6, we don't need these libs. Included in the lib/jdk5 directory of the Hibernate Validator distribution. Once we have added the Bean Validation libraries to our project, we have to make sure that we have also added ExtVal’s Bean Validation module to our project. The Bean Validation module is only available from ExtVal version 1.2.3 onwards. See the Setting up ExtVal section for more details. Using Bean Validation annotations The basic usage of Bean Validation is very similar to the use of ExtVal’s Property Validation annotations. There are some differences in the annotations, though. The following table lists all of the annotations that are defined in the Bean Validation specification: Annotation Attributes Description @AssertFalse   Assure that the element that is annotated is false. @AssertTrue   Assure that the element that is annotated is true. @DecimalMin value The value of the annotated element must be a numeric value greater than or equal to the indicated value. The value attribute must be a String that will be interpreted as a BigDecimal string representation. @DecimalMax value The value of the annotated element must be a numeric value less than or equal to the indicated value. The value attribute has the same behavior as the value attribute of the @DecimalMin annotation. @Digits integer, fraction The annotated element must have a numeric value that can't have more integer digits and fraction digits than indicated by the integer and fraction attributes. @Past   Can be applied to java.util.Date and java.util.Calendar elements. The value of the annotated element must be in the past. @Future   Can be applied to java.util.Date and java.util.Calendar elements. The value of the annotated element must be in the future. @Min value Only for integer values. The value of the annotated element must be greater than or equal to the given value. @Max value Only for integer values. The value of the annotated element must be less than or equal to the given value. @NotNull   The annotated value can't be null. @Null   The annotated value must be null. @Pattern regexp, flags Can only be applied to Strings. The annotated String must match the regular expression that is given in the regexp attribute. The flags attribute can be set to an array of Pattern.Flag values, indicating which flags should be set to the java.util.regex.Pattern that will be used to match the value against. Valid flags are UNIX_LINES, CASE_INSENSITIVE, COMMENTS, MULTILINE, DOTALL, UNICODE_CASE, and CANON_EQ. See the JavaDoc documentation of java.util.regex.Pattern for an explanation of the flags. (http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html) @Size min, max Can be applied to Strings, Collections, Maps, and arrays. Verifies that the size of the annotated element is between the given min and max values, min and max included. @Valid   For recursive validation. All annotations are defined in the javax.validation.constraints package. Apart from the attributes mentioned in the previous table, all annotations (except the @Valid annotation) have the following common attributes: message: This attribute can be used to set a custom error message that will be displayed if the constraint defined by the annotation is not met. If we want to set a message bundle key instead of a literal message, we should surround it with braces. So we can set message to either "This value is not valid" or "{inc.monsters.mias.not_valid}". groups: This attribute can be used to associate a constraint with one or more validation processing groups. Validation processing groups can be used to influence the order in which constraints get validated, or to validate a bean only partially. (See http://docs.jboss.org/hibernate/stable/validator/reference/en/html/validator-usingvalidator.html#validator-usingvalidator-validationgroups for more on validation groups.) payload: This attribute can be used to attach extra meta information to a constraint. The Bean Validation standard does not define any standard metadata that can be used, but specific libraries can define their own metadata. This mechanism can be used with ExtVal to add severity information to constraints, enabling the JSF pages to show certain constraint violations as warnings instead of errors. See the Using payloads to set severity levels section for an example of this. OK, now we know which annotations can be used. Let’s see how we can use Bean Validation annotations on our Employee class: // Package declaration and imports omitted for brevitypublic class Employee implements Serializable { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; @Temporal(TemporalType.DATE) @Column(name="BIRTH_DATE") @Past private Date birthDate; @Column(name="FIRST_NAME") private String firstName; @Temporal(TemporalType.DATE) @Column(name="HIRE_DATE") @Past private Date hireDate; @Column(name="JOB_TITLE") @NotNull @Size(min=1) private String jobTitle; @Column(name="LAST_NAME") private String lastName; @Min(value=100) private int salary; @Column(name="KIDS_SCARED") private int kidsScared; @OneToMany(mappedBy="employee") private List<Kid> kids; // Getters and setters and other code omitted.} The Bean Validation annotations are highlighted in the code example. Note that the annotations are applied to the member variables here. Alternatively, we could have applied them to the getter methods. In this example, the birthDate and hireDate are annotated with @Past so that only dates in the past can be set. The jobTitle is set to have a minimum length of one character by the @Size annotation. The salary must have a minimum value of 100, as set by the @Min annotatiion. Reusing validation Bean Validation does not have a solution like the @JoinValidation annotation of ExtVal’s Property Validation module. However, Bean Validation offers other ways to avoid repetitive code and help us reusing validation. This section describes some of the possibilities Inheriting validation Constraints defined on (the properties of) super classes are inherited. This means that if we have a super class called Person, like the following example, our Employee class can inherit the properties—including the annotated constraints—as follows: public class Person { @Size(min=1) private String firstName; @Size(min=1) private String lastName; @Past private Date birthDate; // Getters and setters omitted.} No special actions have to be taken to inherit annotated validation constraints. Using recursive validation We can use the @Valid annotation to use recursive validation (or graph validation as it is called in the JSR 303 specification). The @Valid annotation can be used on single member objects as well as on Collections. If applied to a Collection, all objects in the collection are validated, but null values in the Collection are ignored. For example, we could use this to validate the List of scared Kids that is part of our Employee class, as follows: public class Employee implements Serializable { // Other member variables are left out here. @OneToMany(mappedBy="employee") @Valid private List<Kid> kids; // Getters and setters are omitted.} Now the List of Kids that is referenced by the kidsvariable can only contain valid Kid objects. This means that all Bean Validation constraints that are defined on the Kid class will be checked on all Kid objects in the List.
Read more
  • 0
  • 0
  • 4267
Modal Close icon
Modal Close icon