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-wordpress-3-security-apache-modules
Packt
10 Jun 2011
6 min read
Save for later

WordPress 3 Security: Apache Modules

Packt
10 Jun 2011
6 min read
  WordPress 3 Ultimate Security Protect your WordPress site and its network         Read more about this book       (For more resources on WordPress, see here.) IP deny with mod_access Apache offers a sure-fire way to lock down admin, care of the mod_access module. Similar to cPanel's IP Deny Manager, the greater flexibility of hand-coding empowers us to allow or deny all but specified IP addresses, domains, hosts, and networks. For now, we'll prevent access to the wp-admin directory pages for all IPs except yours. Open an htaccess file in your wp-admin directory via your control panel or the terminal: nano /path/to/WP-root/wp-admin/.htaccess Add these lines, swapping the IP for yours: order deny,allowdeny from allallow from 123.45.67.890 Need access from more IPs? Just add more alongside the first one, single space separated. But. If your IP address is dynamic, which very often it is, you may find this method a little too effective. If you do become locked out, cruise server-side to switch the IP. What is my IP? That old chestnut: whatismyip – http://whatismyip.com IP spoofing A chestnut gone bad, denying alone won't protect against man-in-the-middle attacks, so if you got this farthinking that you could have avoided all the SSL stuff after all, no, you were right to do that. No safeguard is a silver bullet. Deny syntax sure helps though, if you're not on the move.   Password protect directories Password protection is a way to give access to a directory and its sub-tree to a selected few people and may be used, typically: To house private files to which you need access from anywhere By developers fine-tuning a new blog theme For a client zone on a commercial site As an extra layer of protection to, say, wp-login or phpMyAdmin The procedure is to choose a directory, granting access to specified users. These privileged directory users are separate from, and should not be confused with, your server or WordPress users, the control being governed by Apache rather than by Linux or your WordPress database. That's a good thing, adding an independent tier of protection. cPanel's Password Protect Directories There are various ways to secure a directory, so let's start off with the regular control panel option, which in cPanel, is called Password Protect Directories: Browse to the target directory in File Manager, right-clicking and choosing Password Protect (or click through the panel icon if you like). Select the checkbox and give the directory a name to appear on the authentication screen. Save and you are redirected to a confirmation page. Click back to the previous page and add a username and password to access the folder. Save the newly authorized user. Now you can surf to that folder or some file within, are asked for credentials, and can log in. So what did we really just do there? Clicked on some shiny icons, added some details, and cPanel interacted a bit over far too many pages. Let's get geeky, it's worth it.   Authentication with mod_auth When we protect a folder, cPanel uses Apache's mod_auth module to amend or create two hidden files, htaccess and passwd. htaccess lives in the folder to protect and passwd lives safely above the web root in the hush-hush htpasswd directory. Using an example file, we can compare our control panel actions with those using the terminal, interacting directly with mod_auth. Cue screenshots, using cPanel we did this: And mod_auth creates the ruleset in the htaccess file, which we equally could just type: AuthType BasicAuthName "Protect me pretty please"AuthUserFile "/home/USERNAME/.htpasswds/public_html/protectme/passwd"Require valid-user Then we did this: And mod_auth yawns a bit while it adds credentials to a password file: johndoe:L9c7m/hO16slA (John's password is encrypted, server-side, but he logs in using the plaintext hackth!s.) Now then. Two points. First, with the syntax learnt or duplicated, it's quicker to bin the middleman and just use the shell. More importantly, by directly chatting up Apache, we have a better array of security tools. To clarify, let's take this a step at a time. The htaccess file Before we look at the mod_auth syntax that goes in htaccess files, a quick aside ... A quick shout out to htaccess, bless We've met the hidden htaccess file already. It's essentially a convenient and versatile web configuration file that can be added to multiple directories. The directives these files contain can equally be placed in other types of files such as those for our virtual hosts (which is tidier, all those directives from htaccess files being in one place). Uniquely, however, rules added in htaccess can be parsed immediately, or in other words, without the need to restart Apache. Feel the power! One other thing about htaccess: you don't need root access to add or edit these files. Listen up, shared hosting people, this is very convenient because you don't have root access (to hack into your co-sharers directories!) to those configuration files, but you do have access to your own jailed (or chroot-ed) web files. And because htaccess files live with your files, you can tweak them at will. Now back to using htaccess to store that mod_auth syntax ... In this case, for any directory you want to protect, just add or append an htaccess file with your tailored mod_auth directives. Here's a closer look at the mod_auth syntax, beginning with its type: AuthType Basic Pretty basic then and more on that later. For when we navigate to the login page we want some kind of instructional message: AuthName "Protect me pretty please" Now the link to the directory's corresponding password file: AuthUserFile "/home/USERNAME/.htpasswds/public_html/DIRECTORY-TOPROTECT/passwd" And we'll specify to give access only to users recorded in the password file: Require valid-user So far so good. Carry on. The passwd file Often referred to as the htpasswd file, here's the syntax it houses: johndoe:L9c7m/hO16slA johndoe is the authorized, or required user. L9c7m/hO16slA is the encrypted form of hackth!s , his password. We use a handy tool, also called htpasswd, to encrypt that. Add as many usernames and passwords as you like to this file, each on a new line. The file itself can live and be called whatever you like as long as the AuthUserFile directive corresponds. One thing though: the file should be located above your web root.  
Read more
  • 0
  • 0
  • 1487

article-image-cocoa-and-objective-c-handling-events
Packt
09 Jun 2011
8 min read
Save for later

Cocoa and Objective-C: Handling events

Packt
09 Jun 2011
8 min read
Some recipes in this article require Mac OS X Snow Leopard 10.6. The Trackpad preferences allow you to easily adjust many gestures that will used in the following recipes. To make sure that your trackpad is recognizing gestures, make sure that you have set the correct preferences to enable gesture support under the Trackpad System Preference. Interpreting the pinch gesture The pinch gesture is a gesture normally used for the zooming of a view or for changing the font size of text. In this recipe, we will create a custom view that handles the pinch gesture to resize a custom view. Getting ready In Xcode, create a new Cocoa Application and name it Pinch. How to do it... In the Xcode project, right-click on the Classes folder and choose Add…, then choose New File… Under the MacOS X section, select Cocoa Class, then select Objective-C class. Finally, choose NSView in the Subclass of popup. Name the new file MyView.m Double-click on the MainMenu.xib file in the Xcode project. From Interface Builders Library palette, drag a Custom View into the application window. From Interface Builders Inspector's palette, select the Identity tab and set the Class popup to MyView. Choose Save from the File menu to save the changes that you have made. In Xcode, Add the following code in the drawRect: method of the MyView class implementation: NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect: [self bounds] xRadius:8.0 yRadius:8.0]; [path setClip]; [[NSColor whiteColor] setFill]; [NSBezierPath fillRect:[self bounds]]; [path setLineWidth:3.0]; [[NSColor grayColor] setStroke]; [path stroke]; Next, we need to add the code to handle the pinch gesture. Add the following method to the MyView class implementation: - (void)magnifyWithEvent:(NSEvent *)event { NSSize size = [self frame].size; size.height = size.height * ([event magnification] + 1.0); size.width = size.width * ([event magnification] + 1.0); [self setFrameSize:size]; } Choose Build and Run from Xcode's toolbar to run the application. How it works... In our drawRect: method, we use Cocoa to draw a simple rounded rectangle with a three point wide gray stroke. Next, we implement the magnifyWithEvent: method. Because NSView inherits from NSResponder, we can override the magnifyWithEvent: method from the NSResponder class. When the user starts a pinch gesture, and the magnifyWithEvent: method is called, the NSEvent passed to us in the magnifyWithEvent: method which contains a magnification factor we can use to determine how much to scale our view. First, we get the current size of our view. We add one to the magnification factor and multiply by the frame's width and height to scale the view. Finally, we set the frame's new size. There's more... You will notice when running the sample code that our view resizes with the lower-left corner of our custom view remaining in a constant position. In order to make our view zoom in and out from the center, change the magnifyWithEvent: method's code to the following: NSSize size = [self frame].size; NSSize originalSize = size; size.height = size.height * ([event magnification] + 1.0); size.width = size.width * ([event magnification] + 1.0); [self setFrameSize:size]; CGFloat deltaX = (originalSize.width - size.width) / 2; CGFloat deltaY = (originalSize.height - size.height) / 2; NSPoint origin = self.frame.origin; origin.x = origin.x + deltaX; origin.y = origin.y + deltaY; [self setFrameOrigin:origin]; Basically, what we have done is moved our custom view's origin by the difference between the original size and the new size. Interpreting the swipe gesture The swipe gesture is detected when three or more fingers move across the trackpad. This gesture is often used to page through a series of images. In this recipe, we will create a custom view that interprets the swipe gesture in four different directions and displays the direction of the swipe in our custom view: Getting ready In Xcode, create a new Cocoa Application and name it Swipe. How to do it... In the Xcode project, right-click on the Classes folder and choose Add…, then choose New File… Under the MacOS X section, select Cocoa Class, then select Objective-C class. Finally, choose NSView in the Subclass of popup. Name the new file MyView.m Double-click on the MainMenu.xib file in the Xcode project. From Interface Builders Library palette, drag a Custom View into the application window. From Interface Builders Inspector's palette, select the Identity tab and set the Class popup to MyView. Choose Save from the File menu to save the changes that you have made. In Xcode, open the MyView.h file and add the direction variable to the class interface: NSString *direction; Open the MyView.m file and add the following code in the drawRect: method of the MyView class implementation: NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect: [self bounds] xRadius:8.0 yRadius:8.0]; [path setClip]; [[NSColor whiteColor] setFill]; [NSBezierPath fillRect:[self bounds]]; [path setLineWidth:3.0]; [[NSColor grayColor] setStroke]; [path stroke]; if (direction == nil) { direction = @""; } NSAttributedString *string = [[[NSAttributedString alloc] initWithString:direction] autorelease]; NSPoint point = NSMakePoint(([self bounds].size.width / 2) - ([string size].width / 2), ([self bounds].size.height / 2) - ([string size].height / 2)); [string drawAtPoint:point]; Add the following code to handle the swipe gesture: - (void)swipeWithEvent:(NSEvent *)event { if ([event deltaX] > 0) { direction = @"Left"; } else if ([event deltaX] < 0) { direction = @"Right"; } else if ([event deltaY] > 0) { direction = @"Up"; } else if ([event deltaY] < 0){ direction = @"Down"; } [self setNeedsDisplay:YES]; } In Xcode, choose Build and Run from the toolbar to run the application. How it works... As we did in the other recipes in this article, we draw a simple rounded rectangle in the drawRect: method of the view. However, we will also be drawing a string denoting the direction of the swipe in the middle of our view. In order to handle the swipe gesture, we override the swipeWithEvent: method from the NSResponder class which NSView inherits. By inspecting the values of deltaX and deltaY of the NSEvent passed into the swipeWithEvent: method, we can determine the direction of the swipe. We set the direction string with the direction of the swipe so we can draw it in the drawRect: method. Finally, we call setNeedsDisplay:YES to force our view to redraw itself. There's more... You might have noticed that we do not need to override the acceptsFirstResponder: method in our view in order to handle the gesture events. When the mouse is located within our view, we automatically receive the gesture events. All we need to do is implement the methods for the gestures we are interested in. Interpreting the rotate gesture The rotate gesture can be used in any number of ways in a custom view. From rotating the view itself or simulating a rotating dial in a custom control. This recipe will show you how to implement the rotate gesture to rotate a custom view. Using your thumb and index finger, you will be able to rotate the custom view around its center: Getting ready In Xcode, create a new Cocoa Application and name it Rotate. How to do it... In the Xcode project, right-click on the Classes folder and choose Add…, then choose New File… Under the MacOS X section, select Cocoa Class, then select Objective-C class. Finally, choose NSView in the Subclass of popup. Name the new file MyView.m. Double-click on the MainMenu.xib file in the Xcode project. From Interface Builders Library palette, drag a Custom View into the application window. From Interface Builders Inspector's palette, select the Identity tab and set the Class popup to MyView. Choose Save from the File menu to save the changes that you have made. In Xcode, add the following code in the drawRect: method of the MyView class implementation: NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect: [self bounds] xRadius:8.0 yRadius:8.0]; [path setClip]; [[NSColor whiteColor] setFill]; [NSBezierPath fillRect:[self bounds]]; [path setLineWidth:3.0]; [[NSColor grayColor] setStroke]; [path stroke]; Next we need to add the code to handle the rotate gesture. Add the following method to the MyView class implementation: - (void)rotateWithEvent:(NSEvent *)event { CGFloat currentRotation = [self frameCenterRotation]; [self setFrameCenterRotation:(currentRotation + [event rotation])]; } Choose Build and Run from Xcode's toolbar to test the application. How it works... As we did in the previous recipe, we will create a simple rounded rectangle with a three-point stroke to represent our custom view. Our custom view overrides the rotateWithEvent: method from NSResponder to handle the rotation gesture. The rotation property of the NSEvent passed to us in the rotateWithEvent: contains the change in rotation from the last time the rotateWithEvent: method was called. We simply add this value to our view's frameCenterRotation value to get the new rotation. There's more... The value returned from NSEvent's rotation will be negative when the rotation is clockwise and positive when the rotation is counter-clockwise.
Read more
  • 0
  • 0
  • 3316

article-image-how-build-rss-reader-windows-phone-7
Packt
09 Jun 2011
10 min read
Save for later

How to Build a RSS Reader for Windows Phone 7

