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
All 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

1797 Articles
article-image-welcoming-your-visitors-creating-attractive-home-pages-and-overview-pages
Packt
31 May 2013
25 min read
Save for later

Welcoming your Visitors: Creating Attractive Home Pages and Overview Pages

Packt
31 May 2013
25 min read
(For more resources related to this topic, see here.) Up to now, you've set up the home page and category overview pages using the default options. But you may have noticed that Joomla offers dozens of options for these page types. Changing these options can completely alter the way content is presented. In fact, different settings can create very different looking pages. To effectively welcome your visitors and entice them to read your valuable content, we'll create a better home page and effective category pages. In the following screenshots, you'll see the page types we're talking about. The basic layout of both home pages and overview pages is similar. On the left-hand side is the example home page in the default Joomla installation, on the right-hand side is an example category overview page found via the About Joomla menu (Using Joomla | Using Extensions | Components | Content Component | Article Category Blog): Why do you need overview pages, anyway? Typically, Joomla will lead your site visitor to a category content in three steps. Between the Main Menu and the actual content, there's a secondary page to show category contents. You can see how this works in the following set of screenshots: A visitor clicks on a menu link. They are taken to an overview page with article previews inviting them to click Read more links. They click to read the full article. As you can see, what's on the home page and the overview pages (and how it's presented) is vitally important to your site. It's the teaser texts, images, and hyperlinks on these pages that offer your visitors a first glimpse of the actual content. Of course, people don't always arrive at your site via the home page. Search engine results might take them directly to any page— including overview pages. One more reason to make those pages as enticing as you can! Overview page, landing page, secondary home page? Joomla doesn't have a name for overview pages. Among web builders they're also known as start pages, category pages, department pages, or landing pages. Whatever you like to call it, it's the same thing: a navigational page that provides an overview of site categories. In this book we'll call them category overview pages. Creating the perfect home – mastering home page layout By default, the homepage of any Joomla site is set up to display the following items: One introductory article text over the full width of the mainbody Three intro texts in three columns As we haven't changed any of the homepage layout settings up to now, the example site homepage has the same layout. This default setup is suited for many types of content-rich sites. But you're certainly not limited to displaying this one particular combination of intro texts and links in the central part of the home page (the "mainbody", as it is called in Joomla). There's a vast amount of choices on how to display content on the home page, and what to display. Changing the way the home page is arranged It's your client on the phone, telling you that—happy as they are with their new site—some CORBA staff members find the home page layout too distracting. They don't like the newspaper look that displays the content columns in different widths. Would you be so kind as to tone things down a little? If you could quickly show them an alternative layout, that would be fine. You hang up and dive into the homepage settings. Time for action – rearranging the layout of articles on the home page You decide to rearrange the items on the home page. Let's say you want a maximum of two intro texts, both in just one column. Apart from this, you would like to show a few hyperlinks to other articles that could be of interest to visitors browsing the home page. You may wonder where Joomla stores the home page settings. As we've seen in previous chapters, menu link settings often determine Joomla's page output—and this also holds for the Home link in the main menu. This menu link is of a specific Menu Item Type, Featured Articles. To change the appearance of the home page, we'll customize the Home menu link settings. Navigate to Menus | Main Menu. In the Menu Manager, click on Home to enter the screen where you can edit the menu link settings. Click the Advanced Options tab. In the Layout Options section, the current settings are shown as follows: These are the "magic numbers" that determine the page lay-out. There's 1 leading article (which means it's displayed in full width), intro articles are shown in 3 columns, and there are 0 links to articles. Change the values as follows: set # Leading Articles to 0, # Intro Articles to 2, # Columns to 1, and # Links to 4. This way just two articles will be shown in a single column and the rest of the featured articles is displayed as a set of hyperlinks. Save your changes and click on View site to see the changes on the frontend. There are now two full-width intro texts. Although you have set # Links to 4, beneath the intro texts only two article links are displayed. This is because up to now only four articles have been assigned to the home page. If you'll assign more articles to the home page, this list will grow to a maximum of four hyperlinks. What just happened? The settings of any menu item allow you to influence the look of the hyperlink's destination page. By default, the Joomla Home link of the main menu is of the Featured Articles Menu Item Type. In this case, you've tweaked the layout options of the Featured Articles menu link to change the home page mainbody. The magic numbers of the Layout Options section are really powerful as different values can completely change the way the page content is displayed. Have a go hero – tweak home page layout options Joomla offers you dozens of settings to customize the home page layout. Navigate to Menus | Main Menu | Home and click the Advanced Options tab to have a look at the different option panels, such as Layout Options. First, you will probably want to set Pagination to Hide. That way, you'll hide the pagination links (< Start Prev Next Last >) that Joomla displays when there are more articles available than can be shown on the home page as intro texts. In our example, the pagination links allow the visitor to navigate to a "second home page", displaying the intro texts of the two hyperlinks in the More articles ... list. Showing pagination links on a home page seems suited for weblog home pages, where visitors expect to be able to browse through possibly long lists of blog entries. On most other types of sites, web users aren't likely to expect multi-page home pages. The options for the Home link (or any other Featured Articles Menu Item Type) allow you to also control exactly what details are shown for every article on the home page. Through the menu link settings you determine whether or not you want to show the author name, publication date, the category name, and much more. These article display settings in the menu link overrule the general settings found through Content | Article Manager | Options. For a full overview of all options available for the Featured Articles Menu Item Type. Adding items to the home page In the More Articles … hyperlink list at the bottom of your home page, two hyperlinks are shown. That's because only four articles are set to display on the home page. To add a couple of articles, navigate to Content | Article Manager. Add any article by clicking on the white star in the Status column to the left-hand side of the article title. The grey star changes to an orange star. In the following example, we've selected a News item (CORBA Magazine Looking for Authors) to be Featured on the homepage: Want to see what this looks like up front? Just click on View Site. The new home page item is shown at the top. All other featured items are now positioned one position lower than before. You'll notice that the Hideous Still Lifes intro text has disappeared as this featured item has now slid down one position, to the list with article hyperlinks. This list now contains three articles instead of two. Another way to add articles to the home page Adding items to the home page takes just a few clicks in the Article Manager Status column. You can also add an individual article to the home page through a setting in the Edit Article screen: under Details, select Featured: Yes. Controlling the order of home page items manually Now that you've reorganized your home page layout, you'll probably want some control over the order of the home page items. To manually set the order, first edit the Home menu link. Click Advanced Options and under Layout Options, make sure Category Order is set to No order: Click Save & Close and go to Content | Featured Articles and set the order as desired. First, set the value of the Sort Order By select box (by default it shows Title) to Ordering. Now you can change the articles order by clicking the three vertical squares to the left-hand side of any article title and dragging the article to another position. The intro texts and links on the home page will now be displayed in the order they have in the Featured Articles screen: What's the use of the Featured Articles screen? In the Featured Articles screen, you can't—as you might have expected—assign items to the Featured status. As you've seen, you can assign articles to the Featured status in the Article Manager (or in the article editing screen). You'll probably use the Featured Articles screen if you want to manually control the order of home page items, or if you want a quick overview of all featured articles. Apart from this, the Featured Articles screen allows you to publish, delete, or archive featured articles—but you can just as easily use the Article Manager for that too. Setting a criteria to automatically order home page items Having full manual control over the order of home page items can be convenient when you have a fixed set of content items that you want to show up on the home page, for example, when you have a corporate site and want to always show your company profile, an introduction to your products, and a link to a page with your address and contact details. However, when your site is frequently updated with new content, you'll probably want Joomla to automatically arrange the home page items to a certain ordering criteria. Again, you can customize this behavior by editing the Home link in the main menu. Its Layout Options allow you to choose from a wide range of ordering methods. Time for action – show the most recent items first The visitors of the CORBA site will probably expect to see the most recently added items on the top of the page. Let's set the Layout Options to organize things accordingly. Navigate to Menus | Main Menu and click the Home link to edit its settings. Under the Advanced Options tab, you'll find the Layout Options offering several ordering options for featured articles. Make sure Category Order is set to No order, to avoid that specific category order settings overruling the article settings you choose. In the Article Order drop-down list, choose Most recent first. As the Date for ordering, select Create Date. When ordering your articles by date, you'll probably want to display the creation date for every article. Navigate to the Article Options panel of the menu link and make sure Show Create Date is set to Show. Click on Save and click on View Site. Now the most recent items are shown first on the home page: What just happened? You've told Joomla to put the most recently added items first on the home page. If you want, you can check this by opening a featured article, changing its created date to Today, and saving your changes; this article will immediately be displayed at the top in the home page layout. If you prefer to order home page items in another way (for example, alphabetically by title), you can do this by selecting the appropriate Article Order settings of the home page menu item (the Home link in the Main Menu). The Featured Articles Menu Item Type – an overview of all options You've seen that the Home menu is a link of the Featured Articles Menu Item Type. When adding or editing a Featured Articles menu link, you'll see there are are six expandable options panels available under the Advanced Options tab, offering a huge number of customization settings. Below you'll find a complete reference of all available options. Dozens of dazzling options – isn't that a bit too much? You've seen them before and now they turn up again, those seemingly endless lists of options. Maybe you find this abundance discouraging. Is it really necessary to check thirty or forty options to create just one menu link? Luckily, that's not how it works. You get fine results when you stick to the default settings. But if you want to tweak the way pages are displayed, it is worthwhile to experiment with the different options. See which settings fit your site best; in your day-to-day web building routine you'll probably stick to those. Layout Options Under Layout Options of the Featured Articles Menu Item Type, you find the main settings affecting the layout and arrangement of home page items. Select Categories   By default, the home page displays Featured Articles from all article categories. You can, however, control exactly from which categories featured articles should be shown. For example, you might want to display only featured articles from the News category on the home page, and featured articles from another category on another Featured Articles page, introducing another category. You'll see an example of this in the section Creating more than one page containing featured articles later in this article. # Leading Articles   Enter the number of leading articles you want to display, that is, intro texts displayed across the entire width of the mainbody. # Intro Articles The number of article intro texts that you want to show in two or more columns. # Columns   Specify the number of columns; over how many columns should the # Intro Articles be distributed? # Links   The number of hyperlinks to other articles (shown below Leading or Intro Articles) Multi Column Order   Should intro texts in multiple columns be sorted from left to right (across) or from top to bottom (down)? Category Order   Do you want to organize the items on the page by category title? You might want to do this when you have many items on your home page and you want your visitor to understand the category structure behind this. If you want to order by category, set Show Category (see Article Options explained in the next table) to show; that way, the visitor can see that the articles are grouped by category. The following Category Order options are available: No Order: If you select this option, the items are displayed in the order you set in the Article Order field (the next option under Layout Options). Title Alphabetical: Organizes categories alphabetically by title. Title Reverse Alphabetical: Organizes categories reverse-alphabetically by title. Category Manager Order: Organizes categories according to the order in the Category Manager and orders the category contents according to the Article Order (which you can specify below). Article Order   You can order the items within the featured articles page by date, alphabetically by Author name or Title, Most hits, and so on. If you choose Featured Articles Order, then the items appear in the order they have on the Content | Featured Articles screen. This last option gives you full manual control over the order of items on the page. Note: the Article Order is applied only after the Category Order. Article Order only has effect if you choose No Order in the Category Order box. Date for Ordering   If you've set the Article Order to Most Recent First or Oldest First, select the date for ordering: Created, Modified, or Published. Pagination   Auto: When there are more items available than it can fit the first page, Joomla automatically adds pagination links (<<Start <Previous 1 2 3 Next> End>>). On the home page, in many cases, you'll probably want to set Pagination to Hide. Pagination Results   If pagination links are shown, Joomla can also display the Pagination Results, the total number of pages (as in Page 1 of 3). Article Options The Article Options influence how articles are displayed on the Featured Articles page. For many extras you can select Show, Hide, Use Global (which means: use the settings chosen under Article Manager | Options), or Use Article Settings (use the settings chosen in the option panels of the individual articles). The Article Options are similar to the options you can set in the general preferences for articles (Article Manager | Options. Here, you can depart from the general settings for the articles and make different choices for this particular menu item. Show Title Display article titles or not? It's hard to find a reason to select Hide. Linked Titles Should the title of the article be a hyperlink to the full article? By default this option is set to Yes. This is better for usability reasons, because your visitor can just click on the article title to read a full article (instead of just on a Read more link). It is also better because search engines love links that clearly define the destination (which article titles should do). Show Intro Text After the visitor has clicked on a Read more link, do you want them to see a page with just the rest of the article text (select No) or the full article including the intro text (select Yes)? Position of Article Info The Article Info consists of the article details, such as the publication date, author name, and so on. If these details are set to be displayed, do you want to display them above the article, below the article, or split (partly above the article and partly below it)? Show Category Select Show if you want to show the category name below the article title. Joomla will display the category (as shown in the following screenshot: Category: Club Meetings). Link Category If the Category title is shown, should it be a hyperlink to the category? In most cases it's a good idea to select Yes here: this provides visitors with a link to category contents with every article. Show Parent Select Show if you want to show the name of the main category (the parent category of the current article category) below the article title. This will look as follows: Link Parent Just like the Category title, the title of the parent category can be made a link to an overview page of the main category contents. Show Author, Link Author, Show Create Date, Show Modify Date, Show Publish Date Do you want to show the author name (and make it a link to a page with other articles by the same author), the creation date, the date the article was last updated, and/or the date on which the article was first published? By default, many of these options are set to Show. You may want to choose Hide if you've got a small site or a site that isn't regularly updated. In that case you probably don't want to broadcast when your articles were written or who wrote them. Show Navigation Select Show if want to display navigation links between articles. Show Voting Should readers be able to rate articles (assign one to five stars to an article)? Show "Read more" Do you want a Read more link to appear below an article intro text? You'll probably want to leave this set to Yes, but if the title of the article is a hyperlink, a Read more link can be omitted. Although Joomla displays the Read more link by default, many web builders just make the article title clickable and omit a separate Read more link. Show Title with Read More It's a good idea to display the article title as part of the Read more text, as this will make the link text more meaningful for both search engines and ordinary visitors. Show Icons Joomla can show a set of special function icons with any article. These allow the visitor to print the article, or to e-mail it. Do you want to display these options as icons or text links? Show Print Icon, Show Email Icon Show or hide the special function icons? It's often better to altogether hide these extras. Your visitors may want to use the print function, but any modern browser offers a print function with better page formatting options. Show Hits Should the number of hits per article (the number of times it's been displayed) be shown? Show Unauthorized Links Do you want to show hyperlinks to articles that are only accessible to registered users, or hide these articles completely? The Article Options listed previously allow you to show or hide all kinds of details, such as Author, Create Date, and Modify Date. In the following image, you can see the result when most options are set to Show. Obviously, this results in too much "detail clutter". On a website that's maintained by just one or a few authors, or a website that isn't updated regularly, you might want to hide author and date details. On a home page you'll probably also want to hide all of the special function icons (set Icons, Print Icon, and Email Icon to Hide). It's unlikely that visitors want to print or e-mail parts of your home page content. In the following image, all extras are hidden, which leaves much more room for actual content in the same space. Integration Options The Integration Options are only relevant when you use news feeds (RSS feeds) on your website. Show Feed Link The Show Feed Link option allows you to show or hide an RSS Feed Link. This will display a feed icon in the address bar of the web browser. For each feed item show This option allows you to control what to show in the news feed; the intro text of each article, or the full article. Link Type Options The Link Type Options allow you to set the display of the menu link to this page (in this case the Home link). Link Title Attribute Here you can add a description that is displayed when the mouse cursor hovers over the menu link to this page. Link CSS Style Only relevant if you are familiar with CSS and want to apply a custom CSS style to this specific menu link. If you've added a specific style in the CSS stylesheet, in this box you should fill in the name of that special style. Joomla will adjust the HTML and add the CSS style to the current menu Home link, as follows: <a class="specialstyle" ref="/index.php">Home </a> Link Image Should an image be shown in the Main Menu link next to the Home link? Menu images (icons) can make a menu more attractive and easier to scan. Following is one of countless examples from the web: Add Menu Title When you use a Link Image, should the menu link text be displayed next to it? Select No only if you want a completely graphical menu, using just icons. Page Display Options Under Page Display Options, you'll find some options to customize page headings and an option to control the general design of the page. Browser Page Title An HTML page contains a title tag. This doesn't appear on the page itself, but it's is displayed in the title bar of the browser. By default, Joomla will use the menu item title as the title tag. Here, you can overrule this default title. Show Page Heading Here you can determine if a page heading appears at the top of the page (that is, in the mainbody). By default, this option is set to No. Select Yes to show the Menu Item Title as the Page Heading. Page Heading If you want to customize the Page Heading (instead of using the default Menu Item Title as the heading text), enter a text here. Page Class This is only relevant if you want to get more control over the page design: font size, colors, and so on. Using the Page Class field, you add a suffix to the name of all CSS styles used on this page. To use this feature, you have to know your way around in CSS. Metadata Options The Metadata Options allow you to add description and keywords to describe the web page's content. Meta Description, Meta Keywords, Robots, Secure Metadata information is used by search engines. You can add an article description, meta keywords, and enter instructions for Robots (web search engine spiders) and select whether this link should use a specified security protocol. Module Assignment for this Menu Item tab Click the Module Assignment for this Menu Item tab to see links to all modules that are assigned to the current menu item. Modules in Joomla are always assigned to one or more menu items. When the visitor clicks a menu link, a page is displayed consisting of (among other things) specific module blocks. This overview of (links to) assigned modules makes it easier for administrators to jump directly from the menu item to all related modules and change their settings. Creating more than one page containing featured articles By default, the Featured Articles Menu Item Type is used only once on your site. All articles that have the Featured status, are shown on the homepage. This is because the Home link in the Main Menu is created using the Featured Articles Menu Item Type. However, you can create as many Featured Articles pages as you like, each one showing featured articles from different categories. Let's say you want to create a page called "News Highlights", containing featured articles only from the News category. To do this, create a new menu link of the Featured Articles Menu Item Type and instead of All Categories select only the News category: The output would be a separate featured articles page containing news highlights. To avoid the same featured news showing up on both the homepage and the News Highlights page, you would probably want to change the home page settings (currently set to show all categories) and get it to display featured articles from all categories except for the News category. Another type of home page: using a single article So far you've used Joomla's Featured Articles layout for your site's home page. But what if you want a completely different home page layout? That's easily achieved, since Joomla allows you to set any menu item as the default page. Time for action – creating a different home page Let's not use the Featured Articles and create a simple home page that only shows one single, full article: Navigate to Menus | Main Menu. As you can see, there's a star in the Home column of the Home link. This indicates that this is the default page; the visitor will see this page in the mainbody when accessing your site. In this example we'll select the Mission Statement menu item as the new home page. Locate this article in the list and click on the grey star in the Home column. Clicking the grey star will turn its color into orange, indicating this is now the default page. Click on View Site. The results are shown in the following screenshot. An ordinary article is now the home page: If you want to update the Main Menu to reflect these changes, you can hide the existing Home link in the Article Manager, which is still pointing to the "old" homepage. To do this, in the Menu Manager you would click on the Unpublish item icon next to the Home link and rename the existing Mission Statement menu link to Home. What just happened? You've changed the default view of the home page to a fresh look, showing one article. Of course, you can dress up such a basic home page any way you like. For some sites (a simple "brochure site" presenting a small company or a project), this may be a good solution. The consequence of this approach is, of course, that the Featured status (that you can set in the Article Manager and in the article edit screen) no longer determines what's published on the home page.
Read more
  • 0
  • 0
  • 2240