Packt
09 Jun 2011
10 min read
  Microsoft SharePoint 2010 Enterprise Applications on Windows Phone 7 Create enterprise-ready websites and applications that access Microsoft SharePoint on Windows Phone 7         Read more about this book       (For more resources on Microsoft Sharepoint, see here.) Security in SharePoint 2010 We begin this article with a discussion on security for a very simple reason: security in SharePoint is tricky. In addition to that one very simple reason, authenticating users against SharePoint from within a Windows Phone 7 client application is even trickier. In this article, the example RSS reader that we develop will only use anonymous access to the RSS feeds in SharePoint. Setting up anonymous access is very simple and we'll walk through the steps here. When writing this article, I came across a lot of errors on my testing server, but not my development server. After a couple of days of unsuccessful web searches and reinstalling different components, I discovered the root of my problem was due to the fact that the SharePoint 2010 Prerequisites install a non-final version of ADO. NET Data Services 1.5. Make sure the final version is installed from Microsoft. More information is available at the following URL: http://blogs.msdn.com/b/astoriateam/archive/2010/01/27/data-services-update-for-net-3-5-sp1-available-for-download.aspx There are two places where we need to make changes to our SharePoint site to enable anonymous access: Central Administration Site Permissions Central Administration Classic mode authentication is more or less just classic Windows authentication using NTLM or Kerberos. Although Internet Explorer Mobile in Windows Phone 7 can do the NTLM authentication, as we've been doing up to now to view SharePoint sites in the browser, the version of Silverlight that is included in Windows Phone 7 cannot currently use this authentication mechanism. Carry out the following steps to configure Central Administration for anonymous access: From the Start menu, select All Programs. Find the folder named Microsoft SharePoint 2010 Products in the list of programs and click on it. Click on SharePoint 2010 Central Administration. You need to select the Yes option on the User Account Control dialog that may appear. At this point, the home page for SharePoint 2010 Central Administration should appear as displayed in the following screenshot: (Move the mouse over the image to enlarge.) Next, click on Manage web applications. The page that appears lists out all of the web applications in the SharePoint site. There should be two items listed here, but it is possible there are more. Select the main website by clicking on its name. This main website is usually titled SharePoint – 80. Once selected, the ribbon bar across the top should light up, as all the icons become active. Carry out the following steps to enable anonymous access: Click on the Authentication Providers icon. In the Authentication Providers dialog that appears, select the Default link. The Edit Authentication dialog box will appear. In the third section, down under a heading of Anonymous Access there is a check box listed as Enable anonymous access. Check that box. Scroll all the way to the bottom of the dialog box and select the Save button. SharePoint 2010 will process the request. Then, return to the Authentication Providers dialog box and close it. There is one more section that may need tweaking and if this is a production environment, it should be considered. That section is Anonymous Policy. Click on the icon for it in the ribbon and a dialog box will appear. From here, we can customize the anonymous policy for the site. None – No policy basically leaves the door open for read and write access from anonymous users. This is a good policy to use when anyone who can access the site should also be able to modify the content of the site. This is a good policy for Wiki's. Deny Write – Has no write access allows the anonymous users to read the site, but they cannot write, update, or delete content. This is a good policy to use for sites that we want to specify particular authenticated accounts write access, but allow everyone the ability to read the content. Some Wiki's use this policy and a lot of blogs use this policy. Deny All – Has no access selecting this removes all permissions to the anonymous user. Secure content should always use this policy. Site Permissions Once we have updated the web application to allow anonymous access, we have to give anonymous users access to the site collection. To do this, we close Central Administration and open our SharePoint site. Once on the site, select Site Permissions from the Site Actions menu. This will open the Permissions home page. In the ribbon at the top, there is an icon named Anonymous Access. Click on that button and the Anonymous Access dialog will appear, as shown in the following screenshot: This dialog has three radio buttons to fine tune the access that anonymous users have. The key point to remember here is that although we are really opening up the site for everyone to see, we can break the inherit permissions model on a child page at any time if we need to remove anonymous access. Now that we have opened up our SharePoint site to anonymous users, we can begin to write applications for Windows Phone 7. In a production environment, we may not have the privilege of opening a SharePoint site this wide, but remember that we are only doing it for demonstration purposes here. We have to walk before we can run. Now, let's get started on the RSS reader.   Using WebClient to get data from the web As was stated in the introduction to this article, we are going to build a really simple RSS reader for Windows Phone 7. We are going to keep everything really simple. What that means is that we are going to focus on the pieces of code that actually do something. This is what we are going to do: Create our base project Add a text block to display the WebClient results Create a WebClient Use the WebClient to request the contents of our SharePoint home page Display the raw HTML that is returned in the text block on the page First, a quick word about WebClient. WebClient isn't the most robust method of making requests over a network, but it's really simple and works for simple cases, such as the one we are working with. Creating the base project We can start by creating our base project. This RSS reader will use the Visual Studio Silverlight for Windows Phone Windows Phone Application template. Carry out the following steps to start the project: Open Visual Studio 2010. Select File from the main menu and then select New Project…. In the New Project dialog box that appears, select Silverlight for Windows Phone. Then select Windows Phone Application from the list of templates for Windows Phone. Give the project a name, for example SimpleRSSReader. Give the Solution a name, for example Chapter06. Change the Location as desired and click on the OK button. At this point, Visual Studio will go off and create the solution and project. When it has finished, MainPage.xaml will appear on the screen in split screen mode, as shown in the following screenshot: Displaying WebClient results by adding a text block The first thing we are going to do here is add a text block to the content panel. Add the following code to the Grid that has a name of ContentPanel. <TextBlock x_Name="webClientResults" /> This creates a text block named webClientResults and puts it in ContentPanel. We could spruce this up a bit by providing a font size, or padding, but we are going to keep this really simple and only show the code needed to get things done. Save the progress. Creating a WebClient Open up the code behind by either clicking on it in the top tab bar, double-clicking the file name in Solution Explorer, or press F7 while in the XAML code. In the code behind, create a private member variable, outside the constructor, named client of type WebClient and a private member variable, also outside the constructor, named siteUrl of type string. The siteUrl should have a value that is the URL to your SharePoint home page. private WebClient client = new WebClient();private string siteUrl = "http://ssps2010/"; These are the variables that we'll be using in just a minute. The first is the WebClient that makes the requests on the network. The second is the Url for our SharePoint home page. This is the address that the WebClient will use to request a web page. Requesting the contents of our SharePoint home page Now that we have a WebClient, let us do something with it. Add the following code to the Main Page constructor: client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);client.DownloadStringAsync(new Uri(siteUrl)); The first line adds a new event handler to the DownloadStringCompleted event. This event handler is called client_DownloadStringCompleted and we will write it shortly. The second line is what starts an asynchronous request to our SharePoint home page to get the HTML content. Displaying the raw HTML that is returned Until now, we've created a place in the content panel to display our results. We've created a couple of variables. We've added a new event handler for when the WebClient finishes and we've made the web request for our SharePoint home page. Next, we are going to receive the result from the WebClient. Earlier, when we added a new event handler to the WebClient, we told WebClient that when it finishes downloading the string, it should call our method named client_DownloadStringCompleted. The following is the code for that method: void client_DownloadStringCompleted(object sender,DownloadStringCompletedEventArgs e) { if(e.Error == null) { webClientResults.Text = e.Result; }} First, we check to see if there is an error. To make this as simple as possible, we are not handling the situation where there is an error. We only care if there are no errors. Always check that errors are null. If there is an exception in the WebClient request, the DownloadStringCompletedEventArgs Error property will contain an object of type Exception. These exceptions can range from network connections being down, which is common for cell phones, to invalid URLs. We then take the result of the web request and put it in the text block we created earlier. Save the progress and press F5 to see the application run on the Windows Phone 7 Emulator. In the preceding screenshot, ApplicationTitle and PageTitle have also been updated. Both of these text blocks are found in the XAML in TitlePanel. We have successfully used WebClient to read data from the web and display it on the screen. It is still in a raw format though, and it isn't much of an RSS reader, especially since this page isn't even RSS. We will get there, but first let's find some RSS in SharePoint.  
Read more
  • 0
  • 0
  • 1160
Visually different images

article-image-moodle-20-multimedia-working-2d-and-3d-maps
Packt
08 Jun 2011
12 min read
Save for later

Moodle 2.0 Multimedia: Working with 2D and 3D Maps

Packt
08 Jun 2011
12 min read
  Moodle 2.0 Multimedia Cookbook Add images, videos, music, and much more to make your Moodle course interactive and fun         Read more about this book       (For more resources on Moodle 2.0, see here.) Introduction Whenever you think of a map, you may either think of the traditional planisphere or the terrestrial globe. There are several types of maps apart from those previously mentioned. We can work with maps of the moon, Mars, constellations, and even the universe! Thus, we are not only going to focus on our planet, but we are going to travel even further! The topic of this article is going to deal with Traveling Around the World and Watching the Universe. After reading this article, you can focus on your next holiday! We explain how to work with different types of maps. We are going to be as creative as possible. We should try to work with maps in an unconventional way. That is to say, the idea is to use a map for a Geography class, but we can use maps as a resource for any type of activity. Thus, we can work with the Geography teacher and he/she could work on another geographical feature of the place that we are working with. Therefore, in that way, we are adding more information to the place we are exploring. Maps are very attractive and they may become quite appealing to our students as long as we find a way to develop a rich activity using them. We should encourage the use of maps and the available resources that we have on the Web so that they can insert them in their homework by themselves as well. Thus, we can develop the activities in such a way that we can either provide the map or ask them to design a map. We can also work with maps in the case of Literature. We can ask students to draw a map of a place that has never existed in the real world, though it did in a story. Thus, another bit of homework that could prove helpful would be for students to design and carry out the map of such a place using the tools that we are going to explore in the following recipes. An example of this could be to draw the map of the country Ruritania and locate the cities of Zenda and Strealsau. These places do not exist in the real world, but they exist in the book The Prisoner of Zenda by Anthony Hope. So, many things can be done with maps. Creating maps with sceneries In this activity, we are going to create a map with sceneries. Therefore, we could either browse our files for pictures from our trips or holidays, or we can search for sceneries on the Web. After selecting the pictures, we create a new folder in Windows Explorer, for example C:Images_Traveling. In this folder, we save all the pictures so as to organize our work. We will use the following well-known website: http://earth.google.com/ to design a map using the pictures we have saved in the folder that we have just created. Let's get ready! Getting ready In this activity, we will work with the previously mentioned website. Therefore, we need to open the web browser and enter it. Click on Download Google Earth 6. Read the Google Maps/Earth Terms of Service and if you agree, click on Agree and Download. The icon of Google Earth will appear on your desktop, as shown in the following screenshot: How to do it... We have already carried out the first steps for this activity. Now, we have to design the maps with the pictures that we want to add. There are also some pictures that are available in the maps; you can also work with them, though the aim of this activity is to upload images in the map. Follow these steps in order to create a folder and find images for the activity: Click on the icon on your desktop and open Google Earth. Bring the Earth closer with the icons on the right. Locate a remote city in the southern hemisphere, as shown in the following screenshot: In the Fly to block, write "Mar del Plata", or any other remote city. Then press Enter or click on the magnifying glass next to the block. You will travel virtually to the desired city. Bring the map forward and locate the place where the picture to be uploaded was taken. Click on Add | Photo. Complete the Name block. Click on Browse. Search for the picture that you want to upload and click on it. Complete the other blocks: Description | View | Photo. Click on OK. The picture will appear, as shown in the following screenshot: You can repeat the same process as many times as the number of pictures you want to upload. After uploading all the pictures, click on File | Save | Save Image, as shown in the following screenshot: Complete the File name block and click on Save. How it works... After uploading the desired pictures to the map, we can create an activity. We could start this course with a little social interaction. We ask our students to think about what element they shouldn't forget if they happen to go to this place. They may not know this city, for sure, unless they live nearby. This is the most interesting part of inserting a remote city that they may want to know more about it! Therefore, a Chat is a good idea to have where all the students will be invited in order to discuss the city. We upload the map that we have created with the images to our activity within the Moodle course. Choose the weekly outline section where you want to insert this activity and follow these steps: Click on Add an activity | Chat. Complete the Name of this chat room and Introduction text blocks. Click on the Insert/edit image icon | Find or upload an image | Browse and look for the image that we have just saved. Click on Upload this file. Complete the Image description block and click on Insert. Click on Save and return to course. The activity looks as shown in the following screenshot: Drawing regions within a map In this activity, we are going to use an interactive website in which we choose a map to work with. It is a very simple one, but we could enhance it by adding interesting ingredients to the recipe. We will use a software for drawing a region on the map, and highlight a region for our students to work with. As it was pointed out before, we are not going to focus on geographical features, though you can add this ingredient yourself when designing the activity. Getting ready We open our default web browser and work with the following website: http://www.fusioncharts.com/maps/Default.asp. We click on Map Gallery and choose a map to work with. In this case, we choose a map of the world and highlight five regions, one for each continent. You can modify it and work with different regions within a continent or a country too. How to do it... We look for the desired map. We can find different types of maps to work with. Everything depends on what type of activity we have in mind. In this case, as the topic of this article has to do with traveling, we circle five regions and ask our students to choose where they would like to go. First of all, we have to find the map and save it as an image so that we can draw the regions and upload it to our Moodle course. Therefore, follow these steps: Click on click here | World Map with countries on the aforementioned site. Another pop-up window appears, displaying a map of the world with the countries. There appears a Map Configuration block where you can customize some features, as shown in the next screenshot. Click on Save Map as Image, as shown in the following screenshot: Another pop-up window will appear. Click on Save. Complete the File name block. Click on Save. Click on Open. A pop-up window displaying the map will appear. Click on File | Copy. Paste the map in Paint or Inkscape. Click on Edit | Paste from and browse for the name of the file. Select the file and click on Open. Use the resources available to draw the regions that you want students to work with, as shown in the following screenshot: Click on File | Save as and write a name for the file. Click on Save. How it works... We have already drawn the regions that we want our students to work with. We have chosen one country from every continent; you can choose another or design it in a different way. We can add a writing activity in which students choose where they would like to travel using the previous map. Select the weekly outline section where you want to add the activity and follow these steps: Click on Add an activity | Upload a single file within Assignments. Complete the Assignment name and Description blocks. Click on the Insert/edit image icon | Find or upload an image | Browse. When you find the image that you want to upload, click on Open | Upload this file. Complete the Image description block. Click on Insert. Click on Save and return to course. The activity is ready! When students click on the activity, it looks as shown in the following screenshot: Labeling a map with pins In this recipe, we will learn how to insert a map in our Moodle course labeled with pins, because we pin all the cities that we are going to work with. Therefore, we insert the map as a resource. After that, we design activities for our students to use the interactive map that we have just added. It is another way to use a resource, making our Moodle course more appealing to the eyes of our students. Getting ready We are going to work with Google Earth, as we did in the first recipe, so we have already installed it. We should think of the cities to insert in our course because we need to pin them all! How to do it... Click on the Google Earth icon that you have on your desktop. This is a way to enrich our traveling course by enhancing its appearance. So, these are the steps that you have to follow: Complete the Fly to block with the place that you want to pin. Click on the yellow pin, as shown in the following screenshot: A pop-up window will appear. Complete the Name block by writing the name of the city. Check the Latitude and Longitude, so that you place the pin correctly. You may complete the Description block. You can change the appearance of the pin by clicking on the pin itself. Another pop-up window will appear showing different sorts of icons, as shown in the following screenshot: You can choose the desired icon by clicking on it | OK. The icon that you have selected will appear in the map. Pin as many cities as you are going to work with and repeat steps 1-7. After pinning all the cities, save the file. Click on File | Save | Save Place as. Complete the File name block (remember to save the file in the folder which was created for this course) | Save. You have already saved the pinned map. How it works... We have to insert the map in our Moodle course. In this case, we are going to Add a resource, because we are introducing all the activities that are to come. So, choose the weekly outline section where you want to save the resource. These are the steps that you have to follow: Click on Add a resource | File. Complete the Name and Description blocks. Click on Add | Browse. Click on the file that you are going to upload | Open | Upload this file | Save and return to course. Although we have added a file, students can work with the map interactively! There's more We can embed the map in an HTML block in our Moodle course. Click on the downwards arrow next to Add... in Add a block, as shown in the following screenshot: Choose HTML and a new block will appear in our Moodle course. Embedding a map in an HTML block Open Google Earth and follow these steps in order to embed the map in the block that we have already added: Click on the View in Google Maps icon, as shown in the following screenshot: Another window appears. Click on Link | Customize and preview embedded map, as shown in the following screenshot: Click on Custom and adjust the Width and Height. In the Preview section, click on the minus sign and adjust the map to fit the window. Copy the HTML code to embed in our Moodle course. Go back to the Moodle course and click on the configuration icon to embed the map. Complete the Block title. In the Content block, click on the HTML icon, paste the HTML code which was copied, and click on Update. Click on Save changes. The map will look as shown in the following screenshot:
Read more
  • 0
  • 0
  • 2051

article-image-python-3-designing-tasklist-application
Packt
08 Jun 2011
7 min read
Save for later

Python 3: Designing a Tasklist Application