article-image-introduction-citrix-xendesktop
Packt
29 May 2013
23 min read
Save for later

Introduction to Citrix XenDesktop

Packt
29 May 2013
23 min read
(For more resources related to this topic, see here.) Configuring the XenDesktop policies Now that the XenDesktop infrastructure has been configured, it's time to activate and populate the VDI policies. This is an extremely important part of the implementation process, because with these policies you will regulate the resource use and assignments, and you will also improve the general virtual desktops performance. Getting ready All the policies will be applied to the deployed virtual desktop instances and the assigned users, so you need an already existing XenDesktop infrastructure on which you will enable and use the configuration rules. How to do it... In this recipe we will explain the configuration for the user and machine policies offered by Citrix XenDesktop. Perform the following steps: Connect to the XenDesktop Director machine with domain administrative credentials, then navigate to Start | All Programs | Citrix and run the Desktop Studio. On the left-hand side menu expand the HDX Policy section and select the Machines link. Click on the New button to create a new policy container, or select the default unfiltered policies and click on Edit to modify them. In the first case, you have to assign a descriptive name to the created policy. In the Categories menu, click on the following sections and configure the values for the policies that will be applied to the clients, in terms of network flow optimization and resource usage monitoring: The ICA section ICA listener connection timeout: Insert a value in milliseconds; default is 12000. ICA listener port number: This is the TCP/IP port number on which the ICA protocol will try to establish the connection. The default value is 1494. The Auto Client Reconnect subsection Auto client reconnect: (Values Allowed or Prohibited) Specify whether or not to automatically reconnect in case of a broken connection from a client. Auto client reconnect authentication: (Values Do not require authentication or Require authentication) Decide whether to let the Citrix infrastructure ask you for the credentials each time you have to reperform the login operation. Auto client reconnect logging: (Values Do Not Log auto-reconnect events or Log auto-reconnect events) This policy enables or disables the logging activities in the system log for the reconnection process. In case of active autoclient reconnect, you should also activate its logging. End User Monitoring subsection ICA round trip calculation: (Values Enabled or Disabled) This decides whether or not to enable the calculation of the ICA network traffic time. ICA round trip calculation interval: Insert the time interval in seconds for the period of the round trip calculation. ICA round trip calculations for idle connections: (Values Enabled or Disabled) Decide whether to enable the round trip calculation for connections that are not performing traffic. Enable this policy only if necessary. The Graphics subsection Display memory limit: Configure the maximum value in KB to assign it to the video buffer for a session. Display mode degrade preference: (Values Degrade color depth first or Degrade resolution first) Configure a parameter to lower the resolution or the color quality in case of graphic memory overflow. Dynamic Windows Preview: (Values Enabled or Disabled) With this policy you have the ability to turn on or turn off the high-level preview of the windows open on the screen. Image caching: (Values Enabled or Disabled) With this parameter you can cache images on the client to obtain a faster response. Notify user when display mode is degraded: (Values Enabled or Disabled) In case of degraded connections you can display a pop up to send a notification to the involved users. Queueing and tossing: (Values Enabled or Disabled) By enabling this policy you can stop the processing of the images that are replaced by other pictures. In presence of slow or WAN network connections, you should create a separate policy group which will reduce the display memory size, configure the degrade color depth policy, activate the image caching, and remove the advanced Windows graphical features. The Keep Alive subsection ICA keep alive timeout: Insert a value in seconds to configure the keep alive timeout for the ICA connections. ICA keep alives: (Values Do not send ICA keep alive messages or Send ICA keep alive messages) Configure whether or not to send keep-alive signals for the running sessions. The Multimedia subsection Windows Media Redirection: (Values Allowed or Prohibited) Decide whether or not to redirect the multimedia execution on the Citrix server(s) and then stream it to the clients. Windows Media Redirection Buffer Size: Insert a value in seconds for the buffer used to deliver multimedia contents to the clients. Windows Media Redirection Buffer Size Use: (Values Enabled or Disabled) This policy decides whether or not to let you use the previously configured media buffer size. The Multi-Stream Connections subsection Audio UDP Port Range: Specify a port range for the UDP connections used to stream audio data. The default range is 16500 to 16509. Multi-Port Policy: This policy configures the traffic shaping to implement the quality of service (QoS). You have to specify from two to four ports and assign them a priority level. Multi-Stream: (Values Enabled or Disabled) Decide whether or not to activate the previously configured multistream ports. You have to enable this policy to activate the port configuration in the Multi-Port Policy. The Session Reliability subsection Session reliability connections: (Values Allowed or Prohibited) By enabling this policy you allow the sessions to remain active in case of network problems. Session reliability port number: Specify the port used by ICA to check the reliability of incoming connections. The default port is 2598. Session reliability timeout: Specify a value in seconds used by the session reliability manager component to wait for a client reconnection. You cannot enable the ICA keep alives policy if the policies under the Session Reliability subsection have been activated. The Virtual Desktop Agent Settings section Controller Registration Port: Specify the port used by Virtual Desktop Agent on the client to register with the Desktop Controller. The default value is 80. Changing this port number will require you to also modify the port on the controller machine by running the following command: <BrokerInstallationPath>BrokerService.exe / VdaPort <newPort> Controller SIDs: Specify a single controller SID or a list of them used by Virtual Desktop Agent for registration procedures. Controllers: Specify a single or a set of Desktop Controllers in the form of FQDN, used by Virtual Desktop Agent for registration procedures. Site GUID: Specify the XenDesktop unique site identifier used by Virtual Desktop Agent for registration procedures. In presence of more than one Desktop Controller, you should create multiple VDA policies with different controllers for a load-balanced infrastructure.   The CPU Usage Monitoring subsection Enable Monitoring: (Values Allowed or Prohibited) With this policy you can enable or disable the monitoring for the CPU usage. Monitoring Period: Insert a value in seconds to configure the time period to run the CPU usage recalculation. Threshold: Configure a percentage value to activate the high CPU usage alert. The default value is 95 percent. Enable the CPU Usage Monitoring policies in order to better troubleshoot machine load issues. After configuring, click on the OK button to save the modifications. On the left-hand side menu, click on the Users policy link in the HDX Policy section. Click on the New button to create a new policy container, or select the default unfiltered policies and click on Edit to modify them. In the first case, you have to assign a descriptive name to the created policy. In the Categories menu click on the following sections and configure the associated values: The ICA section Client clipboard redirection: (Values Allowed or Prohibited) This policy permits you to decide whether or not to enable the use of the client clipboard in the XenDesktop session, and to perform copy and paste operations from the physical device to the remote Citrix session. The active clipboard redirection could be a security issue; be sure about its activation! The Flash Redirection subsection Flash acceleration: (Values Enabled or Disabled) This policy permits you to redirect the Flash rendering activities to the client. This is possible only with the legacy mode. Enable this policy to have a better user experience for the Flash contents. Flash backwards compatibility: (Values Enabled or Disabled) With this policy you can decide whether or not to activate the compatibility of older versions of Citrix Receiver with the most recent Citrix Flash policies and features. Flash default behavior: (Values Enable Flash acceleration, Disable Flash acceleration, or Block Flash player) This policy regulates the use of the Adobe Flash technology, respectively enabling the most recent Citrix for Flash features (including the client-side processing), permitting only server-side processed contents, or blocking any Flash content. Flash event logging: (Values Enabled or Disabled) Decide whether or not to create system logs for the Adobe Flash events. Flash intelligent fallback: (Values Enabled or Disabled) This policy, if enabled, is able to activate the server-side Flash content processing when the client side is not required. The Flash Redirection features have been strongly improved starting from XenDesktop Version 5.5. The Audio subsection Audio over UDP Real-time transport: (Values Enabled or Disabled) With this policy you can decide which protocols to transmit the audio packets, RTP/UDP (policy enabled) or TCP (policy disabled). The choice depends on the kind of audio traffic to transmit. UDP is better in terms of performance and bandwidth consumption. Audio quality: (Values Low, Medium, or High) This parameter depends on a comparison between the quality of the network connections and the audio level, and they respectively cover the low-speed connections, optimized for speech and high-definition audio cases. Client audio redirection: (Values Allowed or Prohibited) Allowing or prohibiting this policy permits applications to use the audio device on the client's machine(s). Client microphone redirection: (Values Allowed or Prohibited ) This policy permits you to map client microphone devices to use within a desktop session. Try to reduce the network and load impact of the multimedia components and devices where the high user experience is not required. The Bandwidth subsection Audio redirection bandwidth limit: Insert a value in kilobits per second (Kbps) to set the maximum bandwidth assigned to the playing and recording audio activities. Audio redirection bandwidth limit percent: Insert a maximum percentage value to play and record audio. Client USB device redirection bandwidth limit: Insert a value in Kbps to set the maximum bandwidth assigned to USB devices redirection. Client USB device redirection bandwidth limit percent: Insert a maximum percentage value for USB devices redirection. Clipboard redirection bandwidth limit: Insert a value in Kbps to set the maximum bandwidth assigned to the clipboard traffic from the local client to the remote session. Clipboard redirection bandwidth limit percent: Insert a maximum percentage value for the clipboard traffic from the local client to the remote session. COM port redirection bandwidth limit: Insert a value in Kbps to set the maximum bandwidth assigned to the client COM port redirected traffic. COM port redirection bandwidth limit percent: Insert a maximum percentage value for the client COM port redirected traffic. File redirection bandwidth limit: Insert a value in Kbps to set the maximum bandwidth assigned to client drives redirection. File redirection bandwidth limit percent: Insert a maximum percentage value for client drives redirection. HDX MediaStream Multimedia Acceleration bandwidth limit: Insert a value in Kbps to set the maximum bandwidth assigned to the multimedia content redirected through the HDX MediaStream acceleration. HDX MediaStream Multimedia Acceleration bandwidth limit percent: Insert a maximum percentage value for the multimedia content redirected through the HDX MediaStream acceleration. Overall session bandwidth limit: Specify a value in Kbps for the total bandwidth assigned to the client sessions. In presence of both bandwidth limit and bandwidth limit percent enabled policies, the most restrictive value will be used. The Desktop UI subsection Aero Redirection: (Values Enabled or Disabled) This policy decides whether or not to activate the redirection of the Windows Aero graphical feature to the client device. If Aero has been disabled, this policy has no value. Aero Redirection Graphics Quality: (Values High, Medium, Low, and Lossless) If Aero has been enabled, you can configure its graphics level. Desktop wallpaper: (Values Allowed or Prohibited) Through this policy you can decide whether or not to permit the users having the desktop wallpaper in your session. Disable this policy if you want to standardize your desktop deployment. Menu animation: (Values Allowed or Prohibited) This policy permits you to decide whether or not to have the animated menu of the Microsoft operating systems. The choice depends on what kind of performances you need for your desktops. View window contents while dragging: (Values Allowed or Prohibited) This policy gives you the ability to see the entire window contents during the drag-and-drop activities between windows, if enabled. Otherwise you'll see only the window's border. Enabling the Aero redirection will have impact only on the LAN-based connection; on WAN, Aero will not be redirected by default. The File Redirection subsection Auto connect client drives: (Values Enabled or Disabled) With this policy the local drives of your client will or will not be automatically connected at logon time. Client drive redirection: (Values Allowed or Prohibited) The drive redirection policy allows you to decide whether it is permitted or not to save files locally on the client machine drives. Client fixed drives: (Values Allowed or Prohibited) This policy decides whether or not to permit you to read data from and save information to the fixed drives of your client machine. Client floppy drives: (Values Allowed or Prohibited) This policy decides whether or not to permit you to read data from and save information to the floppy drives of your client machine. This should be allowed only in presence of an existing floppy drive, otherwise it has no value to your infrastructure. Client network drives: (Values Allowed or Prohibited) With this policy you have the capability of mapping the remote network drives from your client. Client optical drives: (Values Allowed or Prohibited) With this policy you can enable or disable the access to the optical client drives, such as CD-ROM or DVD-ROM. Client removable drives: (Values Allowed or Prohibited) This policy allows or prohibits you to map, read, and save removable drives from your client, such as USB keys. Preserve client drive letters: (Values Enabled or Disabled) Enabling this policy offers you the possibility of maintaining the client drive letters when mapping them in the remote session, whenever possible. Read-only client drive access: (Values Enabled or Disabled) Enabling this policy will not permit you to access the mapped client drivers in write mode. By default, this policy is disabled to permit the full drive access. To reduce the impact on the client security, you should enable it. You can always modify it when necessary. These are powerful policies for regulating the access to the physical storage resources. You should configure them to be consistent with your company security policies. The Multi-Stream connections subsection Multi-Stream: (Values Enabled or Disabled) As seen earlier for the machine section, this policy enables or disables the multistreamed traffic for specific users. The Port Redirection subsection Auto connect client COM ports: (Values Enabled or Disabled) If enabled, this policy automatically maps the client COM ports. Auto connect client LPT ports: (Values Enabled or Disabled) This policy, if enabled, autoconnects the client LPT ports. Client COM port redirection: (Values Allowed or Prohibited) This policy configures the COM port redirection between the client and the remote session. Client LPT port redirection: (Values Allowed or Prohibited) This policy configures the LPT port redirection between the client and the remote session. You have to enable only the necessary ports, so disable the policies for the missing COM or LPT ports. The Session Limits subsection Disconnected session timer: (Values Enabled or Disabled) This policy enables or disables the counter used to migrate from a locked workstation to a logged off session. For security reasons, you should enable the automatic logoff of the idle sessions. Disconnected session timer interval: Insert a value in minutes, which will be used as a counter reference value to log off locked workstations. Set this parameter based on a real inactivity time for your company employees. Session connection to timer: (Values Enabled or Disabled) This policy will or will not use a timer to measure the duration of active connections from clients to the remote sessions. The Time Zone Control subsection Use local time of client: (Values Use server time zone or Use client time zone) With this policy you can decide whether to use the time settings from your client or from the server. XenDesktop uses the user session's time zone. The USB Devices subsection Client USB device redirection: (Values Allowed or Prohibited) With this important policy you can permit or prohibit USB drives redirection. Client USB device redirection rules: Through this policy you can generate rules for specific USB devices and vendors, in order to filter or not; and if yes, what types of external devices mapping. The Visual Display subsection Max Frame Per Second: Insert a value, in terms of frames per second, which will define the number of frames sent from the virtual desktop to the user client. This parameter could dramatically impact the network performance, so be careful about it and your network connection. The Server Session Settings section Single Sign-On: (Values Enabled or Disabled) This policy decides whether to turn on or turn off the SSO for the user sessions. Single Sign-On central store: Specify the SSO store server to which the user will connect for the logon operations, in the form of a UNC path. The Virtual Desktop Agent Settings section The HDX3DPro subsection EnableLossLess: (Values Allowed or Prohibited) This policy permits or prohibits the use of a lossless codec. HDX3DPro Quality Settings: Specify two values, Minimum Quality and Maximum Quality (from 0 to 100), as HDX 3D Pro quality levels. In the absence of a valid HDX 3D Pro license, this policy has no effect. The ICA Latency Monitoring subsection Enable Monitoring: (Values Allowed or Prohibited) This rule will or will not monitor the ICA latency problems. Monitoring Period: Define a value in seconds to run the ICA latency monitor. Threshold: Insert a threshold value in milliseconds to check if the ICA latency has arrived to the highest level. The Profile Load Time Monitoring subsection Enable Monitoring: (Values Allowed or Prohibited) With this policy you can monitor the time required to load a user profile. Threshold: Specify a value in seconds to activate the trigger for the high profile loading time event. These are important policies to troubleshoot performance issues in the profile loading activities, especially referred to the centralized profiles. After configuring click on the OK button to save the modifications. For both the edited policy categories (Machines and Users), click on the Edit button, select the Filters tab, and add one or more of the following filters: Access Control: (Mode: Allow or Deny, Connection Type: With Access Gateway or Without Access Gateway) Insert the parameters for the type of connection to which you are applying the policies, using or not using Citrix Access Gateway. Branch Repeater: (Values Connections with Branch Repeater or Connections without Branch Repeater) This policy decides whether or not to apply the policies to the connection that passes or doesn't pass through a configured Citrix Branch Repeater. Client IP Address: (Mode: Allow or Deny) Specify a client IP address to which you are allowing or denying the policy application. Client Name: (Mode: Allow or Deny) Specify a client name to which you are allowing or denying the policy application. Desktop Group: (Mode: Allow or Deny) Select from the drop-down list an existing desktop or application group to which you are applying or not applying the configured policies. Desktop Type: (Mode: Allow or Deny) This policy decides to allow or deny the policy application to the existing deployed resources (Private Desktop or Shared Desktop, Private Applications or Shared Applications). Organizational Unit: (Mode: Allow or Deny) Browse for an existing domain OU to which you are applying or not applying the configured policies. Tag: (Mode: Allow or Deny) This policy decides to allow or deny the application of the policies to specific tags applied to the desktops. User or Group: (Mode: Allow or Deny) Browse for existing domain users and groups to which you are applying or not applying the configured policies. For the machine section, you'll only have the desktop group, desktop type, organizational unit, and tag categories of filters. After completing this, click on the OK button to save the changed filters. How it works... The Citrix XenDesktop policies work at two different levels of components, machines and users, and for each of them you can apply a set of filters to decide when and where to permit or not to permit the policy utilization. These configurations should be strongly oriented to the performance and security optimization, so the best practices to apply is to generate different sets of policies and specifically apply them to different kinds of virtual desktops, clients, and users. The following is the explanation of the previously applied configurations: Machines policy level: These kinds of policies apply at the machine level, trying to regulate and optimize the session management, and the multimedia resources redirection. With this group of settings you are able to configure the standard ICA port to listen, and the relative connection timeouts. It's possible to decide whether or not to automatically reconnect a client in case of broken connections. Enabling Auto client reconnect policy could be right in some cases, especially when you have interrupted an important working session, but on the other hand, you could not have calculated waste of resources, because the Citrix broker could run a new session in the presence of issues with the session cookies. With the ICA round trip policies, you can monitor and measure the response time taken by the users for the operations. This data permits you to understand the responsiveness of your Citrix infrastructure. In case it allows you to apply remediation to the configuration, especially for the policies that involve graphics components, you can size the display memory and the image caching area, or turn on or off specific Windows advanced graphical features, such as the Dynamic Windows Preview (DWP). With the queuing and tossing policy active, you could have problems of lost frames when reproducing animations. The Windows media redirection policy optimizes the reproduction of multimedia objects; by applying a correct sizing to its buffer size you should obtain evident improvements in the streaming and reproduction operations. So, you should consider disabling this policy, demanding the processing of audio and video to the clients only when you can see no particular benefits. Another important feature offered by these policies is the QoS implementation; you can enable the multistream connection configurations and apply the traffic priority levels to them, permitting to give precedence and more bandwidth to the traffic that is considered more critical than others. The Multi-Stream policy for the QoS can be considered a less powerful alternative to Citrix Branch Repeater. As the last part of this section, the Virtual Desktop Agent Settings section permits you to restrict the access to only pre-configured resources, such as specific Desktop Controllers. Users policy level: Combined with the machines policies we have the users policies. These policies apply settings from a user session perspective, so you can configure, for instance, processing the Adobe Flash contents, deciding whether or not to activate the compatibility with the oldest version of this software, and whether to elaborate the Flash multimedia objects on the user's clients or on the Citrix servers. Moreover, you can configure the audio settings, such as audio and microphone client redirection (in the sense of using the local device resources), the desktop settings (Aero parameters, desktop wallpapers, and so on), or the HDX protocol quality settings. Be careful when applying policies for the desktop graphical settings. To optimize the information transmission for the desktops the bandwidth policy is extremely important; by this you can assign, in the form of maximum Kbps or percentage, the values for the traffic types such as audio, USB, clipboard, COM and LPT ports, and file redirection. These configurations require a good analysis of the traffic levels and their priorities within your organization. The last great configuration is the redirection of the client drives to the remote Citrix sessions; in fact, you can activate the mount (automatic or not) and the users rights (read only or read/write) on the client drives, removable or not, such as CD-ROM or DVD-ROM, removable USB devices, and fixed drives as the client device operating system root. This option gives you the flexibility to transfer information from the local device to the XenDesktop instance through the use of properly configured Virtual Desktop Agent. This last device policy could make your infrastructure more secure, thanks to the use of the USB device redirection rules; through it, in fact, you could only permit the use of USB keys approved by your company, prohibiting any other nonpolicy-compliant device. The granularity of the policy application is granted by the configuration of the filters; by using these-you can apply the policies to specific clients, desktop or application groups, or domain users and groups. In this way you can create different policies with different configurations, and apply them to specific areas of your company, without generalizing and overriding settings. There's more... To verify the effective running of the policies applied to your VDI infrastructure, there's a tool called Citrix Group Policy Modeling Wizard inside the HDX Policy section, which performs this task. This tool performs a simulation for the policy applications, returning a report with the current configuration. This is something similar to Microsoft Windows Domain Group Policy Results. The simulations apply to one or all the domain controllers configured within your domain, being able to test the application for a specific user or computer object, including organizational units containing them. Moreover, you can apply filters based on the client IP address, the client name, the type of machine (private or shared desktop, private or shared application), or you can apply the simulation to a specific desktop group. In the Advanced Options section you can simulate slow network connections and/or loopback processing (basically, a policy application only based on the computer object locations, instead of both the user and computer object positions) for a configured XenDesktop site. After running the policy application test, you can check the results by right-clicking on the generated report name, and selecting the View Report option. This tool is extremely powerful when you have to verify unexpected behaviors of your desktop instances or user rights because of the application of incorrect policies. Summery In this article we discussed the configuration of the XenDesktop infrastructural policies. Resources for Article : Further resources on this subject: Linux Thin Client : Considering the Network [Article] Designing a XenApp 6 Farm [Article] Getting Started with XenApp 6 [Article]
Read more
  • 0
  • 0
  • 2022