Packt
08 Jun 2011
7 min read
  Python 3 Web Development Beginner's Guide Use Python to create, theme, and deploy unique web applications         Read more about this book       (For more resources on Python, see here.) Designing a tasklist application   Designing an application should start with a clear idea of what is expected. Not only to determine what is technically required, but almost as important, to define clear boundaries so that we don't lose time on things that are just nice to have. Nice to have features are something to be added if there is time left in the project. Thehighlightedcodesetstherotationofthecircletofalse.Withoutthis,therevolute jointwouldbejustaweld jointintheend. So let's draw up a shortlist of the relevant features of our tasklist application. Some of these may seem obvious, but as we will see, these have a direct impact on some implementation choices that we have to make, such as: The application will be used by multiple users Task lists should be stored indefinitely A task list may contain an unlimited number of tasks but the user interface is designed for optimal performance for up to 25 tasks or so Tasks may be added, deleted, and marked as done Although this list isn't exhaustive, it has some important implications. The fact that the tasklist application will be used by more than one user means that we have to identify and authorize people who want to use it. In other words, we will need some sort of logon screen and a way to check people against some sort of password database. Because we do not want to burden the user with identifying himself/herself each and every time a task list is refreshed or altered, we need some way of implementing the concept of a session. Web applications use the stateless HTTP protocol. This means, from the server's point of view, every request is a single, unrelated event, and no information is retained at the server. This obviously presents us with a problem if we want to perform a set of related actions. The solution is to ask the web browser to send a small piece of information along with every request it makes to the application after the application has identified the user. This might be accomplished in a number of ways. The server may add an extra parameter to all links inside any web page it generates, commonly referred to as a session id, or use the even more general concept of a cookie. Once the server asks the web browser to store a cookie, this cookie is sent with every following request to the same website. The advantage of cookies is that common web application frameworks (like CherryPy) are already equipped to deal with them and implementing sessions with cookies is much simpler than designing the application to alter all hyperlinks it generates to include a proper session ID. The disadvantage might be that people may block their browser from storing cookies because some websites use them to track their clicking behavior. We let the simplicity of implementation prevail and opt for cookies. If users want to block cookies this is not much of a problem as most browsers also have the option to selectively allow cookies from designated websites. The following image illustrates the way CherryPy manages sessions with the help of cookies: It starts when the client (the web browser) sends a request to CherryPy. Upon receiving the request, the first check is to see if the web browser has sent along a cookie with a session ID. If it didn't, a new session idea is generated. Also, if there was a cookie with a session ID, if this ID is no longer valid (because it has expired, for example, or is a remnant from a very old interaction and doesn't exist in the current cache of session IDs) CherryPy also generates a new session ID. At this point, no persistent information is stored if this is a new session, but if it's an existing session there might be persistent data available. If there is, CherryPy creates a Session object and initializes it with the available persistent data. If not, it creates an empty Session object. This object is available as a global variable cherrypy.session. The next step for CherryPy is to pass control to the function that will handle the request. This handler has access to the Session object and may change it, for example, by storing additional information for later reuse. (Note that the Session object acts like a dictionary so you can simply associate values with keys with cherrypy.session['key']=value. The only restriction to the keys and values is that they must be serializable if the persistent storage is on disk). Then before returning the results generated by the handler, CherryPy checks if the Session object has changed. If (and only if) it has, are the contents of the Session object saved to a more permanent storage. Finally, the response is returned accompanied by a cookie with the session ID. Time for action – creating a logon screen Our first task is to create a small application that does little more than present the user with a logon screen. It will be the starting point of our tasklist application and many others as well. The code for this example is available from the Packt website. If you have not downloaded it yet, this might be a good time to do so. Enter the following pieces of code and save it in a file called logonapp.py import cherrypy import logon class Root(object): logon = logon.Logon(path="/logon", authenticated="/", not_authenticated="/goaway") @cherrypy.expose def index(self): username=logon.checkauth('/logon') return ''' <html><body> <p>Hello user <b>%s</b></p> </body></html>'''%username @cherrypy.expose def goaway(self): return ''' <html> <body><h1>Not authenticated, please go away.</h1> </body></html>''' @cherrypy.expose def somepage(self): username=logon.checkauth('/logon',returntopage=True) return '''<html> <body><h1>This is some page.</h1> </body> </html>''' if __name__ == "__main__": import os.path current_dir = os.path.dirname(os.path.abspath(__file__)) cherrypy.quickstart(Root(),config={ '/': {'tools.sessions.on': True } } ) If you now run logonapp.py, a very simple application is available on port 8080. It presents the user with a logon screen when the top level page http://localhost:8080/ is accessed. An example is shown in the following illustration: If a correct username/password combination is entered, a welcome message is shown. If an unknown username or wrong password is entered, the user is redirected to http://localhost:8080/goaway. The somepage() method (highlighted) returns a page with (presumably) some useful content. If the user is not yet authenticated, the logon screen is shown and upon entering the correct credentials, the user is directed back to http://localhost:8080/somepage. The complete tree of web pages within the logon sample application and the possible paths the user may pick through is shown next: Logon + session ID vs. HTTP basic authentication You may wonder why we choose not to reuse CherryPy's bundled auth_basic tool that offers basic authentication (for more information on this tool, see http://www.cherrypy.org/wiki/BuiltinTools#tools.auth_ basic). If all we wanted was to check whether a user is allowed access to a single page, this would be a good choice. The basic authentication is sufficient to authenticate a user, but has no concept of a session. This means we lack a way to store data that needs to be accessible when we process subsequent requests by the same user. The sessions tool we use here does provide this additional functionality.
Read more
  • 0
  • 0
  • 2664

article-image-25-useful-extensions-drupal-7-themers
Packt
07 Jun 2011
5 min read
Save for later

25 Useful Extensions for Drupal 7 Themers

Packt
07 Jun 2011
5 min read
Drupal 7 Themes Create new themes for your Drupal 7 site with a clean layout and powerful CSS styling Drupal modules There exist within the Drupal.org site a number of modules that are relevant to your work of theming a site. Some are straightforward tools that make your standard theming tasks easier, others are extensions to Drupal functionality that enable to you do new things, or to do things from the admin interface that normally would require working with the code. The list here is not meant to be comprehensive, but it does list all the key modules that are either presently available for Drupal 7 or at least in development. There are additional relevant modules that are not listed here, as at the time this was written, they showed no signs of providing a Drupal 7 version. Caution One thing to keep in mind here—some of these modules attempt to reduce complex tasks to simple GUI-based admin interfaces. While that is a wonderful and worthy effort, you should be conscious of the fact that sometimes tools of this nature can raise performance and security issues and due to their complexity, sometimes cause conflicts with other modules that also are designed to perform at least part of the functions being fulfilled by the more complex module. As with any new module, test it out locally first and make sure it not only does what you want, but also does not provide any unpleasant surprises. The modules covered in this article include: Administration Menu Chaos Tool Suit Colorbox Conditional Stylesheets Devel @font-your-face Frontpage HTML5 Tools .mobi loader Mobile Theme Nice Menus Noggin Organic Groups Panels Semantic Views Skinr Style Guide Sweaver Taxonomy Theme Theme Developer ThemeKey Views Webform Administration Menu The Administration Menu was a mainstay of many Drupal sites built during the lifespan of Drupal 6.x. With the arrival of Drupal 7, we thought it unlikely we would need the module, as the new toolbar functionality in the core accomplished a lot of the same thing. In the course of writing this, however, we installed Administration Menu and were pleasantly surprised to find that not only can you run the old-style Administration Menu, but they have also now included the option to run a Toolbar-style Administration Menu, as shown in the following screenshot: The Administration Menu Toolbar offers all the options of the default Toolbar plus the added advantage of exposing all the menu options without having to navigate through sub-menus on the overlay. Additionally, you have fast access to clearing the caching, running cron, and disabling the Devel module (assuming you have it installed). A great little tweak to the new Drupal 7 administration interface. View the project at: http://drupal.org/project/admin_menu. Chaos Tool Suite This module provides a collection of APIs and tools to assist developers. Though the module is required by both the Views and Panels modules, discussed elsewhere in this article, it provides other features that also make it attractive. Among the tools to help themers are the Form Wizard, which simplifies the creation of complex forms, and the Dependent widget that allows you to set conditional field visibility on forms. The suite also includes CSS Tools to help cache and sanitize your CSS. Learn more at http://drupal.org/project/ctools. Colorbox The Colorbox module for Drupal provides a jQuery-based lightbox plugin. It integrates the third-party plugin of the same name (http://colorpowered.com/colorbox/). The module allows you to easily create lightboxes for images, forms, and content. The module supports the most commonly requested features, including slideshows, captions, and the preloading of images. Colorbox comes with a selection of styles or you can create your own with CSS. To run this module, you must first download and install the Colorbox plugin from the aforementioned URL. Visit the Colorbox Drupal module project page at: http://drupal.org/project/colorbox. Conditional Stylesheets The module allows themers to easily address cross-browser compatibility issues with Internet Explorer. With this module installed, you can add stylesheets targeting the browser via the theme's .info file, rather than having to modify the template.php file. The module relies on the conditional comments syntax originated by Microsoft. To learn more, visit the project site at http://drupal.org/project/conditional_styles. Devel The Devel module is a suite of tools that are useful to both module and theme developers. The module provides a suite of useful tools and utilities. Among the options it provides: Auto-generate content, menus, taxonomies, and users Print summaries of DB queries Print arrays Log performance Summaries of node access The module is also a prerequisite to the Theme Developer module, discussed later in this article. Learn more: http://drupal.org/project/devel. @font-your-face @font-your-face provides an admin interface for browsing and applying web fonts to your Drupal themes. The module employs the CSS @font-face syntax and draws upon a variety of online font resources, including Google Fonts, Typekit. com, KERNEST, and others. The system automatically loads fonts from the selected sources and you can apply them to the styles you designate—without having to manually edit the stylesheets. It's easy-to-use and has the potential to change the way you select and use fonts on your websites. @font-your-face requires the Views module to function. Learn more at the project site: http://drupal.org/project/fontyourface. Frontpage This module serves a very specific purpose—it allows you to designate, from the admin interface, different front pages for anonymous and authenticated users. Though you can accomplish the same thing through use of $classes and a bit of work, the module makes it possible for anyone to set this up without having to resort to coding. Visit the project site at http://drupal.org/project/frontpage.
Read more
  • 0
  • 0
  • 2851
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-customizing-sharepoint-communities-windows-phone-7
Packt
03 Jun 2011
9 min read
Save for later

Customizing SharePoint Communities for Windows Phone 7

Packt
03 Jun 2011
9 min read
  Microsoft SharePoint 2010 Enterprise Applications on Windows Phone 7 Create enterprise-ready websites and applications that access Microsoft SharePoint on Windows Phone 7         Read more about this book       (For more resources on Microsoft Sharepoint, see here.) Let's get started with the discussion of SharePoint communities by taking a look at blogs.   Blogs At this point in the 21st century, everyone is familiar with what a blog is. In SharePoint, a blog is a site that is characterized by entries of content being listed from newest at the top of the page to oldest at the bottom. Content is determined by the author and can contain metadata such as the author, date, and keywords or tags to designate the categories in which the content belongs. Creating a blog site in SharePoint A blog site can either be the root site or a site contained within another site. This is consistent with all site types in SharePoint. The reason this is pointed out though, is that when creating a new SharePoint engagement, it is important to truly think of the overall goal of the website as a whole. If the website will essentially be a blog with other content thrown in from time to time, then it makes sense for the root site to be of the type blog. Otherwise, it makes sense to make the root site something else like the team site or a blank site and then add a blog site within that root site. This is important to think about because to add a blog to an existing site is fairly straightforward. Simply, carry out the following steps: From the root site, click on the Site Actions menu. On the Site Actions menu, select the New Site option. From the Installed Items list, select Blog. Give the new blog site a Title and a URL name. Finally, click on the Create button. At this point, SharePoint will create a new blog site. The new blog will contain some seed data to get the blog going. There are three categories named appropriately: Category 1 Category 2 Category 3 The new blog site will also have a location for archives containing the one entry that was seeded in the site titled Welcome to your Blog! This can all be seen in the following screenshot: Customizing a SharePoint blog site Although this blog site is ready to go right now, we will probably want to customize it for our usage scenario. There are several places to customize it, which are as follows: About this blog Categories Blog Tools Links About this blog When new readers reach a blog they look for information about the blog so they can get a high level overview of what to expect from the content of the site. This is usually found in the "about this blog" section of the site. In the SharePoint blog site, the About this blog section is a Wiki Web Part found in the right column. Although we will learn more about Wikis in the next section, for now just know that this web part allows us a what-you-see-is-what-you-get (WYSIWYG) editing surface to enter any content we want. To get into this editing mode, carry out the following steps: From the Site Actions menu, select Edit Page. When the page changes to edit mode, click on the text inside the About this blog section. At this point, the ribbon at the top will have the following four main sections: Editing Tools: This has the basic text editing tools that are familiar to anyone who has used Word. Table Tools: The about section is actually a table with two rows and one column. The top cell has the image, and the bottom has the text. The Table Tools section of the ribbon allows us to manage this table. Page Tools: These are the basic tools that are global to the page and not specific to this section. Web Part Tools:This part of the ribbon contains tools that allow us to minimize, restore, or delete the web part. It also allows us to edit the Web Part Properties. These properties include the title, as well as other appearance features such as height and width. It also includes layout information and some advanced features. Categories The next section to customize on this blog site is the list of categories. When creating a blog entry, we can categorize the contents with a tag. The default categories for a new blog are as follows: Category 1 Category 2 Category 3 The following steps show how to customize these categories: Click on the title Categories in the left column. This will open the list page for the categories. The categories list will display the three default categories. For each category, click on the Edit icon, as shown in the following screenshot: (Move the mouse over the image to enlarge.) Change the Title to something that makes sense for the blog which we are creating. Click on the Save button. Repeat these steps for all three of the default categories. To add more categories, click on the Add new item link below the list of categories. To delete a category, carry out the following steps: Move the pointer over the title of the category. This will trigger an arrow to appear to the right of the title next to the edit icon. Click on this down arrow. In the context menu that appears, select the Delete Item option. A confirmation message will appear asking if we are sure we want to send it to the recycle bin. Click on OK and the category will be deleted. Blog Tools Now that we have a blog, how do we manage the content? This is where the Blog Tools section comes into use. There are 4 links to help us manage the blog, which are as follows: Create a post Manage posts Manage comments Launch blog program to post Create a post Clicking on the Create a post link will open a modal dialog with a form to fill out to create a new blog entry. The fields include the following: Title: This is a plain text field used for the title of the entry. Body: This is a rich text field that utilizes the edit ribbon. Category: Here we can select the categories that the entry is a part of. Published: Here we can set a date for our entry to be published. Publishing an entry in the future is helpful when we have information that isn't supposed to be public knowledge until a specifi c time and date, or when information needs to be published at a specifi c time and date. The preceding fields are shown in the following screenshot: Manage posts Blog entries, like most things in SharePoint, are items in a list. Clicking on the Manage posts link will display all the blog entries. From this list, we can perform many management functions such as the following: Manage approval status Edit entries View entries Manage permissions Delete entries Manage comments All of the comments are managed in a separate list from the blog entries. Clicking on the Manage comments link will display all of the comments for all of the blog entries in this site. From here we can view, edit, or delete the comments, as well as manage permissions. Managing permissions on comments and posts is a lot like managing permissions elsewhere in SharePoint. By default, the list items inherit the parent permissions, but occasionally we will want to have specific permissions for special cases. We could have a blog entry that we only want a small group of people to see, or maybe we want to save a comment, so that only we can see it. The manage permissions section is how we can deal with these cases. More information on managing permissions can be found in the online help or on TechNet at the following URL: http://technet.microsoft.com/en-us/library/cc721640.aspx Launch blog program to post Although creating a blog entry in the web browser works well, sometimes we may want to use a more powerful tool to create entries. The Launch blog program to post link will open Microsoft Word 2007, or a newer version, to edit a new blog entry. Configuring Windows Live Writer There is a link in Blog Tools to launch Microsoft Word 2007 or newer, to create a new blog entry. Although Word does a pretty good job of creating new blog entries, there is a free tool from Microsoft, named Windows Live Writer (http://explore.live.com/windows-live-writer) which is true genius when it comes to editing blog entries. Using this tool can make most, if not all, blog posting tasks much easier within SharePoint. Configuring Windows Live Writer for a SharePoint is simple: When setting up Windows Live Writer, select SharePoint from the What blog service do you use? Click on Next and enter the URL of the SharePoint blog. Click on Next and provide the SharePoint authentication information. That's all there is to it. The Windows Live Writer interface also displays a preview of what the blog entry will look like in the site by clicking on the Preview tab at the bottom, as shown in the following screenshot: Links Finally, the links section allows us to add hyperlinks to the page for easy access to anything. The default entry is to a photo library named Photos. Adding a new link is as simple as the following steps: Click on the Add new link hyperlink. Enter the URL for the link. Optionally, enter a description that will be used in place of the raw URL for display. Optionally, add any notes. Notes show up when viewing the full list of links. The full list of links can be viewed by clicking on the title Links from the home page. Click on Save, as shown in the following screenshot:  
Read more
  • 0
  • 0
  • 1073

article-image-html5-generic-containers
Packt
01 Jun 2011
15 min read
Save for later

HTML5: Generic Containers

Packt
01 Jun 2011
15 min read
  HTML5 Multimedia Development Cookbook Recipes for practical, real-world HTML5 multimedia driven development.         Read more about this book       (For more resources on Multimedia development, see here.) Introduction "On the web, a man should not be judged by the color of his skin but by the content of his content." - Internet meme To be correct according to the specification semantically, we need to know what the content is so we can wrap it with the most appropriate new element tag. While this may mean we developers have to think differently, a new challenge is exactly why we're here. In this article we'll look at some examples of how to do just that using several of HTML5's new elements. "In case of conflict, consider users over authors over implementers over specifiers over theoretical purity." - Priority of Constituencies Throughout this article, we'll show you how to use the new <article> element to mark up both blog posts and comments, add a meaningful publication date to an <article>, use the new <mark> element to highlight text, and how to note visual elements using the new <figure> element. We'll then turn our attention to some new methods of styling text with font replacement techniques, as well as adding drop shadows and gradients to our text.   Structuring a blog article "The <article> element represents a self-contained composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content." - WHATWG's HTML5 Draft Standard - http://whatwg.org/html5 Getting ready Blog entries are perfect candidates for the new <article> element, which is designed for syndicated content. For this recipe, let's start by identifying the major elements of a blog <article>: There's usually a headline in the form of a heading tag, the blog entry itself consisting of several paragraphs and perhaps one or more images, and some information that usually includes the author's name and other related metadata. Notice this is all self-contained related content. How to do it... We're going to continue using the new HTML5 <header> and <footer> elements. The headline, entry and meta-information should be wrapped in their own unique tags, like <h2>, multiple <p>s and the new &ltfooter>. Let's start with a foundation and add our new <article> element twice: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Blog Title</title> <!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"> </script>[endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body><article> <header> <h2>Headline</h2> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer></article><article> <header> <h2>Headline</h2> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer></article></body></html> Put your code on a diet? Ready for a shocker? Want to have your mind blown? The <html> and <head> and <body> tags (as well as their closing tags) are now optional in the HTML5 specification. Sure, you could leave them in there, and your pages will validate just fine, but why should we? If remove them from the previous code, we are left with the spartan: <!DOCTYPE html><meta charset="UTF-8"><title>Blog Title</title><!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"> </script>[endif]--><meta name="viewport" content="width=device-width, initial-scale=1.0"><article> <header> <h2>Headline</h2> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer></article><article> <header> <h2>Headline</h2> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer></article> Don't believe me? Run that code through the World Wide Web Consortium's validator at: http://validator.w3.org, and you'll see it displays correctly in the browser. Well, not so fast buster. The problem is that removing those elements breaks our code for screen readers. Uh oh. Strike one. Also, removing the <body> tag breaks our new HTML5-enabling JavaScript for Internet Explorer. Strike two. And guess what? You can see it coming, can't you? Yes, removing the <html> tag removes the language of the page. There it is: Strike three. So let's add those elements back in, shall we? <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Blog Title</title> <!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"> </script>[endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body> <article> <header> <h2>Headline</h2> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer> </article> <article> <header> <h2>Headline</h2> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer> </article></body></html> There, that's better. How it works... Remember, the new <article> element is a collection of related information intended for syndication via RSS or another means. There's more... Richer, more meaningful semantics is perhaps the most significant goal for HTML5. It's better for machines, better for authors, and most importantly, better for our audiences. Validation as an aid, not a crutch As we saw previously, removing the &lthtml> and <head> and <body> tags render a still valid page. So that begs the question of how valid validators are. Unlike the XML world, HTML5 can use incorrect syntax and still render just fine. The author makes every effort to validate his code whenever possible. It's not necessary to be slavish to the validator, but it's always a good quality control check. And the closer you get to valid code, the better chance browsers will display your work in as consistent a manner as possible. Eric Meyer's funny The author loves how CSS guru Eric Meyer thinks about validators: Where to find validators You can make good use of code validators at: http://validator.nu http://validator.w3.org   Highlighting text using the mark element "The &ltmark> element represents a run of text in one document marked or highlighted for reference purposes, due to its relevance in another context. When used in a quotation or other block of text referred to from the prose, it indicates a highlight that was not originally present but which has been added to bring the reader's attention to a part of the text that might not have been considered important by the original author when the block was originally written, but which is now under previously unexpected scrutiny. When used in the main prose of a document, it indicates a part of the document that has been highlighted due to its likely relevance to the user's current activity." - WHATWG's HTML5 Draft Standard - http://whatwg.org/html5 Getting ready When viewing search results, you'll often find the term for which you searched highlighted. Instead of relying on a semantically meaningless tag, we can now use the more meaningful <mark> element. How to do it... In this recipe, you'll see HTML5doctor.com has an excellent example of how to use the new <mark> element to highlight a search results term. This gives a useful semantic hook not only for styling but also for the machine tracking the results. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title> <!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"> </script>[endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body> <h1>716,000,000 search results for the query "<mark>HTML 5</mark>"</h1> <section id="search-results"> <article> <h2><a href="http://en.wikipedia.org/wiki/HTML_5"> <mark>HTML 5</mark> - Wikipedia, the free encyclopedia</a></h2> <p><mark>HTML 5</mark> is the next major revision of <mark>HTML</mark> ("hypertext markup language"), the core markup language of the World Wide Web. The WHATWG started work on the ... <a href="http://en.wikipedia.org/wiki/HTML_5"> Read more</a></p> </article> <article> <h2><a href="http://dev.w3.org/html5/spec/Overview.html"> <mark>HTML 5</mark></a></h2> <p>A vocabulary and associated APIs for <mark>HTML</mark> and XHTML. Editor's Draft 16 August 2009. Latest Published Version: http://w3.org/TR/<mark>html5</mark>/; Latest Editor's ... <a href="http://dev.w3.org/html5/spec/Overview.html"> Read more</a></p> </article> </section></body></html> Adding a simple style declaration like: <style type="text/css"> mark {background-color: yellow; font-weight: bold;}</style> in the <head> section helps us render this highlighted text: How it works... The new <mark> element simply highlights a word or phrase to draw the reader's attention. To do this, simply specify the <mark> to be bold or italicized or highlighted in some way in your corresponding Cascading Style Sheet. There's more... Sure, you could mark up and style a search-results page to use the <b> or <i> or even <span> tags to indicate for which term the search took place, but each of those tags only affects the presentation layer. They lack meaning. The new &ltmark> element can accomplish the same visual effect, while also adding that extra meaning to your markup. In fact, the new &ltmark> element is full of win. <Mark> long and prosper Another great use of the new <mark> element is highlighting a date in a calendar picker, as we often see on any date-based reservation system website like Priceline.com. Priceline.com highlights the current date by default when booking your itinerary. Instead of using a semantically meaningless tag to achieve this, the new <mark> element could be a perfect candidate to use. Waiting for browsers The new <mark> element isn't fully supported by any web browser at the time of this writing. Though the extra semantic meaning may not be apparent to machine readers, we can still use the new <mark> element as a stylistic "hook" until the day its meaning is fully supported by a variety of browsers. Is "future proof" a word? Remember that HTML5's new elements attempt to add extra meaning to our markup. The goal is never to take away meaning or break pages. With this in mind, it becomes much more palatable to layer on new elements like the <mark> element that's not fully implemented by browsers yet. Even if its meaning is not fully understood by machines yet, it certainly does not hurt to add it and make our pages as "future proof" as we possibly can. See also In 2001, Carrie Bickner prepared the "New York Public Library Online Style Guide" (http://legacy.www.nypl.org/styleguide) for branches of the NYPL to use when updating their websites. In this seminal publication, Bickner made the case for web standards by separating content (markup) from presentation (Cascading Style Sheets) from behavior (JavaScript). The publication was extremely forward-thinking for the time and was in use for many years.   Using the time element "The &lttime> element represents either a time on a 24-hour clock, or a precise date in the proleptic Gregorian calendar, optionally with a time and a time-zone offset." - WHATWG's HTML5 Draft Standard - http://whatwg.org/html5 Getting ready The new <time> element is a powerful way to display time or a specific date. How to do it... In this recipe we'll display dates and times that will be readable for both humans and machines. Let's look at four examples. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title> <!--[if lt IE 9]><script src=http://html5shiv.googlecode.com/svn/trunk/html5.js> </script>[endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body> <article> <header> <h2>Headline</h2> <time datetime="2010-11-29">November 29, 2010</time> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer> </article> <article> <header> <h2>Headline</h2> <time datetime="2010-11-29">Nov. 29</time> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer> </article> <article> <header> <h2>Headline</h2> <time datetime="2010-11-29">the date this was written</time> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer> </article> <article> <header> <h2>Headline</h2> <time datetime="2010-11-29T11:34">the date and time this was written</time> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer> </article></body></html> How it works... We can use the new <time> element to indicate specific dates, times, or both. There's more... The new &lttime> element specifies an exact moment in time—not a time period. Odd rules One interesting aspect of the new <time> element is that you can't use a date before the Christian Era. You also can't use a date like "November 2010." Whatever date we specify must be a positive, specific date—not a relative one. The HTML5 Working Group continues to address this seemingly arbitrary restriction. <time>'s Time will come Browsers display the new <time> element but don't do anything special with it—yet. Always remember SEO Time. Why are we so obsessed with it? One very valid reason to focus on time and dates on the web is Search Engine Optimization. SEO, once seen as some sort of mysterious voodoo only black hatted wizards understood, is now everyone's responsibility online. You spend time creating good code and expect a writer to create content worth reading. Now go one step further and ensure that your intended audience can actually find the content you have taken the time to create. And the new <time> element is just one of the ways search engines draw attention to the most recent content. See also The new HTML5 <time> element is a possible addition to the Microformats movement. Microformats promise to add additional semantic meaning to our markup. Though not officially a standard, Microformats are slowly gaining acceptance in the web development community. Learn more at Microformats.org.  
Read more
  • 0
  • 0
  • 2964

article-image-cocoa-and-objective-c-animating-calayers
Packt
27 May 2011
6 min read
Save for later

Cocoa and Objective-C: Animating CALayers

Packt
27 May 2011
6 min read
Cocoa and Objective-C Cookbook Understanding the CALayer class In this recipe, we will use multiple layers to draw our custom view. Using a delegate method, we will draw the background of our view. A second layer will be used to include an image centered in the view. When complete, the sample application will resemble the following screenshot: Getting ready In Xcode, create a new Cocoa Application and name it CALayer. How to do it... In the Xcode project, right-click on the Classes folder and choose Add…, then choose New File… Under the MacOS X section, select Cocoa Class, then select Objective-C class. Finally, choose NSView in the Subclass of popup. Name the new file MyView.m. In the Xcode project, expand the Frameworks group and then expand Other Frameworks. Right-click on Other Frameworks and choose Add…, then choose Existing Frameworks… Find QuartzCore.framework in the list of frameworks and choose Add. Click on MyView.m to open it and add the following import: #import <QuartzCore/QuartzCore.h> Remove the initWithFrame: and drawRect: methods. Add the following awakeFromNib method: - (void) awakeFromNib { CALayer *largeLayer = [CALayer layer]; [largeLayer setName:@"large"]; [largeLayer setDelegate:self]; [largeLayer setBounds:[self bounds]]; [largeLayer setBorderWidth:4.0]; [largeLayer setLayoutManager:[CAConstraintLayoutManager layoutManager]]; CALayer *smallLayer = [CALayer layer]; [smallLayer setName:@"small"]; CGImageRef image = [self convertImage:[NSImage imageNamed:@"LearningJQuery"]]; [smallLayer setBounds:CGRectMake(0, 0, CGImageGetWidth(image), CGImageGetHeight(image))]; [smallLayer setContents:(id)image]; [smallLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMidY relativeTo:@"superlayer" attribute:kCAConstraintMidY]]; [smallLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMidX relativeTo:@"superlayer" attribute:kCAConstraintMidX]]; CFRelease(image); [largeLayer addSublayer:smallLayer]; [largeLayer setNeedsDisplay]; [self setLayer:largeLayer]; [self setWantsLayer:YES]; } Add the following two methods to the MyView class as well: - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context { CGContextSetRGBFillColor(context, .5, .5, .5, 1); CGContextFillRect(context, [layer bounds]); } - (CGImageRef) convertImage:(NSImage *)image { CGImageSourceRef source = CGImageSourceCreateWithData((CFDataRef )[image TIFFRepresentation], NULL); CGImageRef imageRef = CGImageSourceCreateImageAtIndex(source, 0, NULL); CFRelease(source); return imageRef; } Open the MyView.h file and add the following method declaration: - (CGImageRef) convertImage:(NSImage *)image; Right-click on the CALayer project in Xcode's project view and choose Add…, then choose Existing Files…. Choose the LearningJQuery.jpg image and click on Add. Double-click on the MainMenu.xib file in the Xcode project. From Interface Builder's Library palette, drag a Custom View into the application window. From Interface Builder's Inspectors palette, select the Identity tab and set the Class popup to MyView. Back in Xcode, choose Build and Run from the toolbar to run the application. How it works... We are creating two layers for our view. The first layer is a large layer, which will be the same size as our MyView view. We set the large layers delegate to self so that we can draw the layer in the drawLayer: delegate method. The drawLayer: delegate method simply fills the layer with a mid-gray color. Next, we set the bounds property and a border width property on the larger layer. Next, we create a smaller layer whose contents will be the image that we included in the project. We also add a layout manager to this layer and configure the constraints of the layout manager to keep the smaller layer centered both horizontally and vertically relative to the larger view using the superlayer keyword. Lastly, we set the small layer as a sub-layer of the large layer and force a redraw of the large layer by calling setNeedsDisplay. Next, we set the large layer as the MyView's layer. We also need to call the setWantsLayer:YES on the MyView to enable the use of layers in our view. There's more... Since we used a layout manager to center the image in the view, the layout manager will also handle the centering of the image when the user resizes the view or window. To see this in action, modify the Size properties in Interface Builder for the custom view as shown in the screenshot below: Animation by changing properties Cocoa provides a way to animate views by changing properties using implied animations. In this recipe, we will resize our custom view when the resize button is clicked, by changing the views frame size. Getting ready In Xcode, create a new Cocoa Application and name it ChangingProperties. How to do it... In the Xcode project, right-click on the Classes folder and choose Add…, then choose New File… Under the MacOS X section, select Cocoa Class, then select Objective-C class. Finally, choose NSView from the Subclass of popup. Name the new file MyView.m. Click on the MyView.m file to open it and add the following in the drawRect: method: NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:[ self bounds] xRadius:8.0 yRadius:8.0]; [path setClip]; [[NSColor whiteColor] setFill]; [NSBezierPath fillRect:[self bounds]]; [path setLineWidth:3.0]; [[NSColor grayColor] setStroke]; [path stroke]; Click on the ChangingPropertiesAppDelegate.h to open it. Next, insert an import for the MyView.h header file: #import "MyView.h" Add the following variables to the class interface: NSButton *button; MyView *myView; Add the following properties to the class interface: @property (assign) IBOutlet NSButton *button; @property (assign) IBOutlet MyView *myView; Add the method declaration for when the Resize button is clicked: - (IBAction) resizeButtonHit:(id)sender; Click on the ChangingPropertiesAppDelegate.m file to open it. Add our synthesized variables below the synthesized window variable: @synthesize button; @synthesize myView; Create a global static boolean for tracking the size of the view: static BOOL isSmall = YES; Add the resizeButtonHit: method to the class implementation: - (IBAction) resizeButtonHit:(id)sender { NSRect small = NSMakeRect(20, 250, 150, 90); NSRect large = NSMakeRect(20, 100, 440, 240); if (isSmall == YES) { [[myView animator] setFrame:large]; isSmall = NO; } else { [[myView animator] setFrame:small]; isSmall = YES; } } Double-click on the MainMenu.xib file in the Xcode project. From Interface Builders Library palette, drag a Custom View into the application window. From Interface Builder's Inspector's palette, select the Identity tab and set the Class popup to MyView. From the Library palette, drag a Push Button into the application window. Adjust the layout of the Custom View and button so that it resembles the screenshot below: From Interface Builder's Inspector's palette, select the Identity tab and set the Class popup to MyView. Right-click on the Changing Properties App Delegate so that you can connect the outlets to the MyView Custom View, the Resize Push Button, and the resizeButtonHit action: Back in Xcode, choose Build and Run from the toolbar to run the application. How it works... We define two sizes for our view, one small size that is the same as the initial size of the view, and one large size. Depending on the state of the isSmall global variable, we set the view's frame size to one of our predefined sizes. Note that we set the view's frame via the views animator property. By using this property, we make use of the implicit animations available in the view. There's more... Using the same technique, we can animate several other properties of the view such as its position or opacity. For more information on which properties can be implicitly animated, see Apple's Core Animation Programming Guide.
Read more
  • 0
  • 0
  • 3190

article-image-joomla-virtuemart-product-list-templates
Packt
26 May 2011
23 min read
Save for later

Joomla! VirtueMart: Product List Templates

Packt
26 May 2011
23 min read
Joomla! VirtueMart 1.1 Theme and Template Design Give a unique look and feel to your VirtueMart e-Commerce store         Read more about this book       (For more resources on Joomla!, see here.) The product list page Product list page is the most important starting page for the shopping life cycle. While the landing page will give some general information regarding the shop, the list of items for sale in the shop is the major job of the product list page. Some shop owners even prefer to use product list page as their home page. Product list page is in singular, but actually the product list page is a series of pages. The total number of pages in the series varies from store-to-store and typically depends on the number of categories you have in the site. Each category will have its own page or even pages, if the category contains many products. Furthermore, the product list page is also used to list the products that relate to a particular manufacturer. It is also used for the keyword search and advanced search, if you enable the product search and advanced search Joomla! modules or the product search Joomla! plugin. To simplify our discussion, we will first restrict ourselves to the study of category listing. The manufacturer listing and search listing are very similar. Let's take a look at a typical category listing. From the preceding screenshot, we can identify a number of important elements on a product list page: Page header: This includes the category name, category description, the PDF, and print icons. The layout of the page header will depend on the page header templates. Navigation: This includes the order by form, the order by direction button (toggle between ascending and descending), number per page drop-down box, and the page navigation links. Note that the page navigation links can appear both at the top and the bottom. The navigation layout is controlled by the navigation templates. Product listing: This is the major item of the page, where the products are listed in a way defined by the product listing style and the number of products per row settings. Each of the products displayed within the listing is controlled by the core browse template (the core browse template is explained in the section Core browse templates). Addendum elements: This includes the recent products, latest products, featured products, and so on. Each of the addenda may have its own template. Page footer: This is the element placed at the end of the listing. Right now, there is only one element within the page footer, the page navigation. As we shall see, the layout of each of these elements is controlled by one or more templates. By customizing any one of these templates, we may be able to change the look of the page completely. We need to distinguish the usage between the terms browse templates and core browse templates. For the purpose of making things clear, we retain the term "browse templates" to refer to all templates within the browse template group. Within this broad template group, there are two subgroups: those which control the layout detail of each individual product (each product in the product listing section) and those which control all the other elements. We refer to them as core and non-core templates, respectively. The core browse templates reside directly under the templates/browse subdirectory. All the non-core templates reside under the subdirectory templates/browse/includes. The difference between the core and non-core templates will become clear in the following explanation.   Looking at our first template While VirtueMart templates are different from each other, they actually follow a definite pattern. To understand how the template is structured, probably the best way is to look at a sample. Let's take a look at the file browse_1.tpl.php as an example. This is one of the core browse templates. The full text of this file is as follows (with line numbers added): 1. <?php if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) )die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );2. mm_showMyFileName(__FILE__);3. ?>4. <div class="browseProductContainer">5. <h3 class="browseProductTitle"><a title="<?php echo$product_name ?>" href="<?php echo $product_flypage ?>">6. <?php echo $product_name ?></a>7. </h3>8.9. <div class="browsePriceContainer">10. <?php echo $product_price ?>11. </div>12.13. <div class="browseProductImageContainer">14. <script type="text/javascript">//<![CDATA[15. document.write('<a href="javascript:void window.open('<?php echo $product_full_image ?>', 'win2', 'status=no,toolbar=no,scrollbars=yes,titlebar=no,menubar=no,resizable=yes,width=<?php echo $full_image_width ?>,height=<?php echo $full_image_height ?>,directories=no,location=no');">');16. document.write( '<?php echo ps_product::image_tag( $product_thumb_image, 'class="browseProductImage" border="0"title="'.$product_name.'" alt="'.$product_name .'"' ) ?></a>' );17. //]]>18. </script>19. <noscript>20. <a href="<?php echo $product_full_image ?>"target="_blank" title="<?php echo $product_name ?>">21. <?php echo ps_product::image_tag($product_thumb_image, 'class="browseProductImage" border="0"title="'.$product_name.'" alt="'.$product_name .'"' ) ?>22. </a>23. </noscript>24. </div>25.26. <div class="browseRatingContainer">27. <?php echo $product_rating ?>28. </div>29. <div class="browseProductDescription">30. <?php echo $product_s_desc ?>&nbsp;31. <a href="<?php echo $product_flypage ?>"title="<?php echo $product_details ?>"><br />32. <?php echo $product_details ?>...</a>33. </div>34. <br />35. <span class="browseAddToCartContainer">36. <?php echo $form_addtocart ?>37. </span>38.39. </div> Downloading the example code You can download the example code files here HTML fragments The coding is pretty typical of a VirtueMart template file. You can see that the template is basically an HTML fragment embedded with PHP coding. All PHP code is enclosed within the tag <?php … ?>. In most cases, the PHP code uses the statement echo $field_name to add the field value to the HTML code. We will be looking at those PHP constructs in the next subsection. After parsing the template, the output should be a well-formed HTML code. You should note that the template is just an HTML fragment, meaning no <html>, <head>, and <body> tags are needed. As you can recall, VirtueMart is just a Joomla! component that will handle the main content. So the HTML fragment produced by the template (together with other code, if any, built up by the page file) will be returned to the Joomla! engine for further processing. Typically, the Joomla! engine will pass this HTML fragment into the Joomla! template which, in turn, will insert the HTML into a location designated by the template. The final output of the Joomla! template will then be a valid HTML document. The <html>, <head>, and <body> tags will therefore be the responsibility of the Joomla! template. Let's look at the code to see how these 39 lines of code work. Remarks will only be needed for lines with the PHP tag. All the rest are HTML code that you should be familiar with. Lines 1 to 3 are actually some housekeeping code following the Joomla!/VirtueMart pattern. They will restrict direct access to the code and print out the template filename when debugging. Line 5 will output the product title with the product name embedded inside a hot link pointing to the product detail page. Line 10 will output the product price. Lines 14 to 23 contain a lengthy JavaScript code. The purpose is to output the image thumbnail embedded inside a hot link to open the full image. We need JavaScript here because we want to ensure the pop-up window size fits the full image size. (Otherwise, the pop-up window size will depend on the default size of the browser.) The window size cannot be controlled by HTML and so we need JavaScript help. If JavaScript is not enabled in a client browser, we will fall back to HTML code to handle the pop-up. Line 27 outputs the product rating, as reviewed by the user. Line 30 outputs the product's short description. Lines 31 to 33 outputs the text of product details within a hot link pointing to the product details page. Line 36 outputs the add-to-cart form, which includes the add-to-cart button, the quantity box, and so on. PHP crash course While we are not going to present all the complex program structure of PHP, it will be useful if we have a basic understanding of some of its major constructs. You may not fully understand what exactly each line of code does at first, but stick with us for a little while. You will soon grasp the concept as the pattern appears repeatedly in the exercise we will work on. In the preceding sample template, the PHP coding is pretty simple. (The most complex structure is actually the JavaScript that tries to spit out some HTML on the client browser, not PHP!) We can identify a few basic PHP constructs among the sample code: Variables: Just like any other programming language, a variable is a basic element in PHP. All PHP variables start with the dollar sign $. A variable name consists of alphanumeric characters and the underscore _ character. The first character must be either alphabetical or _, while numerals can also be used after the first character. It should be noted that the space character, together with most punctuation characters, are not allowed in a variable name. Alphabetic characters can be either uppercase or lowercase. Conventionally, VirtueMart will use only lowercase letters for variable names. While both uppercase and lowercase letters can be used without restrictions, variable names are case sensitive, meaning that $Product and $product will be treated as two different variables. The variable name chosen usually reflects the actual usage of the variable. In the sample template, $product_name and $product_flypage, for example, are typical variables and they will represent the value of a product name and product flypage, respectively. VirtueMart uses _ to separate words within a variable name to make the variable name more readable. Actually, many of the variables are passed into the template by the VirtueMart page file. These variables are called available fields. We will have more to say about that in the next subsection. Constants: Variables are changing values. You can assign a new value to it at any time and it will take up the new value. There are times when you want to keep the value unchanged. You can use a constant for that purpose. A constant name is pretty much the same as a variable name, but you don't need the $ character. In line 1 of the sample template, both _VALID_MOS and _JEXEC are constants. You probably recognize that they both use capital letters. This is conventional for Joomla! and VirtueMart so that constants stand out within the code. Constants are values that cannot be changed. If you try to give it another value, PHP will complain and fail. Data type: Any variable will have a data type associated with it. Data type can be a number, a string (that is, a series of characters or text), or other possibilities. Since the major purpose of a VirtueMart template is to produce HTML code, we will find that most of the variables we deal with are strings. Often, we will need to write out a literal string in our coding. To distinguish our string from the rest of the coding, we need to enclose the literal string with quotes. We can use single or double quotes. Single and double quotes actually have subtle differences, but we won't go into the detail for the time being. According to the VirtueMart program standard, a literal string should be enclosed in single quotes such as 'product name'. Note that 'product name' is a literal string containing the text product name. It is different from $product_name, which is a variable and may contain characters like 'circular saw' instead. Operators: You learnt addition and subtraction at school. They are mathematical operations to combine numbers. In PHP, we also have other operations to combine two or more variables. The most important one in our exercises is probably string concatenation, symbolized by . (the dot character). String concatenation combines two or more strings together to form a single string. The operation 'hello'.'world' will give a new string 'helloworld'. Note that there is no space character between the words. To make sure the words are separated by a space, we will need to use two concatenations such as 'hello'.' '.'world', which will give you the new string 'hello world'. Functions: Often, we will find that the same pattern of program code is used repeatedly to produce a given result. In PHP, we can group those code together to form a function. Each function will have a name and can be invoked using the following syntax: function_name (parameters) Here, parameters are values that will need to be passed into the function to evaluate the result. In PHP, we have lots of functions that deal with strings. The function strlen($product_name), for example, will return the number of characters in the string variable $product_name. If $product_name contains the string 'circular saw', strlen($product_name) will return 12. (You probably recognize that strlen is just a short form for string length.) We will learn some more functions along the way. echo statements: This is the most common statement in the template. echo is used to send the value of a string to the output buffer. So echo $product_name literally means "print out the value of the variable $product_name to the output buffer". Sometimes, the echo statement is mistaken to be a function. So you may try to write something like echo($product_name), instead of echo $product_name. While this is acceptable in PHP most of the time, the braces are actually not needed. (You may be aware that sometimes the command print function is used to send data to the output buffer in the place of echo. While print and echo seem interchangeable, echo runs faster than print and so should be the preferred choice to output data.) if statements: The if statement is a construct to test a condition before taking a certain action. The action will be taken only if the condition evaluates to true. The syntax of an if statement is as follows: if (condition) action where the condition is an expression for testing and action is a statement or a series of statements to be performed, if the expression evaluates to true. The expression can be a true-false type condition (such as $i>0), a mathematical expression (such as $i+$j), or some kind of complex operation involving functions. In any case, it will be considered as true, if it evaluates to a nonzero number or a non-empty string. Statement separator: One important PHP construct we usually overlook is the statement separator ; (the semicolon). We need this to separate two or more statements, even if they are on new lines of their own. In the preceding sample code, we have a ";" at the end of line 1 and 2. This ; is very important. Without that, the PHP parser will be confused and will probably refuse to execute and will give you a fatal error. These are just a few constructs in PHP for the time being. We will have more to say about PHP as we encounter more constructs along the way. Available fields Since many of the variables in our template code are passed down from the VirtueMart page file, one natural question to ask is "What variables can we use in our code?". Variables that we can use in a template are known as available fields. The available fields we have inside a template will vary with the template itself. A field which is available in the flypage template may not be available in a browse template. Even among the browse templates, there may be differences. To maximize our customization effort on a template, it is essential to be aware of the available fields in each template. However, there are so many available fields in a template that it may not be wise to list them all here. For now, it will be useful to distinguish four different types of available fields: Database fields: Most of the data we have comes from the database. Often, the VirtueMart page file just passes those fields directly to the template without changing anything. They are called database fields. The same data you put into the database from the backend will be at your fingertips. Examples are $product_id and $product_sku. Formatted database fields: Sometimes the data you stored in the database is raw data. You will need a different format in the presentation. VirtueMart will do some formatting on the data before passing it to the template. An example is $product_available_date, which is stored in the database as an integer. However, you need to display it in a form that is appropriate to your culture such as yyyy-mm-dd, mm-dd-yyyy, and so on. Processed data: Sometimes there may be complex logic before you can produce data that is useful in the template. A typical example is the $product_price. Do not expect this to be a simple number or a formatted number with the currency symbol added. Actually, the product price will depend on a number of factors such as whether the user has logged in, the shopper group, discount, tax, and so on. So the $product_price in the frontend may be different from the value you entered in the backend. Sometimes it is a formatted number and sometimes it is a message such as call for price. Another example is $product_thumb_image. You may expect this to be just the file location you see in the backend, but its value will depend on whether it is an out of site image, whether the image exists, and whether you want the image to be resized from the full image. VirtueMart class object: In certain cases, VirtueMart developers may think there are too many possibilities for the use of a piece of data. So they decided to let the template designer control what to do with the data. In those cases, VirtueMart will simply pass a class object to the template. An example of this is $ps_product. There are lots of opportunities to make good use of these class objects. However, you will need to understand how this can be properly used and bear all the complexities to make it work.   Core browse templates Product listing is unarguably the most important element on the product list page. There are two major factors that will affect the product listing: the product listing style, and the core browse template. Core browse templates are used to define the layout and styles for each product in the product list. There are actually six different core browse templates in the default theme. We can define a default core browse template for general use and also a specific template for each of the product categories. If you take a closer look at the templates, you will find that they are pretty much the same, except the last one which is for creating a PDF file. We already saw the detail coding in the browse_1.php. We don't need to repeat it here again. So, let's start on some exercises with the browse_1 template right away. Exercise 3.1: Adding an Ask-Seller link to the browse page We know that in the product detail page, there is an Ask-Seller link which will bring up a form so that a shopper can ask a question about the product. This link is not available on the product list page. In this exercise, we will add a similar link to the browse page. While we can use the exact same link here, we purposely use a simpler way to do it to make it easier to understand. Steps Open your favorite text editor. Navigate to the VirtueMart frontend root. Open the file themes/default/templates/browse/browse_1.php. Insert the following line of code after line 5: <a href="index.php?option=com_virtuemart&page=shop.ask&product_id=<?php echo $product_id ?>">Ask a question about thisproduct</a><br /> Save the file and upload it to your server. Point your browser to any VirtueMart browse page that uses the browse_1.php template, you should see the Ask-Seller link added to every product. (This exercise is done on the browse_1 template only. If you browse to the product list of an individual category, the new styles will show only if the category is using the browse_1 template. The same applies to most of the following exercises.) Notes The Ask-Seller link is an <a> tag with the href pointing to the Ask Seller page. The href is built using three parameters: option=com_virtuemart points to the VirtueMart component. page=shop.ask points to the actual Ask Seller page. By changing the page parameter, we can point the shopper to any of the VirtueMart pages. product_id=<? echo $product_id ?> provides the product ID to the Ask Seller page so that it knows which product the shopper has questions on. We need to use a variable because the product_id will vary from product to product. In the previous code, we purposely hardcoded the link as a relative URL to make the code simpler. This works unless SEF is enabled. To cater for SEF, a more generic way to create the link will be needed. The text Ask a question about this product is static text. Feel free to change it to anything you think appropriate. This will not affect the function of the link. <br /> is needed to insert a line break after the link. Exercise 3.1 demonstrates the basic technique to modify a template. You can add static text to a template in whatever way you want. If you need variable data, simply insert the appropriate echo statement at the required place.   Exercise 3.2: Changing core browse template CSS One major task of customizing a template is changing the style of HTML elements. In this exercise, we are going to add some CSS styles to the core browse template. Preparation This exercise is built upon the browse_1.php file we modified in Exercise 3.1. If you start from the original template file, the exact line number may differ. Steps Open your favorite text editor. Navigate to the VirtueMart frontend root. Open the file themes/default/templates/browse/browse_1.php. At line 4 (that is, the top of the file), insert the following lines of code: <?php if (!defined(VM_CUSTOM_CSS)) { define ('VM_CUSTOM_CSS',1);?> <style> .browseProductContainer {border:1px solid #999;padding:5px;background:#eee;margin:5px;} </style><?php } ?> Save the file and upload it to your server. Point your browser to any VirtueMart browse page that uses the browse_1.php template. You should see the product list now with the border, margin, and padding added. Notes We added a stylesheet for the class browseProductContainer in the template file. The stylesheet will be included as part of the HTML output to the browser. The core browse template will be applied for each product. So any coding added to it will be repeated for each product. To ensure that the stylesheet is included only once in the HTML, we define a constant named VM_CUSTOM_CSS the first time the stylesheet is included. The if condition at the start of the coding tests for the existence of the constant VM_CUSTOM_CSS. When the code is executed a second time, VM_CUSTOM_CSS is already defined and so the statements within the braces will be skipped. Exercise 3.2 demonstrates another basic technique to modify a template. The technique applies not only to a CSS stylesheet, but to all coding in general. It can be used for JavaScript inclusion, and for other coding that you only need to appear once in the HTML.   Exercise 3.3: Moving and modifying data In this exercise, we are going to experiment with moving data around and adding some new data fields that are available for the template. Preparation This exercise is built upon the browse_1.php file we modified in Exercise 3.2. If you start from the original template file, the exact line numbers may differ. Steps Open your favorite text editor. Navigate to the VirtueMart frontend root. Open the file themes/default/templates/browse/browse_1.php. At line 40, insert the following line of code: <br />Weight: <?php echo number_format($product_weight,1) .' ' . $product_weight_uom ?><br /> Move the Ask-Seller link from line 13 to line 47, that is, after the closing </span> tag for form_addtocart. Move the <br /> tag from the end of line 47 to the beginning of the line, that is, the line will become: <br /><a href="index.php?option=com_virtuemart&page=shop.ask&product_id=<?php echo $product_id ?>">Ask a question about thisproduct</a> Save the file and upload it to your server. Point your browser to any VirtueMart browse page that uses the browse_1.php template and you should see that the Ask-Seller link has moved to the end of the display, and the product weight and unit has been added to every product. Notes In this exercise, we have performed two modifications. We moved the Ask-Seller link to the bottom instead of the top and added the product_weight field to the browse template. Actually, the order of appearance of the product fields can be changed at will. You can move it around to fit your requirement similar way. To add new data to the display, you first need to determine what you want to show and whether the data is within the list of available fields. Since we know $product_weight and $product_weight_uom (uom stands for unit of measure) are available, we can simply use concatenation to build the final text for the output. The weight is rounded off to 1 decimal place using the number_format() function to make it look nicer. You can change the number of decimal places by changing the second parameter to the number_format() function.  
Read more
  • 0
  • 0
  • 2763