article-image-html5-presentations-creating-our-initial-presentation
Packt
24 May 2013
10 min read
Save for later

HTML5 Presentations: Creating our initial presentation

Packt
24 May 2013
10 min read
Creating our initial presentation This recipe will teach you how to create a basic HTML5 presentation using reveal.js. We will cover the initial markup and setup. The presentation created here will be used throughout the rest of the book. Getting ready Before we start, we need to download the reveal.js script and assets. To do that, simply visit https://github.com/hakimel/reveal.js/downloads and get the latest version of reveal. Now open your favorite text editor and let's work on the presentation markup. How to do it... To create our initial presentation perform the following steps: The first step is to create an HTML file and save it as index.html. Then copy the reveal.js files to the same directory of our HTML file, keeping the following structure (highlighted files are the ones we are using in this recipe): index.html -css ---reveal.min.css ---print ---shaders ---theme -----default.css -----source -----template -js ---reveal.min.js -lib ---css ---font ---js -----head.min.js -plugin ---highlight ---markdown ---notes ---notes-server ---postmessage ---remotes ---zoom-js Now we need to write our initial HTML5 markup, as follows: <!doctype html> <html> <head> <meta charset="utf-8"> <title>HTML5 Presentations How-To</title> </head> <body> <div class="reveal"> <div class="slides"> </div> </div> </body> </html> With our initial markup ready we include the reveal.js base stylesheet and script file plus the default theme stylesheet. We will also need to include the HeadJS JavaScript loader in order to manage reveal.js plugins. The stylesheets will go directly below the title tag, while the script files must be included before the closing body tag: <head> <meta charset="utf-8"> <title>HTML5 Presentations How-To</title> <link rel="stylesheet" href = "css/reveal.min.css"> <link rel="stylesheet" href = "css/theme/default.css"> </head> <body> ... <script src = "lib/js/head.min.js"></script> <script src = "js/reveal.min.js"></script> </body> The fourth step is to create the elements for our slides. Our first presentation will have four slides, so we must add four section elements to our slides div, as follows: <div class="reveal"> <div class="slides"> <section> <h1>HTML5 Presentations</h1> <h3>How to create presentations for web browsers</h3> </section> <section> <h1>About this presentation</h1> <p>This is the example presentation for the book HTML5 Presentations How-To</p> </section> <section> <h1>reveal.js</h1> <ul> <li>created by Hakim El Hattab</li> <li>open source</li> </ul> </section> <section> <h1>References</h1> <ol> <li><a href = "http://hakim.se/">http://hakim.se/</a></li> <li><a href = "https://github.com/hakimel/reveal. js">https://github.com/hakimel/reveal.js</a></li> </ol> </section> </div> </div> After that, we initialize the reveal.js JavaScript object, right after the reveal.js script tag, as follows: <body> ... <script src = "js/reveal.min.js"></script> <script> Reveal.initialize({ controls: true, keyboard: true, center: true, transition: 'default' }); </script> </body> For the last step, open index.html using the browser of your choice and check out how our initial HTML5 presentation looks, as shown in the following screenshot: How it works... reveal.js is a powerful JavaScript library that allows us to create presentations using a web browser. It was created by Hakim El Hattab, a web developer known for his experiments with CSS3 transitions and JavaScript animations. By performing the preceding steps we created a regular HTML5 presentation. We have used reveal.js default themes and some minor configurations just to get started. We started with a basic HTML5 structure. It is important to bear in mind that our presentation is, before anything else, an HTML and it should be rendered normally in the browser. The presentation must follow a structure expected by the reveal.js script. First, our HTML must have one div with reveal as a class attribute. That div must contain another div with slides as a class attribute. The slides div must contain one or more section elements, each one representing a slide. As we will see in the Creating vertical/nested slides (Simple) recipe, it is possible to nest slides, creating a vertical navigation. Each slide can contain any HTML or markdown content. We started with just a few elements but we will enrich our presentation through each recipe. reveal.js comes with multiple themes, available under the css/theme directory. For our initial presentation, we are using the default.css theme. Other options would be beige, night, serif, simple, and sky. Theming will be covered in the Theming (Medium) recipe. With all the markup and styles set, we initialized the reveal.js JavaScript object by using the initialize method. We used only four options, as follows: Reveal.initialize({ controls: true, keyboard: true, center: true, transition: 'default' }); First we enabled the navigation controls at the user interface, setting the controls option to true. We activated keyboard navigation using the arrow keys and also centered the slides' content. The last option sets the transition between slides to default. The next recipe will cover the full list of available options. There's more... reveal.js will work on any browser, but modern browsers are preferred due to animations and 3D effects. We will also need to use external plugins in order to extend our presentation features. Dependencies As previously mentioned, reveal.js uses the HeadJS library to manage plugins and dependencies. You can use only reveal.js if you want, but some useful resources (such as speaker notes and zoom) are only enabled using plugins. The plugins can be loaded through the initialize method and we will see more about them in the Plugins and extensions (Medium) recipe. Overview and blackout modes While on our presentation, pressing the Esc key will switch to overview mode where you can interact with every slide. Another useful resource is the blackout mode. If you want to pause and draw attention from your audience, you can press the B key to alternate between normal and blackout modes, and hide your current slide data. Browser support reveal.js will work better on browsers with full support for CSS 3D animations (Chrome, Safari, Firefox, and Internet Explorer 10), but fallbacks (such as 2D transitions) are available for older browsers. Presentations will not work on Internet Explorer 7 or lower. In this recipe we have created our initial HTML5 presentation using reveal.js default options and theme. Using reveal.js JavaScript API reveal.js provides an extended API to control our presentation behavior. With reveal.js API methods we can move to previous and next slides, get the current index, toggle overview mode, and more. How to do it… To use reveal.js JavaScript API perform the following steps: Using reveal.js API we will create a navigation bar that will be positioned at the bottom of our presentation screen, containing links to our main slides plus links to the first, next, previous, and last slides. We will start by adding some HTML5 markup, including reveal.js API method calls inside the onclick attribute of our navigation elements: <body> <div id="navigation-bar"> <nav> <a href="#" onclick="Reveal.slide(0);">&laquo;&laquo; first</a> <a href="#" onclick="Reveal.prev();">&laquo; previous</a> <a href="#" onclick="Reveal.slide(0);">html5 presentations</ a> <a href="#" onclick="Reveal.slide(1);">about this presentation</a> <a href="#" onclick="Reveal.slide(2);">reveal.js</a> <a href="#" onclick="Reveal.slide(3);">references</a> <a href="#" onclick="Reveal.slide(4);">about the author</a> <a href="#" onclick="Reveal.slide(5);">why use reveal.js</a> <a href="#" onclick="Reveal.next();">next &raquo;</a> <a href="#" onclick="Reveal.slide(5);">last &raquo;&raquo;</ a> </nav> </div> … </body> Our navigation bar will need a CSS of its own. Let's add some new style rules to our style tag: <style> … #navigation-bar { position: fixed; left: 0; bottom: 2px; width: 100%; height: 50px; z-index: 20; background-color: #fff; border-top: 6px solid #df0d32; font-family: Helvetica, Arial, sans-serif; } #navigation-bar nav { padding: 15px 0; text-align: center; } #navigation-bar a { display: inline-block; padding: 0 10px; border-right: 2px solid #ccc; text-decoration: none; color: #df0d32; } #navigation-bar a:last-child { border-right: none; } #navigation-bar a:hover { text-decoration: underline; } </style> If you reload the presentation now, you will see our brand new navigation bar at the bottom, and if you click on the links, you will be taken directly to the referenced slides or actions (first, next, previous, last). How it works... reveal.js JavaScript API allows us to control our presentation behavior using JavaScript code. In the preceding example we have used almost all methods available. Let's take a closer look at them: Option Description Reveal.slide(indexh, indexv, indexf) Slides to the specified index (the indexh parameter). The first slide will have 0 as index, the second has 1, and so on. You can also specify the vertical index (the indexv parameter) in case of nested slides and the fragment index (the indexf parameter) inside the slide. Reveal.left() Goes to the previous slide in the horizontal line of the presentation. Reveal.right() Goes to the next slide in the horizontal line of the presentation. Reveal.up() Changes to the following nested slide. Reveal.down() Returns to the previous nested slide. Reveal.prev() Goes to the previous slide, horizontal or vertical. Reveal.next() Goes to the next slide, horizontal or vertical. Reveal.prevFragment() Switches to the previous fragment inside the current slide. Reveal.nextFragment() Switches to the next fragment inside the current slide. Reveal.toggleOverview() Toggles overview mode. Reveal.getPreviousSlide() Returns the DOM element of the previous slide. Reveal.getCurrentSlide() Returns the DOM element of the next slide. Reveal.getIndices() Returns an object with the current indices, for example {h: 2, v: 1}. The preceding methods are available to use in any JavaScript code after the reveal.js object has been initialized. You can either use it directly on elements' attributes (such as onclick) or call it directly from JavaScript functions and listeners. Summary In this article, the Creating our initial presentation recipe explained how we can create a basic HTML5 presentation and the Using reveal.js JavaScript API recipe explored Reveal.js JavaScript API by creating a custom navigation bar. Resources for Article : Further resources on this subject: HTML5: Audio and Video Elements [Article] HTML5: Developing Rich Media Applications using Canvas [Article] Building HTML5 Pages from Scratch [Article]
Read more
  • 0
  • 0
  • 3296
Visually different images

article-image-designer-friendly-templates
Packt
24 May 2013
11 min read
Save for later

Designer Friendly Templates

Packt
24 May 2013
11 min read
(For more resources related to this topic, see here.) Designer friendly templates (Simple) Inherent to web applications is this breach in technology. We need to combine business logic on the server with HTML pages and JavaScript on the client side. The nicely encapsulated server-side business logic then hits a client-side technology that really was intended to structure pages of text. You somehow need to weave the backend functionality into these web pages. Countless approaches exist that try to bridge the two. Lift is also unique in this regard in that it lets you create valid HTML5 or XHTML templates that contain absolutely no business functionality, yet it manages to combine the two in an inspiring and clear way. Getting ready Again, we will use the example application from the Preparing your development environment (Simple) recipe to talk about the different concepts. You will find the templates under the webapp directory inside src/main. If you open them, you will see they're plain and simple HTML files. It's easy for designers to edit them with the tools they know. How to do it... Lift's page templates are valid XHTML or HTML5 documents that are parsed and treated as NodeSeq documents (XML, basically) until served to the browser. The standard path for everything webby is src/main/webapp inside your project. Say you enter a URL liftapp.com/examples/templates and provide the user with access to this page (see the SiteMap task for details), Lift will search the templates.html page inside the examples directory located at src/main/webapp. That's the normal case. Of course you can rewrite URLs and point to something entirely different, but let's now consider the common case. Let's look at a simple template for the example applications' home page, http://localhost:8080: <!DOCTYPE html><html><head><meta content="text/html; charset=UTF-8"http-equiv="content-type" ></meta><title>Home</title></head><body class="lift:content_id=main"><div id="main"data-lift="surround?with=default;at=content"><h2>Welcome to your project!</h2><p><span data-lift="helloWorld.howdy">Welcome to your Lift app at<span id="time">Time goes here</span></span></p></div></body></html> Granted, this page doesn't do much, but that's all there is to this page. In most applications you have some common parts on a page and some that change content. It's easy to define these hierarchies of templates. In your page template you define by which parent template you want it to be surrounded with and at which place. The parent template itself can also be surrounded by another template, and so on. This is a useful feature to extract common parts of a page into base templates and build on top of these to finally define the structure and surrounding chrome of your pages. The parent template for this page is called default.html and is searched for in the templates-hidden folder. Any file that is embedded into a page is searched underneath templates-hidden. We omit the CSS and some of the Boilerplate and just show the interesting parts of the parent template's content: <body><div class="container">...<div class="column span-6 colborder sidebar"><hr class="space" ><span data-lift="Menu.builder?group=main"></span><hr class="space" ><span data-lift="Menu.builder?group=examples"></span><hr class="space" ><span data-lift="Menu.builder?group=PostingUsers"></span><div data-lift="Msgs?showAll=true"></"></"></div><hr class="space" ></div><div class="column span-17 last"><div id="content">The main content goes here</div></div>...</body> This template defines a sidebar and places our menus there. It defines a place where messages are shown that are sent from Lift with its S.notice, S.warning, and S.error methods. And finally, it defines an ID (content) that marks the element receiving the page content. How it works... Let's walk through the code snippet given in the preceding section and see how the pieces fit together. <body class="lift:content_id=main"> In the page template we tell Lift where the template actually starts. You can create complete, valid HTML pages and then make Lift cut the central piece out for its rendering process, and your designers can still work with complete pages that they can process in isolation from the rest. This line tells Lift that the content starts with the element with the ID, main. The next thing we do is to define a parent template that we use to surround the page with. This way, we define essential page layout markup only once and include it everywhere it's needed. Here's how you surround a page with a parent template: <div id="main" data-lift="lift:surround?with=default;at=content">… your content here…</div> In the class attribute of the div element you call the surround snippet and hand it over the with=default and at=content parameters. The surround snippet now knows that it should find a template called default.html and insert the content of this div element into the parent template at the point defined by the ID, content. Speaking of snippets, it is a mechanism to process parts of your HTML files the same way for built-in snippets as it is for your own. Snippets are pieces of logic that get weaved into the markup. We'll get to this integral part of Lift development really soon. Lift templates are the files that are not defined in the SiteMap. They are located at a subfolder called templates-hidden. They cannot be accessed directly from the URL, but only through code by directly opening it or through the surround-and-embed mechanisms inside other templates or pages. Have a look at the parent template default.html shown previously. This file, along with the other files we discuss here, is available in the source code that comes with the book. It's a standard HTML5 file defining some styles and finally defining a div element to bind the child content: <div id="content">The main content will get bound here</div> Lift will remove the text inside the DIV and replace it with the actual content, as shown in the following screenshot: A few other things at the top of the template are worth noting: <style class="lift:CSS.blueprint"></style><style class="lift:CSS.fancyType"></style><script id="jquery" src = "/classpath/jquery.js""type="text/javascript"></script> Lift comes bundled with the Blueprint CSS framework (http://blueprintcss.org/) and a version of jQuery (http://jquery.com/). It's intended to make it easier for you to start, but by no means are you bound to using Blueprint or the included jQuery version. Just use your own CSS framework (there's a recipe on using Twitter's Bootstrap) or jQuery where it makes sense. For instance, to use a hosted version of the latest jQuery library, you would replace the script tag from the preceding code snippet with the following: <script type="text/javascript" src = "http://code.jquery.com/jquery-1.8.2.min.js"></script> Lift provides some standard snippets which you can use to build up your pages. The default.html template utilizes a snippet to render a menu and another snippet to place messages on the page: <span data-lift="Menu.builder?group=main"></span> When you define the element that encloses the menu, Lift will automatically render it. If you omit the group parameter, all menu entries will be rendered. Having that parameter will restrict the menu only to the items within that group. You can assign a menu group (called LocGroup) in the SiteMap you defined in the Boot class. <div data-lift="Msgs?showAll=true"></div> This snippet call will render messages that are produced by the backend application in this spot. There's more... We will now have a look at execution order. In normal execution mode, Lift first evaluates the outer snippets and then layer by layer moves to the inner snippets. If you want to include the result of some inner snippet evaluations to the input of the outer snippets, you need to reverse that process. For that very reason, Lift provides a snippet parameter, eager_eval=true, that you add to the outer snippet: <div data-lift="ImOuter?eager_eval=true">...<div data-lift="ImInner">...</div>...</div> Adding that parameter causes Lift to first evaluate the inner snippet and then add the result of the inner snippet call to the input that is processed by the outer snippet. You can also embed templates into your page or other templates. That's the opposite operation of surrounding a page, but equally simple. In your page, use the embed snippet to embed a template: <div data-lift="embed?what=/examples/templates/awesome"></div> The what parameter defines the path to the template, which is searched for within the webapp directory. We will now see the programmatic embedding of templates. You can easily search a template and process it programmatically. In that case you need to specify the templates-hidden directory; that way you are able to access top-level pages as well. val ns:Box[NodeSeq] = S.runTemplate(List("templates-hidden","examples", "templates", "awesome")) Please see the EmbedTemplates snippet for an example of how to programmatically access templates and apply transformations before embedding it. <div data-lift="EmbedTemplate?what=/examples/templates/awesome"></div> As you can see, our own templates are called just the same way as Lift's default templates, and they can do the same things. Programmatic access to templates is useful, for instance when you want to send HTML e-mails. Inside the mail sender you would grab the template, process it (see CSS Selectors), and send the complete HTML to the recipient. There are a myriad more reasons or use cases when you want to access your templates from your Scala code. Just keep in the back of your mind that you can do it. The S.runTemplate method will fetch the template and process it. That means it will look for any embedded Lift snippet calls and execute them. These snippet calls could potentially embed other templates recursively. If you do not want the template to be processed, you can retrieve it like this: val tpl:Box[NodeSeq] = Templates(List("templates-hidden", "examples","templates", "awesome") Lift templates are very powerful, and they have to be. They are at the basis of every web application and need to handle a lot of different scenarios. The separation between the markup and the logic keeps the templates clean and prohibits your designers from breaking code. It might take a while to adopt to this template style if you come from a framework that mixes markup and code. We believe, especially in larger applications, you will soon see the benefits of a clear separation and encapsulation of your logic in reusable pieces. Speaking of reusable pieces, let's head over to snippets, Lift's way to plug functionality into templates. The Lift wiki offers further information about templates and binding at the following links: http://www.assembla.com/spaces/liftweb/wiki/Designer_Friendly_ Templates http://www.assembla.com/spaces/liftweb/wiki/Templates_and_ Binding Summary In this article, we learned about designer friendly templates. Resources for Article : Further resources on this subject: RESTful Web Service Implementation with RESTEasy [Article] Spring Roo 1.1: Working with Roo-generated Web Applications [Article] Deploying your Applications on WebSphere Application Server 7.0 (Part 1) [Article]
Read more
  • 0
  • 0
  • 1475