article-image-moodle-20-multimedia-creating-and-integrating-screencasts-and-videos
Packt
23 May 2011
8 min read
Save for later

Moodle 2.0 Multimedia: Creating and Integrating Screencasts and Videos

Packt
23 May 2011
8 min read
  Moodle 2.0 Multimedia Cookbook Add images, videos, music, and much more to make your Moodle course interactive and fun         Read more about this book       (For more resources on Moodle 2.0, see here.) Introduction Moodle 2.0 offers new features, which make it easier to insert videos, especially from the http://www.youtube.com website. You can find them easily from the file picker, provided you have administrative access to the course. You have to bear in mind that you need to be an administrator in order to enable this option. This article covers different ways to create and interact using either screencasts or videos. We will work with several multimedia assets, which will concern the baseline topic of Wildlife. This topic has many resources, which can be integrated with screencasts and videos available on the Web. Creating screencasts using several free and open source software available on the Web is one of the main goals of this chapter. There is plenty of commercial software, which can be used to create screencasts. We will not focus on them though. We add some special features to the screencasts in order to enhance them. Videos can be recorded in several ways. You may use your cell phone, camera, or the webcam of your computer. We are to focus on the way of creating them and uploading into our Moodle course. We can also use a recorded video from YouTube and upload it directly from the file picker in Moodle 2.0. You can also design a playlist in order to combine several videos and let your students watch them in a row. We do it by creating an account in YouTube. The channel in YouTube can be either public or private; it depends on how we want to carry it out. You can create some screencasts in order to present information to your students instead of showing presentations made using Open Office, PowerPoint, or Microsoft Word. Changing any of these into a screencast is more appealing to the students and not such a difficult task to carry out either. We can create an explanation by recording our voice, for which we will create a virtual board that we can choose to be visible to the audience; in the second case, our explanations can only be heard with no visualization. This is quite an important aspect to be taken into account, especially in teaching because students need a dynamic explanation by their teacher. There are several software available that can be used to create screencasts. One of them is Cam Studio. This software captures AVI files and it is open source. It captures onscreen video and audio. Its disadvantage is that only Windows users can use it. You can download it from http://camstudio.com/. It is time for Mac users. There is also a free program for Mac users that focuses on making quick films by saving the recorded video to get a quick access. It does not record audio. This is Copernicus and you can download it from http://danicsoft.com/software/copernicus/. We need a tool for both Mac and Windows, which is free and open source as well. So, JingProject.com is the software. It does not only record video, but also allows you to take a picture, draw, or add a message on it, and upload the media to a free hosting account. A URL is provided in order to watch the video or the image. You can download it from the following website: http://www.techsmith.com/download/jing/. Screencast-o-matic is another tool that is based on Java that does not need to be downloaded at all. It allows you to upload in an automatic way. It works well with both Mac and Windows machines. You can use this at http://www.screencast-o-matic.com/. This is the tool that we are to work with in the creation of a screencast. We may also modify the videos to make them suitable for learning. We can add annotations in different ways so as to interact through the video with our students. That is to say, we add our comments instead of adding our voice so that students read what we need to tell them. Creating a screencast In this recipe, we create a screencast and upload it to our Moodle course. The baseline topic is Wildlife. Therefore, in this recipe, we will explain to our students where wild animals are located. We can paste in a world map of the different animals, while we add extra data through the audio files. Thus, we can also add more information using different types of images that are inserted in the map. Getting ready Before creating the screencast, plan the whole sequence of the explanation that we want to show to our students, therefore, we will use a very useful Java applet available at http://www.screencast-o-matic.com/. Screencast-o-matic requires the free Java Run-time Environment (also known as JRE) for both the teacher and the students' computers. You can download and install its latest version from http://java.sun.com. How to do it... First of all, design the background scene of the screencast to work with. Afterwards, enter the website http://www.screencast-o-matic.com/. Follow these to create the screencast: Click on Start recording. Another pop-up window appears that looks as shown in the following screenshot: Resize the frame to surround the recording area that you want to record. Click on the recording button (red button). If you want to make a pause, click on the pause button or Alt + P, as shown in the following screenshot: If you want to integrate the webcam or a bluetooth video, click on the upwards arrow in this icon, as shown in the following screenshot: When the screencast is finished, click on Done. You can preview the screencast after you finish designing it. If you need to edit it, click on Go back to add more. If you are satisfied with the preview, click on Done with this screencast, as shown in the following screenshot: When the screencast is finished, our next task is to export it because we need to upload it to our Moodle course. Click on Export Movie. Click on the downwards arrow in Type and choose Flash (FLV), as shown in the following screenshot: Customize the Size and Options blocks, as shown in the previous screenshot or as you wish. When you finish, click on Export, as shown in the previous screenshot. Write a name for this file and click on Save. When the file is exported, click on Go back and do more with this screencast if you want to edit it. Click on Done with this screencast if you are satisfied with the result. A pop-up window appears, click on OK. How it works... We have just created the screencast teaching about wild animals, which students have to watch to learn about the places where wild animals live around the world. We need to upload it to our Moodle course. It is a passive resource; therefore, we can add a resource or design an activity out of it. In this case, we design an activity. Choose the weekly outline section where you want to insert it, and follow these steps: Click on Add an activity | Online text within Assignments. Complete the Assignment name and Description blocks. Click on the Moodle Media icon | Find or upload a sound, video or applet ... | Upload a file | Browse | look for the file that you want to upload and click on it. Click on Open | Upload this file | Insert. Click on Save and return to course. Click on the activity. It looks as shown in the following screenshot: There's more... In the case that we create a screencast, which lasts for around 30 minutes or longer, it will take a long time to upload it to our Moodle course. Therefore, it will be advisable to watch the screencast using a free and open source media player, that is to say VLC Media Player. VLC Media Player You can download the VLC Media Player from the following website: http://www.videolan.org/vlc/. It works with most popular video files formats such as AVI, MP4, and Flash, among others. Follow these steps in order to watch the screencast: Click on Media | Open File | browse for the file that you want to open and click on it. Click on Open. The screencast is displayed, as shown in the following screenshot: See also Enhancing a screencast with annotations  