article-image-article-magento-performance-optimization
Packt
24 May 2013
5 min read
Save for later

Magento Performance Optimization

Packt
24 May 2013
5 min read
(For more resources related to this topic, see here.) Using the Magento caching system A cache is a system that stores data so that future requests for that data can be served faster. Having cache is definitely a good thing, but the caching system of Magento is not super effective. How to do it... Let's begin with cache enabling, even if most users are well aware of this one. Go to your backend console and then go to System | Cache Management. By default, all caches are enabled; but some have a negative impact. You have to disable caches for the following items: Collections Data EAV types and attributes Web Services Configuration The following table shows the improvement made due to the previous settings, that is, by disabling the selected caches: Another little win, 200 milliseconds, just enough to fulfill the promise made in the previous recipes. How it works... A cache is a system that stores data so that future requests for that data can be served faster. A web cache stores copies of documents passing through it, and subsequent requests may be satisfied from the cache if a set of conditions exists. There are many hypotheses out there to explain this weird optimization. The main one is that the Magento core has to parse the cache and check in MySQL to compare updated data, and this causes a huge delay. In fact, by allowing Magento to do these kinds of operations, we don't use the full resources of our systems. Using a memory-based filesystem for caching We can easily say that the slowest component of a computer is its hard drive. Moreover, the Magento caching system makes massive use of this component. It would be amazing if we could store the Magento cache files directly inside the memory. How to do it... Open a new console on your Unix server and enter the following command: code1 The path is based on a common installation of Apache with Magento; pay attention to your configuration when typing this command. You have to repeat this command every time the server starts up or you can automatize it by adding the following line into your /etc/fstab file: code1 All the caching mechanisms of Magento will now work with a memory-based filesystem instead of the classical filesystem. How it works... This newly created filesystem is intended to appear as a mounted filesystem, but takes place in the RAM. Of course, the access time of this kind of filesystem is extremely slow in comparison with a classical hard drive. However, all files updated or created are temporary because of the nature of this filesystem. Nothing will be written in the hard drive, and if you reboot everything will be lost. If you plan to reboot your server, you have to save the volatile files in your hard drive, unmount the memory-based system, and then copy the saved data from tmpfs in the cache folder. With the second command, the folder will be remounted automatically after the reboot. Clustering If you have successfully applied all the techniques and your Magento is still slow, it means that you are a very prosperous online retailer and it's time to leave the comfortable world where there is a single server. To keep your customers satisfied, you have to invest in hardware; the tweaking time is now over. How to do it... If you own a single server, you can begin by separating your database in a dedicated server. In order to do this, you have to invest in another server and install MySQL on it (get your host to do it for you), and then extract your database from your first server and import it to your new server. Magento stays on your first server; you have to modify the database connection. Go to /app/etc/local.xml and modify the following lines to fit the new server parameters: code1 As simple as that. You now use a dedicated database server and improve your store performance. The second step in clustering our environment could be using a CDN for our images, CSS, and scripts. A CDN is an independent server optimized for delivering static content such as images, CSS, and scripts. In this way, our web server can focus on running Magento and the CDN can focus on displaying static content. The good news is that Magento has native support to do this. In your Magento backend, navigate to System | General | Web | Unsecure. If you still have CSS and JavaScript compressed from the previous recipes, you just have to copy your media directory from your main server to your CDN server. If it's not the case anymore, you have to modify the Base Skin URL field and the Base JavaScript URL field. Also, if for some reason you use the secure URL for that kind of content, don't forget to apply the changes to the secure part as well. How it works... That's a very good start. Let's summarize it. We were using a single server for all requests, and now, depending on the request, we use three different servers. The first one handles all the Magento work for building pages, the second one handles the data-related operations, and the last one provides static content. With this kind of architecture, each server can focus on only one purpose. Summary This article helped you learn Magento's built-in caching system for saving frequently asked requests. It also introduced you on Magento makes massive use of hard drive which lets you use your available RAM. It also helped you on how to configure a set of loosely connected computers working together for handling more and more customers. Resources for Article : Further resources on this subject: Magento: Exploring Themes [Article] Getting Started with Magento Development [Article] Integrating Facebook with Magento [Article]
Read more
  • 0
  • 0
  • 1138

article-image-getting-started-zombiejs
Packt
22 May 2013
9 min read
Save for later

Getting Started with Zombie.js