Read more
  • 0
  • 0
  • 3339

article-image-getting-started-internet-explorer-mobile
Packt
23 May 2011
13 min read
Save for later

Getting Started with Internet Explorer Mobile

Packt
23 May 2011
13 min read
  Microsoft SharePoint 2010 Enterprise Applications on Windows Phone 7 Create enterprise-ready websites and applications that access Microsoft SharePoint on Windows Phone 7 To get started with Internet Explorer Mobile let's look at basic web page architecture.   Web page architecture Web pages on the client side mainly consist of three vital components: HTML, CSS, and JavaScript. The exact version of each of these varies, but in the end it all comes down to these three pieces. HyperText Markup Language (HTML) HyperText Markup Language (HTML) is the container for the page content. The page should contain just that content and nothing else. A properly coded site would leave the presentation and functionality portions of the page to CSS and JavaScript. In addition, the content should be constructed in a manner that makes logical sense for the content that is being delivered. This is called semantic HTML. People with disabilities use devices, such as a screen reader, to get the content of a site. These screen readers can only gather information from the actual markup of the site. If we have a PNG image with text in it, the screen reader cannot "see" that information. In that particular case, we can use the alt attribute of the image to provide a hint to the content, but it would be better to put the content inside a paragraph, unordered list, or some other textual tag and then replace it with an image if absolutely required using JavaScript. The other case that was mentioned earlier was that search engines can better determine the contents of a web page with semantic markup. This will help our page rankings and hopefully drive more visitors to our site. Think about the HTML markup like the script of a movie. Although we'll add lights, actors, and probably special effects later, right now the black and white text on paper has to convey all of the meaning. The same is true of the HTML markup for your site. As you build websites, constantly keep in mind what information you are trying to impart with the page and make that the focus. Cascading Style Sheets (CSS) Cascading Style Sheets (CSS) are documents that describe the way HTML should be displayed. The CSS language allows the web developer to separate the design aspects (layout, colors, fonts, and so on) from the page content. One could easily change the entire look and feel of a page simply by replacing the CSS files. An amazing group of examples of this is available at http://csszengarden.com. The CSS Zen Garden website demonstrates the amazing power that CSS has on the presentation of HTML content. Utilizing a proper style sheet can result in content that will quickly display the relevant information that a Windows Phone 7 user has come to expect from the applications on the phone. When developing websites that are going to be viewed on Internet Explorer Mobile, it is important to keep in mind some very important potential problems. Although float works great on desktop browsers and will work on many mobile browsers, the content within these containers may not look good on a small screen. The CSS float attribute was one of the first tools that allowed web developers to break free from table based layouts, that is, laying out the contents of a page using tables. Float allowed developers to group content in div elements and then float those block elements into position. It is a very powerful tool, but on a mobile device, the limited screen size would hamper the ability for the user to view the content. Instead, they would be constantly scrolling left and right or up and down to find all the content. A better way of handling this would be to utilize float on the desktop version of the site and then leave the div elements in block display allowing the IE Mobile browser to handle the content layout. Along these same lines, the CSS attributes, padding and margin, work great for precise positioning of elements on a desktop browser. However, the limited screen real-estate of a Mobile browser limits the usefulness of this positioning power. Try to limit the use of these attributes on the mobile device and only use them to highlight useful information. Finally, because pixels are absolute values, a pixel is a precise defined scale of measurement with no room for interpretation; the phone has to work more to display those elements that are positioned using pixel measurements. Using points, em, or percentage measurements instead, allow the phone to be more fluid with the layout. Be sure to test the site on Windows Phone 7 devices to ensure the content is legible and the display is fine. JavaScript JavaScript, otherwise known as ECMAScript, is the scripting language that is used to create dynamic user interfaces and allow a page to update "on the fly". Users have come to expect a certain fluidity to their web experiences, and now with the power of Internet Explorer Mobile for Windows Phone 7, they can have that same power in the palm of their hand. Remember that the user is probably looking at a 3.5 inch screen, has fingers that are roughly 40-80 pixels square, and those fingers are incapable of registering a hover command to the browser. If your navigation, for example, requires the user to hover over something, this will not work in Internet Explorer Mobile. Instead, make the navigation an easy to use, unordered list of hyperlinks Putting HTML, CSS, and JavaScript together Windows Phone 7 is about getting the relevant information viewable with minimal fuss. The following are some tips for creating a website for Windows Phone 7's Internet Explorer Mobile: Show only the content that is relevant for the page requested Reduce the use of images and colors Remove the extra-large hero images Hero images are those large images usually at the top of the main content section, but usually used as a graphic headline. Usually, they don't contain any content and only serve to enhance the design of the site. Rearrange the navigation to take up a minimum amount of space Move the navigation to the bottom of the page if possible Remove flashy loading screens Utilizing HTML, CSS, and JavaScript with proper discipline will result in more satisfied customers. Developing websites is not a trivial task. Mastering each of these three components is a great task. It is important, while developing websites, to try and minimize as much duplication as possible, not only in the JavaScript code that so many developers tended to focus on, but also in the CSS and the HTML content. Reducing duplication will allow for maintainable, upgradable, and understandable code. Also, by reducing duplication, the amount of data sent to the browser is also reduced. This is helpful when dealing with a browser that is connecting from a patchy cellular network. Historically, building a mobile version of a website meant a completely different team of designers and web developers built a totally separate web application from the desktop version of the site. Then, using the server side code, the mobile browsers were detected and redirected to the mobile version. SharePoint does this by redirecting mobile browsers to {server}/_layout/mobile/mblwiki.aspx?Url=%2FSitePages%2FHome%2Easpx as an example. When starting a new web application, a general rule of thumb is to use content adaptation techniques for the application. However, for a baseline you must have at least: ECMAScript 3 W3C DOM Level 1 W3C standard box model support CSS2 rendering Client-side cookies support XMLHttpRequest object support By targeting this lowest common denominator of browser, we will ensure that our web applications will run well on most browsers on the web. Remember that common practices on desktop browsers may end up being annoyances on a mobile device. Try not to open modal dialog boxes, or even open pop-ups. Opening a pop-up window will cause a whole new tab to appear. This may even close a tab that the user had previously opened if they already had six tabs open. When designing the user interaction for a website, always keep the user in mind. They are busy people coming to your website. Be kind to them. Give them the information they are looking for without hassle.   Internet Explorer Mobile Windows Phone 7 comes with a new browser that is based on the rendering engine of Internet Explorer 7 and some JavaScript improvements from Internet Explorer 8. Additionally, it includes some enhancements that aren't found in either of those desktop browsers. Internet Explorer Mobile User Agent The Internet Explorer Mobile User Agent string is as follows: Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0; <DeviceManufacturer>; <DeviceModel>) This UA String allows the device manufacturer to insert their name and the model of the phone in the string. Knowing the User Agent string is helpful when reviewing server logs to determine what browsers are coming to your website. This will help you optimize your site for the people who actually are viewing your content. Like previous versions of Internet Explorer Mobile, the user can select either a Mobile version or a Desktop version display engine. When the Desktop version is selected, the User Agent string changes to the following: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; XBLWP7; ZuneWP7) Changing the display engine mode can be accomplished on the Internet Explorer SETTINGS screen, as shown in the following screenshot: Although this choice could complicate things, as we develop our sites, we should make careful consideration of how we are going to treat the mobile version, but try not to detect the desktop version. If the user makes a conscious choice to view the desktop version, we should not force them to view something different from what they would see on a real desktop browser. Client side browser detection Many people use the user agent string to detect at runtime what to display on the browser. Although this works, there are better techniques to find out if the browser is mobile. Those techniques should be used instead of User Agent detection. Using property detection instead of browser detection will allow your site to be forward compatible. Forward compatibility isn't a very complex idea. It is just thinking about programming so that as new browsers come along with new capabilities, we won't have to rewrite our applications to take advantage of these capabilities. The application just takes advantage of whatever functionality is available to it in whatever browser in which it is currently running. An example of property detection is as follows: function hasAdvancedDOM() { // check for a feature that is known to be advanced if(document.getElementsByClassName) return true; return false } Downloading the example code You can download the example code files from here The preceding code simply detects if the DOM function document.getElementsByClassName() exists or not. Internet Explorer Mobile has this function, as does Firefox 2+, Safari, Chrome, and Internet Explorer 9. However, previous versions of Internet Explorer Mobile did not have this function. If we had this in a previous version of a website, we wouldn't have to do anything special to get this to work in Windows Phone 7's Internet Explorer Mobile. Although, the code we would actually write in a web page would be much more complicated, this example demonstrates a starting point. Server-side detection Server-side detection usually uses the User Agent string along with a large list of mobile device User Agent strings to determine the capabilities of the browsers requesting a page. This list of mobile devices and their capabilities are kept in a .browser file. There are some projects on the web to keep and maintain this .browser file. The best known of these, "Mobile Device Browser File", available at http://mdbf.codeplex.com, lost funding from Microsoft. There is another one that can be found at http://aspnet.codeplex.com/releases/view/41420. The main topic of this article is SharePoint 2010 development for Windows Phone 7. However, ASP.NET 3.5 SP1 is the framework that SharePoint 2010 development is based on. This framework has a smaller list of browsers in the .browser file than the more current ASP.NET 4. One of the omissions is IEMobile. What this means is that in ASP.NET 4, you can use the following code to detect a mobile browser: Request.Browser.IsMobileDevice This code will work in ASP.NET 3.5 SP1, but it will not return true for Windows Phone 7's Internet Explorer Mobile by default. The simplest solution is to use code like this to detect the IE Mobile browser: Request.UserAgent.ToString().Contains("IEMobile") We could probably do better here. In the first place, we could update SharePoint's compat.browser file to include Windows Phone 7. The compat.browser can be found here: <drive>:inetpubwwwrootwssVirtualDirectories<site>80App_Browserscompat.browser The structure of this file can be found at the following URL: http://msdn.microsoft.com/en-us/library/ms228122.aspx If you look at SharePoint's compat.browser file, the fourth browser listed looks like it might be for the Windows Phone 7 Internet Explorer Mobile. However, a closer examination will show that this browser is actually for the Office Hub in Windows Phone 7. To add the Internet Explorer Mobile browser, copy the browser elements for Internet Explorer Mobile for Windows Mobile 6.5 and edit it like this: <browser id="IE7MobileDesktopMode" parentID="IE6to9"> <identification> <userAgent match="XBLWP7" /> </identification> <capabilities> <capability name="supportsTouchScreen" value="true" /> </capabilities> </browser> <browser id=”IE7MobileMobileMode” parentID=”Mozilla”> <identification> <userAgent match="(?i)Windows Mobile OSs7.d.*IEMobile/ (?'version'd+).(?'minor'd+)" /> </identification> <capabilities> <capability name="browser" value="IE Mobile" /> <capability name="canInitiateVoiceCall" value="true" /> <capability name="isMobileDevice" value="true" /> <capability name="javascript" value="true" /> <capability name="optimumPageWeight" value="1500" /> <capability name="tables" value="true" /> <capability name="version" value="${version}" /> <capability name="supportsTouchScreen" value="true" /> </capabilities> </browser> This will make our code easier to manage later by allowing us to use the Request.Browser.IsMobileDevice property. The change here, besides changing the browser ID, is in the regular expression which is used to detect the browser. In the desktop mode, we look for the text, XBLWP7, as this is a very obvious change in the User Agent in this state. For the mobile mode, we copied the IE Mobile 6 plus browser section. Microsoft changed the User Agent slightly between IE Mobile 6 and IE Mobile 7. The change comes in the User Agent, IE Mobile 7 doesn't have a space between the browser name IEMobile and the start of the version number. Instead, it has a forward slash. IE Mobile 6 had a space between the browser name and the version number.  
Read more
  • 0
  • 0
  • 1828

article-image-python-3-building-wiki-application
Packt
19 May 2011
17 min read
Save for later

Python 3: Building a Wiki Application

Packt
19 May 2011
17 min read
Python 3 Web Development Beginner's Guide Nowadays, a wiki is a well-known tool to enable people to maintain a body of knowledge in a cooperative way. Wikipedia (http://wikipedia.org) might be the most famous example of a wiki today, but countless numbers of forums use some sort of wiki and many tools and libraries exist to implement a wiki application. In this article, we will develop a wiki of our own, and in doing so, we will focus on two important concepts in building web applications. The first one is the design of the data layer. The second one is input validation. A wiki is normally a very public application that might not even employ a basic authentication scheme to identify users. This makes contributing to a wiki very simple, yet also makes a wiki vulnerable in the sense that anyone can put anything on a wiki page. It's therefore a good idea to verify the content of any submitted change. You may, for example, strip out any HTML markup or disallow external links. Enhancing user interactions in a meaningful way is often closely related with input validation. Client-side input validation helps prevent the user from entering unwanted input and is therefore a valuable addition to any application but is not a substitute for server-side input validation as we cannot trust the outside world not to try and access our server in unintended ways. The data layer A wiki consists of quite a number of distinct entities we can indentify. We will implement these entities and the relations that exist between them by reusing the Entity/Relation framework developed earlier. Time for action – designing the wiki data model As with any application, when we start developing our wiki application we must first take a few steps to create a data model that can act as a starting point for the development: Identify each entity that plays a role in the application. This might depend on the requirements. For example, because we want the user to be able to change the title of a topic and we want to archive revisions of the content, we define separate Topic and Page entities. Identify direct relations between entities. Our decision to define separate Topic and Page entities imply a relation between them, but there are more relations that can be identified, for example, between Topic and Tag. Do not specify indirect relations: All topics marked with the same tag are in a sense related, but in general, it is not necessary to record these indirect relations as they can easily be inferred from the recorded relation between topics and tags. The image shows the different entities and relations we can identify in our wiki application. In the diagram, we have illustrated the fact that a Topic may have more than one Page while a Page refers to a single User in a rather informal way by representing Page as a stack of rectangles and User as a single rectangle. In this manner, we can grasp the most relevant aspects of the relations at a glance. When we want to show more relations or relations with different characteristics, it might be a good idea to use more formal methods and tools. A good starting point is the Wikipedia entry on UML: http://en.wikipedia.org/wiki/Unified_Modelling_Language. What just happened? With the entities and relations in our data model identified, we can have a look at their specific qualities. The basic entity in a wiki is a Topic. A topic, in this context, is basically a title that describes what this topic is about. A topic has any number of associated Pages. Each instance of a Page represents a revision; the most recent revision is the current version of a topic. Each time a topic is edited, a new revision is stored in the database. This way, we can simply revert to an earlier version if we made a mistake or compare the contents of two revisions. To simplify identifying revisions, each revision has a modification date. We also maintain a relation between the Page and the User that modified that Page. In the wiki application that we will develop, it is also possible to associate any number of tags with a topic. A Tag entity consists simply of a tag attribute. The important part is the relation that exists between the Topic entity and the Tag entity. Like a Tag, a Word entity consists of a single attribute. Again, the important bit is the relation, this time, between a Topic and any number of Words. We will maintain this relation to reflect the words used in the current versions (that is, the last revision of a Page) of a Topic. This will allow for fairly responsive full text search facilities. The final entity we encounter is the Image entity. We will use this to store images alongside the pages with text. We do not define any relation between topics and images. Images might be referred to in the text of the topic, but besides this textual reference, we do not maintain a formal relation. If we would like to maintain such a relation, we would be forced to scan for image references each time a new revision of a page was stored, and probably we would need to signal something if a reference attempt was made to a non-existing image. In this case, we choose to ignore this: references to images that do not exist in the database will simply show nothing: Chapter6/wikidb.py from entity import Entity from relation import Relation class User(Entity): pass class Topic(Entity): pass class Page(Entity): pass class Tag(Entity): pass class Word(Entity): pass class Image(Entity): pass class UserPage(Relation): pass class TopicPage(Relation): pass class TopicTag(Relation): pass class ImagePage(Relation): pass class TopicWord(Relation): pass def threadinit(db): User.threadinit(db) Topic.threadinit(db) Page.threadinit(db) Tag.threadinit(db) Word.threadinit(db) Image.threadinit(db) UserPage.threadinit(db) TopicPage.threadinit(db) TopicTag.threadinit(db) ImagePage.threadinit(db) TopicWord.threadinit(db) def inittable(): User.inittable(userid="unique not null") Topic.inittable(title="unique not null") Page.inittable(content="", modified="not null default CURRENT_TIMESTAMP") Tag.inittable(tag="unique not null") Word.inittable(word="unique not null") Image.inittable(type="",data="blob",title="", modified="not null default CURRENT_TIMESTAMP", description="") UserPage.inittable(User,Page) TopicPage.inittable(Topic,Page) TopicTag.inittable(Topic,Tag) TopicWord.inittable(Topic,Word) Because we can reuse the entity and relation modules we developed earlier, the actual implementation of the database layer is straightforward (full code is available as wikidb.py). After importing both modules, we first define a subclass of Entity for each entity we identified in our data model. All these classes are used as is, so they have only a pass statement as their body. Likewise, we define a subclass of Relation for each relation we need to implement in our wiki application. All these Entity and Relation subclasses still need the initialization code to be called once each time the application starts and that is where the convenience function initdb() comes in. It bundles the initialization code for each entity and relation (highlighted). Many entities we define here are simple but a few warrant a closer inspection. The Page entity contains a modified column that has a non null constraint. It also has a default: CURRENT_TIMESTAMP (highlighted). This default is SQLite specific (other database engines will have other ways of specifying such a default) and will initialize the modified column to the current date and time if we create a new Page record without explicitly setting a value. The Image entity also has a definition that is a little bit different: its data column is explicitly defined to have a blob affinity. This will enable us to store binary data without any problem in this table, something we need to store and retrieve the binary data contained in an image. Of course, SQLite will happily store anything we pass it in this column, but if we pass it an array of bytes (not a string that is), that array is stored as is. The delivery layer With the foundation, that is, the data layer in place, we build on it when we develop the delivery layer. Between the delivery layer and the database layer, there is an additional layer that encapsulates the domain-specific knowledge (that is, it knows how to verify that the title of a new Topic entity conforms to the requirements we set for it before it stores it in the database): Each different layer in our application is implemented in its own file or files. It is easy to get confused, so before we delve further into these files, have a look at the following table. It lists the different files that together make up the wiki application and refers to the names of the layers. We'll focus on the main CherryPy application first to get a feel for the behavior of the application. Time for action – implementing the opening screen The opening screen of the wiki application shows a list of all defined topics on the right and several ways to locate topics on the left. Note that it still looks quite rough because, at this point, we haven't applied any style sheets: Let us first take a few steps to identify the underlying structure. This structure is what we would like to represent in the HTML markup: Identify related pieces of information that are grouped together. These form the backbone of a structured web page. In this case, the search features on the left form a group of elements distinct from the list of topics on the right. Identify distinct pieces of functionality within these larger groups. For example, the elements (input field and search button) that together make up the word search are such a piece of functionality, as are the tag search and the tag cloud. Try to identify any hidden functionality, that is, necessary pieces of information that will have to be part of the HTML markup, but are not directly visible on a page. In our case, we have links to the jQuery and JQuery UI JavaScript libraries and links to CSS style sheets. Identifying these distinct pieces will not only help to put together HTML markup that reflects the structure of a page, but also help to identify necessary functionality in the delivery layer because each of these functional pieces is concerned with specific information processed and produced by the server. What just happened? Let us look in somewhat more detail at the structure of the opening page that we identified. Most notable are three search input fields to locate topics based on words occurring in their bodies, based on their actual title or based on tags associated with a topic. These search fields feature auto complete functionality that allows for comma-separated lists. In the same column, there is also room for a tag cloud, an alphabetical list of tags with font sizes dependent on the number of topics marked with that tag. The structural components The HTML markup for this opening page is shown next. It is available as the file basepage.html and the contents of this file are served by several methods in the Wiki class implementing the delivery layer, each with a suitable content segment. Also, some of the content will be filled in by AJAX calls, as we will see in a moment: Chapter6/basepage.html <html> <head> <title>Wiki</title> <script src= "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"> </script> <script src= "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.3/jquery-ui.min.js" type="text/javascript"> </script> <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/ jqueryui/1.8.3/themes/smoothness/jquery-ui.css" type="text/css" media="all" /> <link rel="stylesheet" href="/wiki.css" type="text/css" media="all" /> </head> <body> <div id="navigation"> <div class="navitem"> <a href="./">Wiki Home</a> </div> <div class="navitem"> <span class="label">Search topic</span> <form id="topicsearch"> <input type="text" > <button type="submit" >Search</button> </form> </div> <div class="navitem"> <span class="label">Search word</span> <form id="wordsearch"> <input type="text" > <button type="submit" >Search</button> </form> </div> <div class="navitem"> <span class="label">Search tag</span> <form id="tagsearch"> <input type="text" > <button type="submit" >Search</button> </form> </div> <div class="navitem"> <p id="tagcloud">Tag cloud</p> </div> </div> <div id="content">%s</div> <script src="/wikiweb.js" type="text/javascript"></script> </body> </html> The <head> element contains both links to CSS style sheets and <script> elements that refer to the jQuery libraries. This time, we choose again to retrieve these libraries from a public content delivery network. The highlighted lines show the top-level <div> elements that define the structure of the page. In this case, we have identified a navigation part and a content part and this is reflected in the HTML markup. Enclosed in the navigation part are the search functions, each in their own <div> element. The content part contains just an interpolation placeholder %s for now, that will be filled in by the method that serves this markup. Just before the end of the body of the markup is a final <script> element that refers to a JavaScript file that will perform actions specific to our application and we will examine those later. The application methods The markup from the previous section is served by methods of the Wiki class, an instance of which class can be mounted as a CherryPy application. The index() method, for example, is where we produce the markup for the opening screen (the complete file is available as wikiweb.py and contains several other methods that we will examine in the following sections): Chapter6/wikiweb.py @cherrypy.expose def index(self): item = '<li><a href="show?topic=%s">%s</a></li>' topiclist = "n".join( [item%(t,t)for t in wiki.gettopiclist()]) content = '<div id="wikihome"><ul>%s</ul></div>'%( topiclist,) return basepage % content First, we define the markup for every topic we will display in the main area of the opening page (highlighted). The markup consists of a list item that contains an anchor element that refers to a URL relative to the page showing the opening screen. Using relative URLs allows us to mount the class that implements this part of the application anywhere in the tree that serves the CherryPy application. The show() method that will serve this URL takes a topic parameter whose value is interpolated in the next line for each topic that is present in the database. The result is joined to a single string that is interpolated into yet another string that encapsulates all the list items we just generated in an unordered list (a <ul> element in the markup) and this is finally returned as the interpolated content of the basepage variable. In the definition of the index() method, we see a pattern that will be repeated often in the wiki application: methods in the delivery layer, like index(), concern themselves with constructing and serving markup to the client and delegate the actual retrieval of information to a module that knows all about the wiki itself. Here the list of topics is produced by the wiki.gettopiclist() function, while index() converts this information to markup. Separation of these activities helps to keep the code readable and therefore maintainable. Time for action – implementing a wiki topic screen When we request a URL of the form show?topic=value, this will result in calling the show() method. If value equals an existing topic, the following (as yet unstyled) screen is the result: Just as for the opening screen, we take steps to: Identify the main areas on screen Identify specific functionality Identify any hidden functionality The page structure is very similar to the opening screen, with the same navigational items, but instead of a list of topics, we see the content of the requested topic together with some additional information like the tags associated with this subject and a button that may be clicked to edit the contents of this topic. After all, collaboratively editing content is what a Wiki is all about. We deliberately made the choice not to refresh the contents of just a part of the opening screen with an AJAX call, but opted instead for a simple link that replaces the whole page. This way, there will be an unambiguous URL in the address bar of the browser that will point at the topic. This allows for easy bookmarking. An AJAX call would have left the URL of the opening screen that is visible in the address bar of the browser unaltered and although there are ways to alleviate this problem, we settle for this simple solution here. What just happened? As the main structure we identified is almost identical to the one for the opening page, the show() method will reuse the markup in basepage.html. Chapter6/wikiweb.py @cherrypy.expose def show(self,topic): topic = topic.capitalize() currentcontent,tags = wiki.gettopic(topic) currentcontent = "".join(wiki.render(currentcontent)) tags = ['<li><a href="searchtags?tags=%s">%s</a></li>'%( t,t) for t in tags] content = ''' <div> <h1>%s</h1><a href="edit?topic=%s">Edit</a> </div> <div id="wikitopic">%s</div> <div id="wikitags"><ul>%s</ul></div> <div id="revisions">revisions</div> ''' % ( topic, topic, currentcontent,"n".join(tags)) return basepage % content The show() method delegates most of the work to the wiki.gettopic() method (highlighted) that we will examine in the next section and concentrates on creating the markup it will deliver to the client. wiki.gettopic() will return a tuple that consists of both the current content of the topic and a list of tags. Those tags are converted to <li> elements with anchors that point to the searchtags URL. This list of tags provides a simple way for the reader to find related topics with a single click. The searchtags URL takes a tags argument so a single <li> element constructed this way may look like this: <li><a href="searchtags?tags=Python">Python</a></li>. The content and the clickable list of tags are embedded in the markup of the basepage together with an anchor that points to the edit URL. Later, we will style this anchor to look like a button and when the user clicks it, it will present a page where the content may be edited.  
Read more
  • 0
  • 0
  • 9507