Packt
22 May 2013
9 min read
(For more resources related to this topic, see here.) A brief history of software and user interface testing Software testing is a necessary activity for gathering information about the quality of a certain product or a service. In the traditional software development cycle, this activity had been delegated to a team whose sole job was to find problems in the software. This type of testing would be required if a generic product was being sold to a domestic end user or if a company was buying a licensed operating system. In most custom-built pieces of software, the testing team has the responsibility of manually testing the software, but often the client has to do the acceptance testing in which he or she has to make sure that the software behaves as expected. Every time someone in these teams finds a new problem in the software, the development team has to fix the software and put it back in the testing loop one more time. This implies that the cost and time required to deliver a final version of the software increases every time a bug is found. Furthermore, the later in the development process the problem is found, the more it will impact the final cost of the product. Also, the way software is delivered has changed in the last few years; the Web has enabled us to make the delivery of software and its upgrade easy, shortening the time between when new functionality is developed and when it is put in use. But once you have delivered the first version of a product and have a few customers using it, you can face a dilemma; fewer updates can mean the product quickly becomes obsolete. On the other hand, introducing many changes in the software increases the chance of something going wrong and your software becoming faulty, which may drive customers away. There are many versions and iterations over how a development process can mitigate the risk of shipping a faulty product and increase the chances of new functionalities to be delivered on time, and for the overall product to meet a certain quality standard, but all people involved in building software must agree that the sooner you catch a bug, the better. This means that you should catch the problems early on, preferably in the development cycle. Unfortunately, completely testing the software by hand every time the software changes, would be costly. The solution here is to automate the tests in order to maximize the test coverage (the percentage of the application code that is tested and the possible input variations) and minimize the time it takes to run each test. If your tests take just a few seconds to run, you can afford to run them every time you make a single change in the code base. Enter the automation era Test automation has been around for some years, even before the Web was around. As soon as graphical user interfaces (GUIs) started to become mainstream, the tools that allowed you to record, build, and run automated tests against a GUI started appearing. Since there were many languages and GUI libraries for building applications, many tools that covered some of these started showing up. Generally they allowed you to record a testing session that you could later recreate automatically. In this session, you could automate the pointer to click on things (buttons, checkboxes, places on a window, and so on), select values (from a select box, for instance), and input keyboard actions and test the results. All of these tools were fairly complex to operate and, worst of all, most of them were technology-specific. But, if you're building a web-based application that uses HTML and JavaScript, you have better alternatives. The most well known of these is likely to be Selenium, which allows you to record, change, and run testing scripts against all the major browsers. You can run tests using Selenium, but you need at least one browser for Selenium to attach itself to, in order to load and run the tests. If you run the tests with as many browsers as you possibly can, you will be able to guarantee that your application behaves correctly across all of them. But since Selenium plugs into a browser and commands it, running all the tests for a considerably complex application in as many browsers as possible can take some time, and the last thing you want is to not run the tests as often as possible. Unit tests versus integration tests Generally you can divide automated tests into two categories, namely unit tests and integration tests. Unit tests: These tests are where you select a small subset of your application—such as a class or a specific object—and test the interface the class or object provides to the rest of the application. In this way, you can isolate a specific component and make sure it behaves as expected so that other components in the application can use it safely. Integration tests: These tests are where individual components are combined together and tested as a working group. During these tests, you interact and manipulate the user interface that in turn interacts with the underlying blocks of your application. The kind of testing you do with Zombie.js falls in this category. What Zombie.js is Zombie.js allows you to run these tests without a real web browser. Instead, it uses a simulated browser where it stores the HTML code and runs the JavaScript you may have in your HTML page. This means that an HTML page doesn't need to be displayed, saving precious time that would otherwise be occupied rendering it. You can then use Zombie.js to conduct this simulated browser into loading pages and, once a page is loaded, doing certain actions and observing the results. And you can do all this using JavaScript, never having to switch languages between your client code and your test scripts. Understanding the server-side DOM Zombie.js runs on top of Node.js (http://nodejs.org), a platform where you can easily build networking servers using JavaScript. It runs on top of Google's fast V8 JavaScript engine that also powers their Chrome browsers. At the time of writing, V8 implements the JavaScript ECMA 3 standard and part of the ECMA 5 standard. Not all browsers implement all the features of all the versions of the JavaScript standards equally. This means that even if your tests pass in Zombie.js, it doesn't mean they will pass for all the target browsers. On top of Node.js, there is a third-party module named JSDOM (https://npmjs.org/package/jsdom) that allows you to parse an HTML document and use an API on top of a representation of that document; this allows you to query and manipulate it. The API provided is the standard Document Object Model (DOM). All browsers implement a subset of the DOM standard, which has been dictated as a set of recommendations by a working group inside the World Wide Web Consortium (W3C). They have three levels of recommendations. JSDOM implements all three. Web applications, directly or indirectly (by using tools such as jQuery), use this browser-provided DOM API to query and manipulate the document, enabling you to create browser applications that have complex behavior. This means that by using JSDOM you automatically support any JavaScript libraries that most modern browsers support. Zombie.js is your headless browser On top of Node.js and JSDOM lies Zombie.js. Zombie.js provides browser-like functionality and an API you can use for testing. For instance, a typical use of Zombie.js would be to open a browser, ask for a certain URL to be loaded, fill some values on a form, and submit it, and then query the resulting document to see if a success message is present. To make it more concrete, here is a simple example of what the code for a simple Zombie.js test may look like: browser.visit('http://localhost:8080/form', function() {browser.fill('Name', 'Pedro Teixeira').select('Born', '1975').check('Agree with terms and conditions').pressButton('Submit', function() {assert.equal(browser.location.pathname, '/success');assert.equal(browser.text('#message'),'Thank you for submitting this form!');});}); Here you are making typical use of Zombie.js: to load an HTML page containing a form; filling that form and submitting it; and then verifying that the result is successful. Zombie.js may not only be used for testing your web app but also by applications that need to behave like browsers, such as HTML scrapers, crawlers, and all sorts of HTML bots. If you are going to use Zombie.js to do any of these activities, please be a good Web citizen and use it ethically. Summary Creating automated tests is a vital part of the development process of any software application. When creating web applications using HTML, JavaScript, and CSS, you can use Zombie.js to create a set of tests; these tests load, query, manipulate, and provide inputs to any given web page. Given that Zombie.js simulates a browser and does not depend on the actual rendering of the HTML page, the tests run much faster than they would if you instrumented a real browser. Thus it is possible for you to run these tests whenever you make any small changes to your application. Zombie.js runs on top of Node.js, uses JSDOM to provide a DOM API on top of any HTML document, and simulates browser-like functionalities with a simple API that you can use to create your tests using JavaScript Resources for Article : Further resources on this subject: Understanding and Developing Node Modules [Article] An Overview of the Node Package Manager [Article] Build iPhone, Android and iPad Applications using jQTouch [Article]
Read more
  • 0
  • 0
  • 11033
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 €14.99/month. Cancel anytime
article-image-preparing-your-website-use-gridster
Packt
22 May 2013
4 min read
Save for later

Preparing your website to use Gridster

Packt
22 May 2013
4 min read
(For more resources related to this topic, see here.) Getting ready There are only two things needed to get Gridster installed on your source code. You first need to download jQuery if you don't already have it, and then download the latest version of Gridster. After that, you will use plain HTML code to include both libraries in your webpage. For most casual users, adding the latest version of jQuery will suffice. There are also nightly builds available, but these won't be discussed here as they are not necessary, and the latest version should be able to do everything we need. How to do it... Start by visiting jQuery's website, http://jquery.com/download/, and download the library to a location you will remember. We won't be debugging our jQuery code in the examples given in this book, so downloading the production version will be fine. We should now head over to Gridster's website, http://gridster.net/#download/, and download the minified versions of both the gridster.js and gridster.css files. These are the files we will use throughout this entire book, so make sure they are kept safe and accessible. A suggestion would be to create a directory structure to make it easier to refer to the files. I will be using the following structure for the examples given here: Under the directory recipe1, create a new text file called index.html. This file should initially contain the following code: <!DOCTYPE html><html><head><script src = "../scripts/jquery-1.8.3.min.js"></script><script src = "../scripts/jquery.gridster.min.js"></script><link href = "../styles/jquery.gridster.min.css" rel="stylesheet" /><title>Recipe 1</title></head><body>Hello Gridster!</body></html> You can download the example code files for all Packt books that you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub. com/support and register to have the files e-mailed directly to you. By double-clicking on this file, you should be presented with a screen that looks like the following screenshot: You can check that everything has loaded up correctly by pressing the F12 key on your browser (Chrome or Firefox), and checking that all files have been correctly loaded without errors, as shown in the following screenshot: There's more... Instead of downloading the files into your project, you can simply load them up via CDN-hosted copies of the files, as follows: <script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> In that case, the files wouldn't be coming from your website, but from jQuery's website itself. This is a good practice when trying to improve performance, as big web servers tend to host files on multiple locations and use very aggressive caching techniques to make sure the files are served quickly. Gridster also offers files in the same way from their website as you will find in their download section. So, for example, you could link directly to their minified file as follows: <scriptsrc ="https://raw.github.com/ducksboard/gridster.js/master/dist/jquery.gridster.min.js"></script> Summary In this recipe we described all the necessary steps to get Gridster up and running on your website, and also demonstrated how to include any of the dependencies needed by the library. Resources for Article : Further resources on this subject: Getting Started with jQuery [Article] jQuery Animation: Tips and Tricks [Article] Tips and Tricks for Working with jQuery and WordPress [Article]
Read more
  • 0
  • 0
  • 1550

article-image-less-css-preprocessor
Packt
21 May 2013
7 min read
Save for later

LESS CSS Preprocessor

Packt
21 May 2013
7 min read
(For more resources related to this topic, see here.) Installing LESS We're going to start the recipes in this book by looking at how we can get hold of LESS, and adding support for it to your website. LESS comes in two versions, depending on whether you want to use it client side or server side; for the purpose of this recipe, we're going to use it client side. The library is hosted on Google Code, and can be downloaded or included (as a CDN link) from http://cdnjs.cloudflare.com/ajax/libs/less.js/1.3.1/less. min.js. How to do it... The following steps will guide you in installing LESS: Let's get started by creating a new folder on your PC, let's call it test less projects. Crack open a normal text editor of your choice, save a copy of the code from the What you need for this book section in the preface of this book, and save it as test less include.html. Add the following in between the <body> tags in the code: <form action="">Name: <input type="text" class="input" />Password: <input type="password" class="input" /><input type="submit" value="This is a button" /></form> It shows a very plain, basic form, so let's fix that by starting to use LESS to provide some styling. Create a new document in your text editor, then add the following, and save it as include.less: @color-button: #d24444;#submitfrm {color:#fff;background:@color-button;border:1px solid @color-button - #222;padding:5px 12px;} Let's now add a link to this file to your main HTML file, so go ahead and alter your code accordingly: <link rel="stylesheet/less" type="text/css" href="include.less"> That's all that's required, so if you now open your browser, and view the file, you should see on screen the same as the following screenshot: How it works... This recipe was intended to serve as a very basic example of how you can use less.js. You will be already familiar with what most of the code does, with two exceptions (highlighted in the following code snippet): @color-button: #d24444;#submitfrm {color:#fff;background:@color-button;border:1px solid @color-button - #222;padding:5px 12px;} The first exception is simply setting a variable called color-button, which holds a value of #d24444; this is the red background you see on the button. There are a couple of points of interest here: All variables used in LESS must be preceded with an @ sign, to denote that they are variables Variables don't actually exist in the LESS library Huh? I hear you ask. That surely doesn't make sense! Well, let me explain: when using LESS, variables are actually classed as constants, as you can't reassign a new value to an existing predefined variable. There is nothing stopping you from using an existing variable to calculate a new value, but that value must be assigned to a new variable, or used to work out a value for a CSS style: background:@ color-button;border: 1px solid @color-button - #222;padding: 5px 12px; There's more... In order for the library to work properly, you need to first include links to your .less stylesheets, and set the rel tag to stylesheet/less, in order for them to work properly: <link rel="stylesheet/less" type="text/css" href="styles.less"> Note the use of the rel attribute on this link, you need to use the /less value, in order for LESS to work properly. If you are using HTML5 syntax, you don't need to include the type="text/less" and type="text/javascript" values. Next, you need to include LESS; you can either download it from the website and include it locally in the same way that you would include any JavaScript file, or use the following CDN link; in either case, you must include it after your .less stylesheet: <script src = "http://cdnjs.cloudflare.com/ajax/libs/less.js/1.3.1/less.min.js"></script> If you get a 406 error in your browser, you may need to set a MIME (or Internet Media Type, as it is now known), as the text/LESS tags may not work properly. We've seen how LESS can compile styles on the fly, but this may not be ideal if you have a very large site, or have a development process which doesn't allow the use of creating styles dynamically. This isn't an issue with LESS, as you can easily generate the stylesheet prior to including it within your site's pages. Precompiling LESS client side In the previous section, we looked at how you can use Less to dynamically generate your compiled stylesheet from within your site. This may not suit everyone's needs. Here, we will see some alternatives that allow us to precompile our CSS styles, so we can then include the finished results on our site. Getting ready Here we're going to use the open source application WinLESS to compile a LESS file into a normal CSS stylesheet. You can download a copy of the program from http://www.winless.org. You will also need your favorite text editor. We're going to create a typical .less file. How to do it... Open up the text editor of your choice, and add in the following lines; save it as testprecompile.less in the folder you created from the Installing LESS section: .border-radius(@radius: 3px) { -webkit-border-radius: @radius;-moz-border-radius: @radius; border-radius: @radius; }.box-shadow(@x : 2px, @y : 2px, @blur : 5px, @spread : 0, @color :rgba(0,0,0,.6)) {-webkit-box-shadow: @x @y @blur @spread @color;-moz-box-shadow: @x @y @blur @spread @color;box-shadow: @x @y @blur @spread @color;}div { @color: green; background: @color; width: 300px; height:300px; margin: 30px auto; .border-radius(10px); .box-shadow(); } Double-click on the WinLess_1.5.3.msi file you downloaded to install it, accept all defaults, and double-click on it to open the application. Click on the Add folder button, and select the folder you created in the first step, and click on OK to add it to the folder list of WinLess. Click on the Refresh folder button to update the list on the right-hand side as shown in the following screenshot: Click on Compile to generate the CSS file; if you open the resulting CSS file, you will see the generated code as follows: div {background: #008000;width: 300px;height: 300px;margin: 30px auto;-webkit-border-radius: 10px;-moz-border-radius: 10px;border-radius: 10px;-webkit-box-shadow: 2px 2px 5px 0 rgba(0, 0, 0, 0.6);-moz-box-shadow: 2px 2px 5px 0 rgba(0, 0, 0, 0.6);box-shadow: 2px 2px 5px 0 rgba(0, 0, 0, 0.6);} As you make further changes to the .less file, WinLess will automatically update the CSS file for you; it will remain in the same folder as the .less file, until you are ready to use it in a production environment. How it works... WinLess is GUI front-ends to the command-line version of LESS, lessc.cmd. The GUI takes the content of the .less file, parses it, and gives a .css file as the output with the compiled CSS styles. WinLess includes an option to maintain a list of files that it will automatically monitor, so that when any are changed, it will automatically update the contents of the equivalent CSS file with the appropriate changes. Summary In this article we saw how to install support for LESS and how to compile CSS styles before adding adding the code to your website. Resources for Article : Further resources on this subject: Drupal 6 Theming: Adding and Optimizing CSS Files [Article] Building our own Plone 3 Theme Add-on Product [Article] Creating Themes for a Report using BIRT [Article]
Read more
  • 0
  • 0
  • 4629

Packt
20 May 2013
15 min read
Save for later

Play! Framework 2 – Dealing with Content

Packt
20 May 2013
15 min read
(For more resources related to this topic, see here.) In order to keep the article short and to the point, we'll only see the Java part. Keep in mind that the Scala version is little different for this level of detail. Body parsing for better reactivity As noted earlier, the way to manage content in Play! 2 is to use instances of body parsers. In brief, a body parser is a component that is responsible for parsing the body of an HTTP request as a stream to be converted into a predefined structure. This has a common sense ring to it, however their strength is in their way of consuming the stream—in a reactive fashion. Reactivity, in this context, is meant to describe a process where an application won't block on a task that is actually idle. As a stream consumption task is idle when no bytes are incoming, a body parser should behave the same. It will read and construct an internal representation of the incoming bytes. But it can also decide at any time that it has read enough to terminate and return the representation. On the other hand, if no more bytes are coming into the stream, it can relax its thread in favor of another request; it pauses its work until new bytes are received. Thinking about an HTTP request that is sending a bunch of XML content, the underlying action can use the XML-related body parser to handle it correctly (read reactively); that is, by parsing it and providing a DOM representation. To understand what a body parser actually is, we'll first look at how they are used—in the actions. An action in Play! 2 represents the piece of software that is able to handle an HTTP request; therefore, they are the right place to use a body parser. In the Java API, an action is allowed to be annotated with the Of annotation available in the BodyParser class. This annotation declares the expected type of request routed to it, and it requires a parameter that is the class of the parser that will be instantiated to parse the incoming request's body. The following screenshot shows an example: Isn't this helpful? We've gone from a request to a W3C document, in a single line. Functionally speaking, this works because an action is semantically a higher-order function that takes a body parser and generates a function that takes a request (and so its body) and results in an HTTP response (result). This result will then be used to construct the HTTP response by Play! 2. In Java, it is not all that obvious how to create a higher-order function. A good way, however, to achieve this was to add an annotation. An annotation can be processed at runtime in order to execute the right body parser (in this case). To illustrate this, we'll have a quick look at the Scala version: With this Scala version, it is easy to see that an action is dealing with a function from a request to a response. There are a plenty of predefined body parsers that can be used to handle our requests, and they are all defined in the BodyParser class as static inner classes. One can have a specific behavior to be applied on its expected request body, and even though a body parser has to be implemented in Scala, a Java coder can simply extend these current implementations. Actually, they're already providing enough control to cover all custom use cases. So, we have in our hands tools to handle the following content types: JSON XML URL form encoded Multipart (for uploading files) Text Raw (fallback) As we can see from the previous list, there is, obviously, an implementation for the x-www-form-urlencoded content type. Indeed, this is the parser we've used so far to retrieve data from the client side. For example, using POST requests throughout HTML forms. But wait, we never had to add such annotations to our actions, and, moreover, we've never looked in the parsed result. That's true, Play! 2, as a great framework, is already doing a lot of stuff for us. And that's because it's a web framework; it takes advantage of HTTP; in this case, using the content-type header. Based on this hint, it seems obvious that Play! Framework 2 will look in this header to find the right parser to apply. So annotations are mandatory, but where did we use them previously? In the bindFromRequest method, of course. Let's see how. We have used form instances, and we fed them some data through the client. Those instances were applied on the request using the bindFromRequest method, and this method's job was to look for data according to the provided content type. And, of course, this content type was set in the header by the HTML forms themselves. Indeed, an HTTP GET will send data in the request URL (query string), where an HTTP POST will be sent with a body that contains all data encoded by default as URL parameters (that is, x-www-url-encoded). So, we can now give an overview of what the bindFromRequest method does. When we ask a form to be filled in with data, this method will: Gather data as URL-form encoded data, if any Gather data from parts (if the content type is multipart-data) Gather data as JSON-encoded, if any Gather data from the query string (that's why GET requests were working as well)/p> Fill in the form's data with all of them (and validate) You might be wondering the worth of such annotations; the quick answer to that is they allow new types of parsers, but they can also enforce certain actions' requests to match a given content type. Another advantage of such annotations is that they allow us to extend or narrow the length of the body that can be handled. By default, 100 K are accepted, and this can be either configured (parsers.text.maxLength=42K) or passed as an argument to the annotation. With all of this in mind, we are now ready to implement these concepts in our code, and what we're going to do is to update our code base to create a kind of forum. A forum where one can log in, initiate a chat, reply to non-closed ones (based on their date), or even attach files to them. Creating a forum In this section, we'll refactor our existing application in order to enable it to act as a forum. And, chances are high that it won't be necessary to learn anything new; we'll just re-use the skills gathered so far; but we'll also use the parsing commodities that Play! 2 offers us. Reorganizing and logging in The very first thing we have to do is to enable a user to log in; this ability was already created in the Data controller. However, for that, we'll update our Application controller a bit, to create a new index action that will check whether a user is logged in or not. So, index is now the new entry point of the application and can be routed from / in the routes file. And, it's solely meant to check if a user has logged in or not. This check is based on the session content, as we simply check whether a user's e-mail is present in the session. We never see what a session can be in Play! 2, but we saw that Play! 2 is completely stateless. So, a session in Play! 2 is only an encrypted map of the value stored in the cookie. Thus it cannot be that big, and definitely cannot contain full data. If the user is present, we redirect the request to the chatroom by calling redirect with the expected action. This will prevent the browser from posting the request again if the user reloads the page. This method is called POST-redirect-GET. Otherwise, we respond with an Unauthorized HTTP response (401) that contains the HTML login page. The two actions (shown in the next screenshot) are so simple that we won't cover them further, except for a single line: session().clear(). It is simply revoking the cookie's content, which will require the subsequent request to create a new one, which then doesn't contain the previously stored e-mail. And finally, enter, which shows how a request's body can easily be handled using the relevant method: asFormUrlEncoded. It should look like that shown in the following screenshot: Indeed, one would normally have to use a form to retrieve this information for us, which would do it for us (behind the scenes); but in this case we have only a single parameter to retrieve, so a form would be overkill. So far, so good; we are now able to create a user, log in with it, and use a login page. To target having cleaner code, it would be worth splitting the Data controller code into several pieces (matter of a good separation of subject). Hence, the Users controller is created, in which will be placed the user-related actions taken out of Data. Now, we'll move back to something we saw earlier but didn't cover—the routes. Chats.allChats() action call. Chatting In the previous section, we were introduced to the Chats controller and its allChats action. If the names are self-descriptive, the underlying code isn't that much. First of all, we're now dealing with Chat instances that must be persisted somewhere in a database, along with their underlying items. But we'll also prepare for the next section, which relates to multipart data (for instance, it's helpful for file upload). That's why we'll add a brand new type, Image, which is also linked to Chat. Having said that, it would be worth checking our new chat implementation: Before we cover the Item and Image types, we'll first go to the Chats controller to see what's going on. Finally, we can see our allChats action; it's simply rendering all existing instances within a template. Even the rest of the controller is simple; everything is done in templates, which are left as exercises (we're so good at them now!). However, there's still the loadChat action that contains something related to this article: Long chatId = Long.parseLong(queryString.get("chatid")[0]); This action handles requests asking to show a particular Chat instance, which is a resource and thus should be served using a GET request. This implies that the parameter value is stored in the query string (or in the URL itself) rather than in the request body. Regarding query string access, it's more interesting to analyze the following line: Map<String,String[]> queryString = request().queryString(); In fact, all actions contextually refer to a request object, which is accessible using the request() method. This request object declares a queryString() method that returns a map of string and an array of strings. What comes next is trivial; we just get chatid out of this map (ok... in a very unsafe way). Until now, we have been able to log in and access the chatroom, where we can create or show chat instances. But we're still unable to reply to a chat. That's what will be tackled now. For that, we need to create an action that will, based on a chat ID, post a new message linked to the logged in user, and then attach this message as an item of the underlying Chat instance. For this, we must update the Item class with persistence information. Afterwards, we'll be able to update the Chats controller in order to create instances. Ok, it's like a beefed-up POJO; let's jump into the action that will create Item instances. The workflow to post a message for a user starts by enabling him/her to participate in a chat. This is done by loading it (using the loadChat action) where the user will be able to post a new message (an overview of the UI will be presented at the end of this article for illustration only). The following screenshot shows how it can be done: Observe how the user was recovered using the session. Still, nothing cumbersome to review here, we've just re-used a lot of stuff we've already covered. The action receives a POST request in which information about the message is given, and then we can bind the request to itemForm and finally save to the database the item contained in the resulting form. At most, we should notice that we're still free to encode the body as we want, and also that the chat ID is not a part of the form but a part of the action signature—that's because it is a part of the URL (routing). We've almost finished our forum; the only thing needed is to enable users to post images. Handling multipart content types The HTTP protocol is ready to accept, from a client, a lot of data and/or large chunks of data, at once. A way to achieve this is to use a specific encoding type: multipart/form-data. Such requests will have a body that can hold several data pieces formatted differently and attributed with different names. So, Play! 2 is a web framework that fits into HTTP as much as possible; that's why it deals with such requests goods, and provides an API that hides almost all of the tricky parts. In this section, we'll see how one could upload an image along with some caption text that will be attached to a specific chat. Before diving into the workflow, let's first create the holding structure: Image. This newly introduced type is not hard to understand as well; only two things should be pointed out: The pic() method that relies on the filePath field to recover the file itself. It uses a File instance to memorize subsequent calls. The enum type that prepares the action logic to filter the incoming files based on the given MIME type. This logic could also be defined in the validate method. These instances are always locked in with the connected user who uploaded it and will be added to a Chat instance. This will allow a chatroom to display all attached images with their caption beside the messages themselves. Now we're ready to look at the file upload itself by paying some attention to the last action of the Chats controller, that is, receiveImage. As we are used to simplifying the code (Play! 2 is there to ease our work, after all) and to get straight to the point, we reflected this in our receiveImage action.. In a very few lines, we declared a new action that expects requests to be multipart encoded containing at least two parts, where the first is a map of data (no matter how this map is encoded) to fill in imageForm (essentially a caption). The second will be the image part. After binding the request with the form and verifying that no errors have occurred, we can move to the body content in order to recover the binary data that was sent along with its metadata: the file content, its content type, its length, and so on. That was quite an intuitive thing to do – asking the body to be parsed as a multipart/multidata and and get it as an Http.MultipartFormData object, which has a getFile method that returns an Http.MultipartFormData.FilePart value. To understand why we didn't specify a body parser, recall that Play! 2 is able, most of the time, to discover which method fits best by itself. The Http.MultipartFormData. FilePart type is not only allowing us to recover the content as a file, but also its key in the multipart body, its filename header, and (especially) its content type. Having all of these things in hand, we are now able to check the content-type validity against the image's enum, and to store the image by getting the file path of the provided file. This file path will target the Temp directory of your machine. In the real world, the file should be relocated in a dedicated folder or maybe on an S3 repository. Et voilà! We have now learned about some of the features that can provide a very simple forum. The following screenshot shows what it could look like (without any efforts on the design, of course). First, the forms to show and enter archived and active chats: On entering an active chat, let's say the one named Today, we reach a page similar to the one shown next: Using the Attach an image form, we can select an image on our filesystem to be sent to the server. The result obtained is shown as follows: Until now, we have spoken about handling various content types coming from the outside world, but what about our application having to render content other than HTML? That's what we're about to see next.
Read more
  • 0
  • 0
  • 1381