article-image-html5-developing-rich-media-applications-using-canvas
Packt
19 May 2011
10 min read
Save for later

HTML5: Developing Rich Media Applications using Canvas

Packt
19 May 2011
10 min read
HTML5 Multimedia Development Cookbook Recipes for practical, real-world HTML5 multimedia driven development. The cool thing with the new open-source canvas element is that not only can you create dynamic images on the fly, but the users' actions can create new images in real time as well—all without requiring a plugin. Sounds great, right? In many ways it is, but it also leaves our friends using assistive technologies out in the cold. What will happen if you're using a browser that doesn't support the new canvas element? Pretty much nothing. The browser just won't display it. That's why you'll need to be especially careful with this technology and not place anything inside the new canvas element on which your site or application absolutely depends. You must also consider fallback content. Browsers that support canvas include: Before proceeding with developing with the new canvas element, make sure you have a good foundation of skills with HTML and JavaScript. Being comfortable with object-oriented programming sure wouldn't hurt either. Now, let's get cooking! Setting up the canvas environment Creating the new canvas element is easy. How to do it... Check out how simple this is: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> </head> <body> <canvas id="FirstCanvas" width="800" height="600"> <!-- Fallback code goes here --> </canvas> </body> </html> How it works... Of course, we can use whatever height and width dimensions we need, but that simple set of tags is what we need to start. You're probably thinking we could use CSS to control the height and width, but resist that temptation. Because the new canvas element contains a 2d rendering context, that approach can cause unpredictable behavior. There's more... Next, we'll call the new canvas element JavaScript API while calling jQuery: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/ jquery.min.js"></script> <script> $(document).ready(function() { var canvas = document.getElementById("FirstCanvas"); var ctx = canvas.getContext("2d"); }); </script> </head> <body> <canvas id="FirstCanvas" width="800" height="600"> <!-- Fallback code goes here --> </canvas> </body> </html> He's smart "Let me make one thing completely clear: When you use canvas, you're not drawing on the canvas element itself. Instead, you're actually drawing on the 2d rendering context, which you're accessing through the canvas element via the JavaScript API." – Rob Hawkes What am I sayin'? Apple first introduced the new canvas element for the OSX Dashboard years ago. It was later implemented in web browsers Safari and then Chrome, with other browsers following suit. Since then it's become an official part of the HTML5 specification. What's next for <canvas>? Right now, we're barely scratching the surface of what the new canvas element can do. Now and in the future we'll use it to create animations, charts, diagrams, drawing apps, graphs, and user interfaces. What will you dream up? See also Developer Martin Angelov penned a great how-to guide titled, "An HTML5 Slideshow w/Canvas & jQuery" for Tutorial Zine at: http://tutorialzine.com/2010/09/html5-canvas-slideshow-jquery. In it, Martin demonstrates how to combine the new canvas element with jQuery, the most popular JavaScript framework, to create an intensely interactive image slideshow. Understanding the 2d rendering context It's important to understand that the new canvas element is really a "surface" on which to draw bitmapped images in the browser. How to do it... Defining a canvas tag like this only tells half the story: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> </head> <body> <canvas id="FirstCanvas" width="800" height="600"> <!-- Fallback code goes here --> </canvas> </body> </html> How it works... By itself that HTML5 code does nothing. We have to use JavaScript to make the Document Object Model retrieve the 2d rendering context in order to get something to happen: <script> $(document).ready(function() { var canvas = document.getElementById("FirstCanvas"); var ctx = canvas.getContext("2d"); }); </script> To be fair, that bit of JavaScript won't do anything without the canvas tag in the HTML either. There's more... You may be wondering about the name. If there's a 2d rendering context, isn't there probably a 3d rendering context too? The short answer is yes. But the more detailed answer isn't so simple. While a 3d rendering context does exist in theory, at the time of this publication no browser supports it. So if the new canvas element renders in 3d but nobody sees it, did it really do anything? You can master <canvas> The 2d context uses a number of different drawing contexts for the new canvas element that use syntaxes that should look quite familiar if you're experienced with CSS and JavaScript. X, meet Y When drawing, remember the X and Y axis in the top left corner of your browser window. Values increase going down the page. Respect my authority! The World Wide Web Consortium's HTML5 Canvas 2d Context specification is online at: http://dev.w3.org/html5/2dcontext. There we can dig even deeper into information like conformance requirements, the canvas state, transformations, compositing, colors and styles, line styles, shadows, simple shapes, complex shapes, focus management, text, images, pixel manipulation, drawing model, examples, and more. Processing shapes dynamically Let's look at the JavaScript functions that allow the new canvas element to draw rectangles. How to do it... fillRect(x,y,width,height) strokeRect(x,y,width,height) In order: fillRect(x,y,width,height) draws a filled rectangle. Next, strokeRect(x,y,width,height) draws an outline around the rectangle. Now, let's draw some shapes. How it works... We'll start with our basic canvas code and incorporate our new functions: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/ jquery.min.js"></script> <script> $(document).ready(function() { var canvas = document.getElementById("FirstCanvas"); var ctx = canvas.getContext("2d"); ctx.strokeRect(10, 10, 396, 236); ctx.fillStyle = "red"; ctx.fillRect(11, 11, 100, 100); ctx.fillStyle = "white"; ctx.fillRect(111, 11, 34, 100); ctx.fillStyle = "red"; ctx.fillRect(156, 11, 249, 100); ctx.fillStyle = "white"; ctx.fillRect(11, 111, 394, 34); ctx.fillStyle = "red"; ctx.fillRect(11, 145, 100, 100); ctx.fillStyle = "white"; ctx.fillRect(111, 145, 34, 100); ctx.fillStyle = "red"; ctx.fillRect(156, 145, 249, 100); }); </script> </head> <body> <canvas id="FirstCanvas" width="416" height="256"> <p>Flag of Denmark</p> </canvas> </body> </html> What we've created resembles the flag of Denmark! There's more... This example may not seem overwhelming at first, but when you remember that we've created an image with hardly any HTML and no CSS whatsoever, the new canvas element starts to look pretty impressive. Any way you want it Note that while we used color names ("white" and "red") we could also use hexadecimal values or RGB or even HSL! Use whatever makes the most sense for you and your interactive project. Similar to tables? Think of the color and size specifications for this example almost as the old-school tables we used to build back in the day for layout. While certainly not the same, there are definitely similarities to that technique in this case. Be a square first Mastering rectangles is the first canvas technique that's important to have under your belt after the ability to set up the element itself. Understanding the basics of this approach will help you grasp the fundamentals of the next few recipes. Drawing borders for images using canvas Let's take a closer look at the super simple method of drawing borders around images using the new canvas element. How to do it... First, we'll start with our basic canvas code and add one new line to draw a border: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/ jquery.min.js"></script> <script> $(document).ready(function() { var canvas = document.getElementById("FirstCanvas"); var ctx = canvas.getContext("2d"); ctx.strokeRect(10, 20, 100, 100); }); </script> </head> <body> <canvas id="FirstCanvas" width="800" height="600"> <!-- Fallback code goes here --> </canvas> </body> </html> How it works... That one line of JavaScript tells the browser to create a rectangle starting at 10 pixels from the left and 20 pixels from the top of the new canvas element. It draws the box 100 pixels square. There's more... That's nice, but if we want the border to be any other color than the default, we'll need to specify that: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/ jquery.min.js"></script> <script> $(document).ready(function() { var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.strokeStyle = "rgb(0, 128, 0)"; ctx.strokeRect(10, 20, 100, 100); }); </script> </head> <body> <canvas id="myCanvas" width="600" height="600"> <!-- Fallback code goes here --> </canvas> </body> </html> In this case we've used strokeStyle to specify an RGB color of pure green. Style first If you plan to style a border, you'll need to specify that before the border is drawn by the browser. If you specify that style afterward, the browser will simply ignore it. Many color values work The style attribute we just used was RGB, but the method also works with colors ("green", for example), hexadecimal values, HSL, and RGBA. I like big borders and I cannot lie If no border width is specified, the browser will automatically draw a one-pixel border. Here's how to change that: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/ jquery.min.js"></script> <script> $(document).ready(function() { var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.lineWidth = 10; ctx.strokeStyle = "rgb(0, 128, 0)"; ctx.strokeRect(10, 20, 100, 100); }); </script> </head> <body> <canvas id="myCanvas" width="600" height="600"> <!-- Fallback code goes here --> </canvas> </body> </html> It's just this easy:  
Read more
  • 0
  • 0
  • 2484

article-image-installation-silverstripe-24
Packt
13 May 2011
11 min read
Save for later

Installation of SilverStripe 2.4

Packt
13 May 2011
11 min read
  SilverStripe 2.4 Module Extension, Themes, and Widgets: Beginner's Guide Create smashing SilverStripe applications by extending modules, creating themes, and adding widgets         Read more about this book       (For more resources on SilverStripe, see here.) Setting up the environment There are many possible scenarios and environments you might require, depending on the complexity of your project. However, we'll keep this short and simple: We'll set up a development environment, which is based on Windows (Windows XP or newer) as it is the most common operating system on desktops and laptops. We'll also set up one live or deployment environment, which is based on Linux as it is the most common operating system for web servers. We'll use Ubuntu in our example as it is freely available and widely used. If you prefer a different distribution some paths and commands will vary, but the general approach should be very similar. In case you want to use a testing or staging environment as well, we'll assume that you simply reuse the previous setup—so we don't need to configure another system. Now that we've decided on the general purpose of the systems and their operating systems, we'll need to choose between different implementations for setting up the web server and database. Specifically, whether to use prebuilt packages or select the components ourselves. To demonstrate both approaches we'll use a prebuilt package on our development machine (as we want to get up and running quickly) and handpick the components on our live site, where we want to have maximum control. To keep our development and live environments closely related, we'll use the same applications for both—disqualifying Windows-only solutions: For the web server we'll use the Apache HTTP Server (http://httpd.apache.org) as it's the most widely used, cross-platform server. Alternatives would be Microsoft's Internet Information Services (http://www.iis.net), which are only available on Windows, and Lighttpd (http://www.lighttpd.net) or Nginx (http://nginx.org), which are both fast, but not as widely used as the Apache web server, and are a little trickier to set up. For the database we'll use the popular MySQL (http://www.mysql.com). Alternatively you could use Microsoft SQL Server (https://www.microsoft.com/sqlserver/2008/en/us/default.aspx), which requires Windows; PostgreSQL (http://www.postgresql.org), SQLite (http://www.sqlite.org), or an Oracle database (http://www.oracle.com/us/products/database/index.html). However, each of these alternatives requires an additional SilverStripe module to support its specific SQL dialect, which generally receive less attention than MySQL. Unless you have a good reason for changing the database, like you're already using MS SQL for everything else, stick with MySQL. For a change the programming language PHP (http://www.php.net) doesn't require any decisions as there are no alternative implementations. For the prebuilt package we'll use XAMPP (http://www.apachefriends.org/en/xampp.html), which matches our requirements. It uses the Apache HTTP Server and MySQL and is available on Windows, Linux, Mac OS X, and Solaris. If your development machine doesn't use Windows, you should still be able to follow the installation steps with minor variations. On Windows there's also Microsoft's Web Platform Installer (http://www.microsoft.com/web/downloads/platform.aspx). It doesn't only include the web server, database and PHP, but also SilverStripe itself (http://www.microsoft.com/web/gallery/silverstripecms.aspx)—which can be downloaded on demand among many other web applications. However, as this is very different to our live site, we won't cover it. If you're looking for a, Windows-only solution this is nevertheless an interesting option as it is very easy to set up. The Windows development system Let's start off by setting up our development system, based on the freely available XAMPP package. Time for action - installing XAMPP We'll assume that the operating system is Windows XP or newer—for Linux, Mac OS X, and Solaris you should only need to get a different download file and do some minor variations of the steps described: Download the XAMPP package at http://www.apachefriends.org/en/xampp-windows.html. We're using the 7zip package as it doesn't require an installation, is compact to download and also portable: you can copy it to a USB drive and use the environment on any Windows computer. Extract the archive to a top-level folder on your internal drive (C: for example), or your portable external drive (U: for example). To do this, you'll need the free 7zip archive utility, which you can download at http://www.7-zip.org. Open up the file xampp/mysql/bin/my.ini and add the following line in the [mysqld] section: lower_case_table_names=2 This setting is important for exchanging database dumps between Windows and Linux systems. As Windows paths are case insensitive, MySQL lowercases database and table names by default (as they are internally stored as folders and files), but only on Windows. On Linux proper cases are preserved, which leads to problems when using dumps on different platforms. The previous statement forces MySQL on Windows to behave like on Linux. Inside the XAMPP folder, start the file xampp-control.exe and use it to Start Apache, MySql and Mercury. XAMPP's control panel should look like this after starting the three applications: If a service doesn't start, check that its port is not already in use—this is the main reason for problems. To do this, open the command line tool and enter netstat-ao. This will show you the ports currently in use and the process IDs (PIDs) of the processes using them. Using Window's Task-Manager you can then find out the name of the process causing the problem, and stop or reconfigure it. The following screenshot illustrates this scenario—the web server cannot be started as Skype is already using port 80: After successfully starting all three services, navigate to http://localhost in your browser. This should redirect you to XAMPP's welcome page. In case you need to send e-mails for testing purposes, you'll need to perform two additional steps to configure your SMTP server: Enable SMTP relaying of non-local mail. However, ensure that no one can access your mail server from outside or you might be abused as a spam relay (your router or firewall will protect you). In XAMPP's control panel, click on Admin... next to the Mercury label. Next go to Configuration, MercuryS SMTP Server and on the Connection control tab uncheck Do not permit SMTP relaying of non-local mail. Provide a DNS server so domain names can be looked up: Under Configuration, MercuryE SMTP Client fill in the field Name server with your provider's DNS server. That's it for our general purpose development machine. In case you want to run automatic tests or generate translation files, you'll also need to install PHPUnit through PEAR: While XAMPP includes PEAR and PHPUnit, the bundled versions are hopelessly outdated. Furthermore the update process doesn't work reliably, so we'll better start anew. First remove xampp/php/PEAR/, xampp/php/pear.bat, xampp/php/pear.ini, xampp/php/peardev.bat and xampp/php/pear-update.bat. Next enable PHP's cURL extension: Open xampp/php/php.ini, find the line ;extension=php_curl.dll and remove the leading semicolon. Then download http://pear.php.net/go-pear.phar into xampp/php/. Next install PEAR on the command line (start it as an admin user). Note that you must be in the folder xampp/php/ for the following commands to work: php go-pear.phar Now we can use PEAR to update its channels and upgrade all packages: pear update-channelspear upgrade --alldeps Finally you can install PHPUnit and all of its dependencies: pear channel-discover pear.phpunit.depear channel-discover components.ez.nopear channel-discover pear.symfony-project.compear install phpunit/PHPUnit That's it, you've successfully installed PHPUnit! The Linux live system Next we'll set up our live system. Thanks to package managers this isn't much harder—you just shouldn't be afraid of the shell. Time for action - installing the requirements by hand In our example we're using Ubuntu, so we'll rely on its package manager Apt, abbreviation of Advanced Package Tool. Note that we won't only install the bare necessities, but also some more tools to make our system ready for production. Open the terminal and install the Apache HTTP Server together with PHP and PHP's GD library (needed for image manipulation) through the following commands. Note that all required dependencies are added automatically, though you may need to manually accept them: sudo apt-get install apache2 php5 php5-gd Next we'll install MySQL and its binding to PHP, again through the terminal. You'll be prompted for a password, which we'll need again later on. sudo apt-get install mysql-server php5-mysql Enable Apache's rewrite module, which SilverStripe requires to use pretty URLs: sudo a2enmod rewrite Edit the file /etc/apache/sites-available/default and replace the line AllowOverride None with AllowOverride All inside the <Directory /var/www/> block. This enables the rewrite module inside the /var/www/ folder. Install Alternative PHP Cache (APC), which will accelerate PHP programs—SilverStripe benefits a lot from this. While there are some alternatives, it is currently planned that APC will be included in PHP 6, which makes it sound like a future-proof decision for our installation: sudo apt-get install php-apc If you want to see APC in action, you'll need its management tool. By default it is located in the file /usr/share/doc/php-apc/apc.php.gz. Unpack and copy it to your web-root to see detailed statistics on how well it's working for you, but protect it against unauthorized access (you can set credentials inside the file). Edit the file /etc/php5/apache2/php.ini, using whatever text-editor you prefer (this can be quite a sensitive topic with programmers). Replace the line ;date.timezone = with date.timezone = US/New_York or your current location. See http://php.net/manual/en/timezones.php for all possible values. Note that removing the semicolon at the beginning is important, otherwise the line will be considered a comment. Restart the web server to apply all the settings we've just made: sudo /etc/init.d/apache2 reload Now it's time to test our installation. Go to the directory /var/www/ which is the default web-root directory: cd /var/www/ It should already contain a file index.html, which you can view if you visit http://127.0.0.1 in your browser (or whichever IP address you can access your server under). However, this is only a static HTML file. To see if PHP is also working, first set the file permissions, assuming our current user is ubuntu (which we'll use to edit files) and the web server is run as www-data (which is the default). So we'll make our user the owner of the files with full permissions, and set the group to the one of the web server with read and execute permissions only: sudo chown ubuntu:www-data -R /var/www/sudo chmod 0755 -R /var/www/ After adding new files, you'll need to rerun these two commands. Next create a file index.php in /var/www/: touch index.php Add the following code to it: <?php phpinfo();?> In your browser load the page http://127.0.0.1/index.php (again use your specific IP address). The output should look something like this: This shows that PHP is working. Also check that you can find mod_rewrite and a full section on APC in the output to be sure they are enabled. That's it, our live system is now ready for action. We haven't installed PEAR as we'll assume that testing and translating is done in the development environment, not on the live server. We've also left out how to install and configure an SMTP server. Unfortunately this is pretty complicated and beyond the scope of this article—especially since you don't want to become a spam relay. If your provider or distribution hasn't already set this up for you, take a look at a specific SMTP server how-to and documentation—Postfix (http://www.postfix.org) is widely used for example.
Read more
  • 0
  • 0
  • 1452