article-image-what-openlayers
Packt
13 May 2013
4 min read
Save for later

What is OpenLayers?

Packt
13 May 2013
4 min read
(For more resources related to this topic, see here.) As Christopher Schmidt, one of the main project developers, wrote on the OpenLayers users mailing list: OpenLayers is not designed to be usable out of the box. It is a library designed to help you to build applications, so it's your job as an OpenLayers user to build the box. Don't be scared! Building the box could be very easy and fun! The only two things you actually need to write your code and see it up and running are a text editor and a common web browser. With these tools you can create your Hello World web map, even without downloading anything and writing no more than a basic HTML template and a dozen line of JavaScript code. Going forward, step-by-step, you will realize that OpenLayers is not only easy to learn but also very powerful. So, whether you want to embed a simple web map in your website or you want to develop an advanced mash-up application by importing spatial data from different sources and in different formats, OpenLayers will probably prove to be a very good choice. The strengths of OpenLayers are many and reside, first of all, in its compliance with the Open Geospatial Consortium ( OGC ) standards, making it capable to work together with all major and most common spatial data servers. This means you can connect your client application to web services spread as WMS, WFS, or GeoRSS, add data from a bunch of raster and vector file formats such as GeoJSON and GML, and organize them in layers to create your original web mapping applications. From what has been said until now, it is clear that OpenLayers is incredibly flexible in reading spatial data, but another very important characteristic is that it is also very effective in helping you in the process of optimizing the performances of your web maps by easily defining the strategies with which spatial data are requested and (for vectors) imported on the client side. FastMap and OpenLayers make it possible to obtain them! As we already said at the beginning, web maps created with OpenLayers are interactive, so users can (and want to) do more than simply looking at your creation. To build this interactivity, OpenLayers provides you with a variety of controls that you can make available to your users. Tools to pan, zoom, or query the map give users the possibility to actually explore the content of the map and the spatial data displayed on it. We could say that controls bring maps to life and you will learn how to take advantage from them in a few easy steps. Fast loading and interactivity are important, but in many cases a crucial aspect in the process of developing a web map is to make it instantly readable. Isn't it useful to build web maps if the users they are dedicated to need to spend too much time before understanding what they are looking at? Fortunately, OpenLayers comes with a wide range of possibilities to styling features in vector layers. You can choose between different vector features, rendering strategies, and customize every aspect of their graphics to make your maps expressive, actually "talking" and—why not?—cool! Finally, as you probably remember, OpenLayers is pure JavaScript, and JavaScript is also the language of a lot of fantastic Rich Internet Application ( RIA) frameworks. Mixing OpenLayers and one of these frameworks opens a wide range of possibilities to obtain very advanced and attractive web mapping applications Resources for Article : Further resources on this subject: Getting Started with OpenLayers [Article] OpenLayers: Overview of Vector Layer [Article] Getting Started with OpenStreetMap [Article]
Read more
  • 0
  • 0
  • 6730
article-image-tips-and-tricks
Packt
09 May 2013
7 min read
Save for later

Tips and Tricks

Packt
09 May 2013
7 min read
(For more resources related to this topic, see here.) Adding more template files to your theme Let's say our site needed to display posts from a specific category differently from the rest of the site, or we needed the home page to work differently, or maybe we wanted to have more control over how search results or 404 pages were displayed. With template files, we can do all that. A search.php file for search results WordPress handles search results pretty well already. Let's see what's displayed in our theme if we try to search for example post (Note that we've now added a Search widgetto the right-hand side footer widget area to make this possible): As you can see, it' s using our index.php template file, so the heading reads This Month:.We'd rather make it more obvious that these are search results. Now let's see what happens if we search for something that can't be found: Again, the heading isn't great. Our theme gives the user a message telling them what's happened (which is coded into index.php as we'll see), but we could beef that up a bit,for example by adding a list of the most recent posts. Time for action – creating a search.php template file Let's create our search.php file and add some code to get it working in the way we'dlike it to: In your theme folder, make a copy of index.php and call it search.php. Find the following code near the top of the file: <h2 class="thisMonth embossed" style="color:#fff;">This Month:</h2> Edit the contents of the h2 element so the line of code now reads: <h2 class="thisMonth embossed" style="color:#fff;">Searchresults:</h2> Find the loop. This will begin with: <?php if (have_posts()) :?><?php while (have_posts()) : the_post();?> The first section of the loop displays any posts found by the search, leave this as itis. The second section of the loop specifies what happens if no search results are found. It's in the following lines of code: <?php else : ?><h2 class="center">Not Found</h2><p class="center">Sorry, but you are looking for somethingthat isn't here.</p><?php get_search_form(); ?><?php endif; ?> Underneath the line that reads <?php get_search_form(); ?> and before <?php endif; ?>, add the following lines of code: <?php endif; ?>, add the following lines of code:<h3>Latest articles:</h3><?php $query = new WP_Query( array ( 'post_type' => 'post', 'post_count' => '5' ) );while ( $query->have_posts() ) : $query->the_post(); ?><ul><li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li></ul><?php endwhile; ?> Save your search.php file and try searching for something which isn't included in the site. What just happened? We created a new template file called search.php, which will be used to display theresults of a site search. We then edited the heading to make it clearer, and added somecode to display the latest posts if the search had no results. We actually did something pretty advanced, we added a second loop inside our original loop. Let's have a look at the code we added after the search form: The function $query = new WP_Query() runs a new query on the database, based on the WordPress WP_Query function, which is the function you should use when running a loop inside the main loop. We gave WP_Query the following parameters: 'post_type' => 'post' – this ensures that the query will only look for posts, not for any other kind of content. 'post_count' => '5' – this tells WordPress how many posts to show. Five, in this case. We then output the title of each post with the php the_title() tag whichwe've already used higher up in the loop to display post titles. We wrapped this in a link inside a list item. The link uses the_permalink() to link to the blog post whose title is displayed. This is very similar to the main loop. Finally, we added endwhile() to stop this loop. This doesn't replace theendwhile() at the end of our main loop, which is higher up in the file. For more on WP_Query and how to use it to create multiple loops, see http://codex.wordpress.org/Class_Reference/ WP_Query. Let's have a look at what our users will see when they do a search now. First,a successful search: Next, an unsuccessful search: So that's how we set up a template file for search results. Our search page is only displayingtwo posts because that's all we have on our site. If there were more than five, it would justdisplay the five most recent. Now let's set one up to display some pages differently. Creating a custom page template In many themes, all pages will need the same basic layout and content, with the same sidebarsand footer and the same styling. But sometimes you may need some pages to look different. For example, you might want to use different sidebars in different pages, or you might wanta different layout. Here we'll look at the second of those two options. Time for action – creating a custom page template Imagine that you have some pages containing a lot of content which you want to displayacross the full width of the page, without the sidebar getting in the way. The way to handlethis is to create a page template which doesn't include the sidebar, and then select thatpage template when you're creating or editing those pages. Let's try it out. In the same folder as your other theme files, make a copy of your page.php file and call it page-no-sidebar.php. At the very top of the file, above the line reading <?php get_header(); ?>,insert the following code: <?php/*Template Name: Full width page without sidebar*/?> Find the following line of code: <div class="content left two-thirds"> Edit it so it reads: <div class="content left full"> Now find the line that reads <?php get_sidebar(); ?> and delete it. Save your file. What just happened? We created a new template file called page-no-sidebar.php, and edited it to displaycontent differently from our default page template: We edited the classes for our .content div, using the object-oriented approach to styling used by the layout-core.css file. This will apply styling for the .fullclass to this div, so that it displays a full width instead of two-thirds of its containing element. We removed the line calling the get_sidebar include, so that it won't be displayed on any pages using this template. The lines we added at the top are essential for WordPress to pick up on our page templateand make it available in the WordPress admin. Page editors will see a drop-down list of pagetemplates available, and the name we defined in the template is what they'll see in that list,as shown in the following screenshot: As you can see, in the Page Attributes box to the right-hand side, a new select box has appeared called Template. Our new page template is listed in that select box, along withDefault Template, which is page.php. Now we can try it out by assigning this template to a page and seeing how it looks.
Read more
  • 0
  • 0
  • 1969

article-image-converting-tables-graphs-advanced
Packt
06 May 2013
7 min read
Save for later

Converting tables into graphs (Advanced)

Packt
06 May 2013
7 min read
(For more resources related to this topic, see here.) Getting ready We maintained the same structure for our table, however this time we do not use this example and load it via AJAX. So the markup looks as follows: <table id="dynamicTable" class="table"> <thead> <tr> <th>Reviews</th> <th>Top</th> <th>Rolling Stones</th> <th>Rock Hard</th> <th>Kerrang</th> </tr> </thead> <tbody> <tr> <th>Ac/Dc</th> <td>10</td> <td>9</td> <td>8</td> <td>9</td> </tr> <tr> <th>Queen</th> <td>9</td> <td>6</td> <td>8</td> <td>5</td> </tr> <tr> <th>Whitesnake</th> <td>8</td> <td>9</td> <td>8</td> <td>6</td> </tr> <tr> <th>Deep Purple</th> <td>10</td> <td>6</td> <td>9</td> <td>8</td> </tr> <tr> <th>Black Sabbath</th> <td>10</td> <td>5</td> <td>7</td> <td>8</td> </tr> </tbody> </table> How to do it... Let's see what we need to do: Add a div right on the top of our table with an ID called graph: <div id="graph"></div> We will use a jQuery Plugin called Highcharts, which can be downloaded for free from http://www.highcharts.com/products/highcharts. Add the following script to the bottom of our document: <script src = "highcharts.js"></script> Add a simple script to initialize the graph as follows: var chart; Highcharts.visualize = function(table, options) { // the data series options.series = []; var l= options.series.length; options.series[l] = { name: $('thead th:eq('+(l+1)+')', table).text(), data: [] }; $('tbody tr', table).each( function(i) { var tr = this; var th = $('th', tr).text(); var td = parseFloat($('td', tr).text()); options.series[0].data.push({name:th,y:td}); }); chart = new Highcharts.Chart(options); } // On document ready, call visualize on the datatable. $(document).ready(function() { var table = document.getElementById('dynamicTable'), options = { chart: { renderTo: 'graph', defaultSeriesType: 'pie' }, title: { text: 'Review Notes from Metal Mags' }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: false }, showInLegend: true } }, tooltip: { pointFormat: 'Total: <b>{point.percentage}%</ b>', percentageDecimals: 1 } }; Highcharts.visualize(table, options); }); Many people choose to hide the div with the table in smaller devices and show only the graph. Once they've optimized our table and depending on the amount of data, there is no problem. It also shows that the choice is yours. Now when we look at the browser, we can view both the table and the graph as shown in the following screenshot: Browser screenshot at 320px. Highcharts plugins have an excellent quality in all browsers and works with SVG, they are compatible with iPad, iPhone, and IE 6. How it works... The plugin can generate the table using only a single data array, but by our intuition and step-by-step description of its uses, we have created the following code to generate the graph starting from a table previously created. We create the graph using the id#= dynamicTable function, where we read its contents through the following function: $('tbody tr', table).each( function(i) { var tr = this; var th = $('th', tr).text(); var td = parseFloat($('td', tr).text()); options.series[0].data.push({name:th,y:td}); }); In the plugin settings, we set the div graph to receive the graph after it is rendered by the script. We also add a pie type and a title for our graph. options = { chart: { renderTo: 'graph', defaultSeriesType: 'pie' }, title: { text: 'Review Notes from Metal Mags' }, There's more... We can hide the table using media query so that only the graph appears. Remember that it just hides the fact and does not prevent it from being loaded by the browser; however we still need it to build the graph. For this, just apply display none to the table inside the breakpoint: @media only screen and (max-width: 768px) { .table { display: none; } } Browser screenshot at 320px, without the table Merging data – numbers and text (Advanced) We introduce an alternative based on CSS3 for dealing with tables containing text and numbers. Getting ready Tables are used for different purposes, we will see an example where our data is not a data table. (Code Example: Chapter07_Codes_1 ) Browser screenshot at 1024px Although our table did not have many columns, showing it on a small screen is not easy. Hence we will progressively show the change in the table by subtracting the width of the screen. How to do it... Note that we have removed the .table class so this time apply the style directly in the table tags, see the following steps: Let's use a simple table structure as we saw before. Add some CSS3 to make some magic with our selectors. Set our breakpoints to two sizes. <table> <thead> <tr> <th>CONTACT</th> <th scope="col">Manager</th> <th scope="col">Label</th> <th scope="col">Phone</th> </tr> </thead> <tbody> <tr> <th scope="row">Black Sabbath</th> <td>Richard Both</td> <td>Atlantic</td> <td>+1 (408) 257-1500 </td> </tr> <tr> <th scope="row">Ac/DC</th> <td>Paolla Matazo</td> <td>Sony</td> <td>+1 (302) 236-0800</td> </tr> <tr> <th scope="row">Queen</th> <td>Suzane Yeld</td> <td>Warner</td> <td>+1 (103) 222-6754</td> </tr> <tr> <th scope="row">Whitesnake</th> <td>Paul S. Senne</td> <td>Vertigo</td> <td>+1 (456) 233-1243</td> </tr> <tr> <th scope="row">Deep Purple</th> <td>Ian Friedman</td> <td>CosaNostra</td> <td>+1 (200) 255-0066</td> </tr> </tbody> </table> Applying the style as follows: table { width: 100%; background-color: transparent; border-collapse: collapse; border-spacing: 0; background-color: #fff } th { text-align: left; } td:last-child, th:last-child { text-align:right; } td, th { padding: 6px 12px; } tr:nth-child(odd), tr:nth-child(odd) { background: #f3f3f3; } tr:nth-child(even) { background: #ebebeb; } thead tr:first-child, thead tr:first-child { background: #000; color:white; } table td:empty { background:white; } We use CSS3 pseudo-selectors here again to help in the transformation of the table. And the most important part, the Media Queries breakpoints: @media (max-width: 768px) { tr :nth-child(3) {display: none;} } @media (max-width: 480px) { thead tr:first-child {display: none;} th {display: block} td {display: inline!important;} } When the resolution is set to 768px, we note that the penultimate column is removed. This way we keep the most relevant information on the screen. We have hidden the information less relevant to the subject. And when we decrease further, we have the data distributed as a block. Summary In this article, we saw an alternative solution combining the previous recipes with another plugin for rendering graphics. Resources for Article : Further resources on this subject: MySQL 5.1 Plugin: HTML Storage Engine—Reads and Writes [Article] Creating Accessible Tables in Joomla! [Article] HTML5: Generic Containers [Article]
Read more
  • 0
  • 0
  • 4605

article-image-creating-website-artisteer
Packt
30 Apr 2013
5 min read
Save for later

Creating a website with Artisteer

Packt
30 Apr 2013
5 min read
(For more resources related to this topic, see here.) Layout The first thing that we should set up while designing a new website is its width. If you are interested in creating web pages, you probably have a monitor with a large widescreen and good resolution. But we have to remember that not all of your visitors will have such good hardware. All the templates generated by Artisteer are centered, and almost all modern browsers enable you to freely zoom the page. It's far better to let some of your visitors enlarge the site than to make the rest of them use the horizontal scroll bar while reading. The resolution you choose will depend on the target audience of your site. Usually, private computers have better parameters than the typical PCs used for just office work in companies. So if you design a site that you know will be viewed mostly by private individuals, you can choose a slightly wider layout than you might for a typical business site. But you cannot forget that many nonbusiness websites, such as community sites, are often accessed from offices. So what is the answer? In my opinion, a layout with a width of 1,000 pixels is still a good choice for most of the cases. Such width ensures that the site will be displayed correctly on a pretty old, but still commonly used, nonwide 17'' monitor. (The typical resolution for this hardware is 1,024 x 768 and such a layout will fill the whole screen.) As more and more users have now started using computers that are equipped with a far better screen, you can consider increasing the resolution slightly, to, for example, 1,150 pixels. Remember that not every user will visit your site using a desktop. Many laptops, and especially netbooks and tablets, don't have wide screens either. Remember that the width of the page must be a little lower than the total resolution of the screen. You should reserve some space for the vertical scrollbar. We are going to set up the width of our project traditionally to 1,000 pixels. To do this, click on the Layout tab on the ribbon, and next to the Sheet Width button. Choose 1000 pixels from the available options on the list. The Sheet Options window is divided into two areas: on the left you can choose from the values expressed in pixels, while on the right, as a percentage. The percentage value means that the page doesn't have a fixed width, but it will change according to the parameters of the screen it is displayed on (according to the chosen percentage value). Designing layouts with the width defined in percentage might seem to be a great idea; and indeed, this technique, when properly used, can lead to great results. But you have to remember, that in such a case, all page elements have to be similarly prepared in order, to be able to adapt to the dynamically changing width of the site. It is far simpler to achieve good results for the layout with fixed values (expressed in pixels). It is a common rule while working with Artisteer that after clicking on a button on the ribbon, you get the list containing the most commonly used standard values. If you need a custom value, however, you can click on the button located at the bottom of the list to go to a window where you can freely set up and choose the required value. For example, while choosing the width of a layout, clicking on the More Sheet Widths... button (located just under the list) will lead you to a window where you can set up the required width with an accuracy up to 1 pixel. We can set the required value in three ways: We can click on the up and down arrows that are located on the right side of the field. We can move the mouse cursor on the field and use the slider that appears. We can click on the field. The text cursor will appear. Then we can type the required value using the keyboard. For me, this is the most comfortable way, especially since the slider's minimal progress is more than 1. Panel mode versus windows mode If you look carefully at the displayed windows, on the bottom-right corner you will see a panel mode button. This button switches Artisteer's interface between panel mode and windows mode. In the windows mode, the advanced settings are displayed in windows. In the panel mode, the advanced settings are displayed on the side panel located on the right side of Artisteer's window. If you are using a wide screen, you may find the panel mode to be more comfortable. Its advantage is that the side panel doesn't cover anything on your project, so you have a better view to observe the changes. Such a change is persistent and if you switch to the panel mode, all the advanced settings will be displayed in the right panel, as long as you decide to go back into the windows mode. To reverse, find and click on the icon located in the top-right corner of the side panel (just next to the x button that closes the panel). Summary This article has covered some features exclusive to Artisteer. It has also explained a brief process of how to create stunning templates for websites using Artisteer. Resources for Article : Further resources on this subject: Creating and Using Templates with Cacti 0.8 [Article] Using Templates to Display Channel Content in ExpressionEngine [Article] Working with Templates in Apache Roller 4.0 [Article]
Read more
  • 0
  • 0
  • 1425
article-image-getting-started-modernizr-using-php-ide
Packt
30 Apr 2013
5 min read
Save for later

Getting started with Modernizr using PHP IDE

Packt
30 Apr 2013
5 min read
(For more resources related to this topic, see here.) From the Modernizr website: Modernizr is a small JavaScript library that detects the availability of native implementations for next-generation web technologies, i.e. features that stem from the HTML5 and CSS3 specifications. Many of these features are already implemented in at least one major browser (most of them in two or more), and what Modernizr does is, very simply, tell you whether the current browser has this feature natively implemented or not. Basically with this library, we can see if the user's browser can support certain features you wish to use on your site. This is important to do, as unfortunately not every browser is created the same. Each one has its own implementation of the HTML5 standard, so some features may be available on Google Chrome but not on Internet Explorer. Using Modernizr is a better alternative to the standard, but it is unreliable, user agent (UA) string checking. Let's begin. Getting ready Go ahead and create a new Web Project in Aptana Studio. Once it is set up, go ahead and add a new folder to the project named js. Next thing we need to do is to download the Development Version of Mondernizr from the Modernizr download page (http://modernizr.com/download/). You will see options to build your own package. The development version will do until you are ready for production use. As of this writing, the latest version is 2.6.2 and that will be the version we use. Place the downloaded file into the js folder. How to do it... Follow these steps: For this exercise, we will simply do a browser test to see if your browser currently supports the HTML5 Canvas element. Type this into a JavaScript file named canvas.js and add the following code: if (Modernizr.canvas) { var c=document.getElementById("canvastest"); var ctx=c.getContext("2d"); // Create gradient Var grd=ctx.createRadialGradient(75,50,5,90,60,100); grd.addColorStop(0,"black"); grd.addColorStop(1,"white"); // Fill with gradient ctx.fillStyle=grd; ctx.fillRect(10,10,150,80); alert("We can use the Canvas element!"); } else { alert("Canvas Element Not Supported"); } Now add the following to index.html: <!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Canvas Support Test</title> <script src = "js/modernizr-latest.js" type="text/ javascript"></script> </head> <body> <canvas id="canvastest" width="200" height="100" style="border:1px solid #000000">Your browser does not support the HTML5 canvas tag.</canvas> <script src = "js/canvas.js"> </script> </body> </html> Let's preview the code and see what we got. The following screenshot is what you should see: How it works... What did we just do? Well, let's break it down: <script src = "js/modernizr-latest.js" type="text/javascript"></script> Here, we are calling in our Modernizr library that we downloaded previously. Once you do that, Modernizr does some things to your page. It will redo your opening <html> tag to something like the following (from Google Chrome): <html class=" js flexbox flexboxlegacy canvas canvastext webgl notouch geolocation postmessage websqldatabase indexeddb hashchange history draganddrop websockets rgba hsla multiplebgs backgroundsize borderimage borderradius boxshadow textshadow opacity cssanimations csscolumns cssgradients cssreflections csstransforms csstransforms3d csstransitions fontface generatedcontent video audio localstorage sessionstorage webworkers applicationcache svg inlinesvg smil svgclippaths"> This is all the features your browser supports that Modernizr was able to detect. Next up we have our <canvas> element: <canvas id="canvastest" width="200" height="100" style="border:1px solid #000000">Your browser does not support the HTML5 canvas tag.</ canvas> Here, we are just forming a basic canvas that is 200 x 100 with a black border going around it. Now for the good stuff in our canvas.js file, follow this code snippet: <script> if (Modernizr.canvas) { alert("We can use the Canvas element!"); var c=document.getElementById("canvastest"); var ctx=c.getContext("2d"); // Create gradient var grd=ctx.createRadialGradient(75,50,5,90,60,100); grd.addColorStop(0,"black"); grd.addColorStop(1,"white"); // Fill with gradient ctx.fillStyle=grd; ctx.fillRect(10,10,150,80); } else { alert("Canvas Element Not Supported"); } </script> In the first part of this snippet, we used an if statement to see if the browser supports the Canvas element. If it does support canvas, then we are displaying a JavaScript alert and then filling our canvas element with a black gradient. After that, we have our else statement that will alert the user that canvas is not supported on their browser. They will also see the Your browser does not support the HTML5 canvas tag message. That wasn't so bad, was it? There's more... I highly recommend reading over the documentation on the Modernizr website so that you can see all the feature tests you can do with this library. We will do a few more practice examples with Modernizr, and of course, it will be a big component of our RESS project later on in the book. Keeping it efficient For a production environment, I highly recommend taking the build-a-package approach and only downloading a script that contains the tests you will actually use. This way your script is as small as possible. As of right now, the file we used has every test in it; some you may never use. So, to be as efficient as possible (and we want all the efficiency we can get in mobile development), build your file with the tests you'll use or may use. Summary This article provided guidelines on creating a new Web Project in Aptana Studio, creating new folder to the project named js, downloading the Development Version of Mondernizr from the Modernizr download page, and placing the downloaded file into the js folder. Resources for Article : Further resources on this subject: Let's Chat [Article] Blocking versus Non blocking scripts [Article] Building Applications with Spring Data Redis [Article]
Read more
  • 0
  • 0
  • 1713

article-image-basic-use-local-storage
Packt
26 Apr 2013
5 min read
Save for later

Basic use of Local Storage

Packt
26 Apr 2013
5 min read
(For more resources related to this topic, see here.) Getting ready For this article, all you need is your browser and favorite text editor. How to do it... Perform the following steps: Let's begin with creating a blank document in your text editor. Then, add the following code and save it as a test localdemo.html: <!DOCTYPE html> <html> <head> <script src = "http://code.jquery.com/jquery-1.8.1.min.js"></script> <script type="text/javascript"> </script> </head> <body> </body> </html> In between the <script> tags, add the following function. This copes with storing the information within the browser. <script type="text/javascript"> function storeItem() { var item = $('#item').val(); var items = localStorage.getItem('myItems'); if (items != null) { items = JSON.parse(items); } else { items = new Array(); } items.push(item); localStorage.setItem('myItems', JSON.stringify(items)); refresh(); } </script> We need to add another function to retrieve information and refresh the content displayed on screen. So go ahead and update the script as highlighted: <script type="text/javascript"> function storeItem() { var item = $('#item').val(); var items = localStorage.getItem('myItems'); if (items != null) { items = JSON.parse(items); } else { items = new Array(); } items.push(item); localStorage.setItem('myItems', JSON.stringify(items)); refresh(); } function refresh() { var items = localStorage.getItem('myItems'); var ul = $('ul'); ul.html(''); if (items != null) { items = JSON.parse(items); $(items).each(function (index, data) { ul.append('<li>' + data + '</li>'); }); } } $(function () { refresh(); }); </script> We finish by adding a basic form—while the purists amongst you will notice that it doesn't have all of the proper forms of tag, it is enough to illustrate how this demo works. Add the following code snippet, just above the closing </body> tag: Enter item: <input type="text" id="item" /> <input type="button" value= "store" onclick="storeItem()" /> <br /> <ul></ul> Crack open your browser and preview the results. Here's a screenshot of what you should see, with some example values already entered: How it works... Now we've seen Local Storage in action, let's take a look at how it works in detail. HTML5 Local Storage works on the principle of named key/value pairs, where you store information using a named key and retrieve it by calling that named key. Everything is stored locally on the user's PC; it cuts down the need to retrieve information from the server, thereby acting as a form of caching. You may have noticed that we've used jQuery in this article—basic use of LocalStorage (and SessionStorage) doesn't necessarily need jQuery; you could use pure JavaScript if you prefer. It all depends on your requirements; if you are already using jQuery in your pages, for example, you may prefer to use this over JavaScript. (You will see I have used a mix of both throughout this book, to show you how you can use either jQuery or JavaScript). In this article, we've used jQuery to reference LocalStorage; if you take a look at the code, you will see two lines of particular importance: var items = localStorage.getItem('myItems'); localStorage.setItem('myItems', JSON.stringify(items)); These two handle the retrieval and setting of values respectively. In this demo, we begin with either fetching the contents of any existing stored information and inserting them into an array, or creating a new one, if nothing exists within the store. We then use JSON. stringify() to convert information from the form into a string, push this into the storage, and then refresh the page so that you can see the updated list. To get the information back, we simply repeat the same steps, but in the reverse way. The beauty of using JSON as part of storing information in this way is that you are not entirely limited to just plain text; you can store some other things in the LocalStorage area, as we will see later in this book. There's more... By now, you will start to see that using Local Storage works very much in the same way that cookies do—indeed some people often refer to Local Storage as "cookies on steroids". This said, there are still some limitations that you need to be aware of when using Local Storage, such as the following: Local Storage will only support text as a format and is set to a suggested arbitary limit of 5 MB, although this is inconsistent across browsers. If you exceed this, the QUOTA_EXCEEDED_ERR error is thrown. At the time of writing this book, there is no support built in for requesting more space. Some browsers such as Opera will allow the user to control each site's quota, but this is a purely userbased action. Web Storage is no more secure than cookies; although use of the HTTPS protocol can resolve a lot of security issues, it is still up to you as a developer to ensure that sensitive information (such as passwords) is not sent to or stored locally on the client using Web Storage. With careful use, we can take advantage of the ability to store relevant information on a user's PC, and avoid the need to push it back to the server. Once the information has been stored, there will be occasions when you will need to view the raw information from within your browser—this is easy enough to do, although the method varies from browser to browser, which we will see as part of the next article. Summary In this article we discussed basic use of HTML5 Local Storage. Resources for Article : Further resources on this subject: Blocking versus Non blocking scripts [Article] Building HTML5 Pages from Scratch [Article] HTML5 Games Development: Using Local Storage to Store Game Data [Article]
Read more
  • 0
  • 0
  • 3745