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

How-To Tutorials - Server-Side Web Development

406 Articles
article-image-manage-your-money-simple-invoices
Packt
13 May 2010
6 min read
Save for later

Manage Your Money with Simple Invoices

Packt
13 May 2010
6 min read
As a freelancer I have one primitive motive. I want to do work and get paid. Getting paid means I need to generate invoices and keep track of them. I've tried to manage my invoices via spreadsheets and documents, but keeping track of my payments in a series of disconnected files is a fragile and inefficient process. Simple Invoices provides a solution to this. Simple Invoices is a relatively young project, and working with it requires that you're willing to do some manual configurations and tolerate the occasional problem. To work with and install the application, you need to be familiar with running a web server on OS X, Windows, or Linux. The next section, Web Server Required provides some out of the box server packages that allow you to run a server environment on your personal computer. It's point and click easy and perfect for an individual user. Not up for running a web server, but still need to find a reliable invoicing application? No problem. Visit www.simpleinvoices.com for a list of hosted solutions. Let's get started. Web Server Required Simple Invoices is a web application that requires Apache, PHP, and MySQL to function. Even if you're not a system administrator, you can still run a web server on your computer, regardless of your operating system. Windows users can get the required software by installing WAMP from www.wampserver.com. OS X users can install MAMP from www.mamp.info. Linux users can install Apache, MySql, and PHP5 using their distribution's software repositories. The database administrative tool, phpMyAdmin makes managing the MySQL database intuitive. Both the WAMP and MAMP installers contain phpMyAdmin, and we'll use it to setup our databases. Take a moment to setup your web server before continuing with the Simple Invoices installation. Install Simple Invoices Our first step will be to prepare the MySQL database. Open a web browser and navigate to http://localhost/phpmyadmin. Replace localhost with the actual server address. A login screen will display and will prompt you for a user name and password. Enter the the root login information for your MySQL install. MAMP users might try root for both the user name and password. WAMP users might try root with no password. If you plan on keeping your WAMP or MAMP servers installed, setting new root passwords for your MySQL database is a good idea, even if you do not allow external connections to your server. After you log in to phpMyAdmin, you will see a list of databases on the left sidebar; the main content window displays a set of tabs, including Databases, SQL, and Status. Let's create the database. Click on the Privileges tab to display a list of all users and associated access permissions. Find the Add a New User link and click on it. The Add New User page displays. Complete the following fields: User Name: enter simpleinvoices Host: select Local Password: specify a password for the user; then retype it in the field provided Database for User: select the Create database with same name and grant all privileges option Scroll to the bottom of the page and click the Go button. This procedure creates the database user and the database at the same time. If you wanted to use a database name that was different than the user name, then could have selected None for the Database for user configuration and added the database manually via the Databases tab in phpMyAdmin. If you prefer to work with MySQL directly, the SQL code for the steps we just ran is (the *** in the first line is the password): CREATE USER 'simpleinvoices'@'localhost' IDENTIFIED BY '***'; GRANT USAGE ON *.* TO 'simpleinvoices'@'localhost' IDENTIFIED BY '***' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;CREATE DATABASE IF NOT EXISTS `simpleinvoices`; GRANT ALL PRIVILEGES ON `simpleinvoices`.* TO 'simpleinvoices'@'localhost'; Now that the database is setup, let's download the stable version of Simple Invoices by visiting www.simpleinvoices.org and following the Download link. The versions are identified by the year and version. At the time of this writing, the stable version is 2010.1. Unzip the Simple Invoices download file into a subdirectory on your web server. Because I like to install a lot of software, I like to keep the application name in my directory structure, so my example installation installs to a directory named simpleinvoices. That makes my installation available at http://localhost/simpleinvoices. Pick a directory path that makes sense for you. Not sure where the root of your web server resides on your server? Here are some of the default locations for the various server environments: WAMP – C:wampwww MAMP – /Applications/MAMP/htdocs Linux – /var/www Linux users will need to set the ownership of the tmp directory to the web user and make the tmp directory writable. For an Ubuntu system, the appropriate commands are: chown -R www-data tmpchmod -R 775 tmp The command syntax assumes we're working from the Simple Invoices installation directory on the web server. The web user on Ubuntu and other Debian-based systems is www-data. The -R option in both commands applies the permissions to all sub-directories and files. With the chmod command, you are granting write access to the web user. If you have problems or feel like being less secure, you can reduce this step down to one command: chmod -R 777 tmp. We're almost ready to open the Simple Invoices installer, but before we go to the web browser, we need to define the database connections in the config/config.ini file. At a minimum, we need to specify the database.params.username and database.params.password with the values we used to setup the database. If you skip this step and try to open Simple Invoices in your web browser, you will receive an error message indicating that your config.ini settings are incorrect. The following screenshot shows the relevant settings in confi.ini. Now, we're ready to start Simple Invoices and step through the graphical installer. Open a web browser and navigate to your installation (for example: http://localhost/simpleinvoices). Step 1: Install Database will display in the browser. Review the database connection information and click the Install Database button. Step 2: Import essential data displays. Click the Install Essential Data button to advance the installation. Step 3: Import sample data displays. We can choose to import sample data or start using the application. The sample data contains a few example billers, customers, and invoices. We're going to set all that up from scratch, so I recommend you click the Start using Simple Invoices button. At this point the Simple Invoices dashboard displays with a yellow note that instructs us to configure a biller, a customer, and a product before we create our first invoice. See the following screenshot. You might notice that the default access to Simple Invoices is not protected by a username and password. We can force authentication by adding a user and password via the People > Users screen. Then set the authentication.enabled field in config.ini equal to true.
Read more
  • 0
  • 0
  • 3024

article-image-creating-your-first-complete-moodle-theme
Packt
11 May 2010
11 min read
Save for later

Creating your First Complete Moodle Theme

Packt
11 May 2010
11 min read
So let's crack on... Creating a new theme Finding a base theme to create your Moodle theme on is the first thing that you need to do.There are, however, various ways to do this; you can make a copy of the standard themeand rename it as you did in part of this article, or you can use a parent theme that isalso based on the standard theme. The important point here is that the standard theme that comes with Moodle is the cornerstone of the Moodle theming process. Every other Moodle theme should be based upon this theme, and would normally describe the differences from the standard theme. Although this method does work and is a simple way to get started with Moodle theming, it does cause problems as new features could get added to Moodle that might cause your theme to display or function incorrectly. The standard theme will always be updated before a new release of Moodle is launched. So if you do choose to make a copy of the standard theme and change its styles, it would be best to make sure that you use a parent theme as well. In this way, the parent theme will be your base theme along with the changes that you make to your copy of the standard theme. However, there is another way of creating your first theme, and that is to create a copy of a theme that is very close to the standard theme, such as standardwhite, and use this as your theme. Moodle will then use the standard theme as its base theme and apply any changes that you make to the standardwhite theme on the top (parent). All we are doing is describing the differences between the standard and the standardwhite themes. This is better because Moodle developers will sometimes make changes to the standard theme to be up-to-date with new Moodle features. This means that on each Moodle update, your standard theme, folder will be updated automatically, thus avoiding any nasty display problems being caused by Moodle updates. The way by which you configure Moodle themes is completely up to you. If you see a theme that is nearly what you want and there aren't really many changes needed, then using a parent theme makes sense, as most of the styles that you require have already been written. However, if you want to create a theme that is completely different from any other theme or wish to really get into Moodle theming, then using a copy of one of the standard sheets would be best. So let's get on and see what the differences are when using different theme setups, and see what effect these different methods have on the theming process. Time for action – copying the standard theme Browse to your theme folder in C:Program FilesApache Software FoundationApache 2.2htdocstheme. Copy the standard theme by right-clicking on the theme's folder and choosing Copy. Paste the copied theme into the theme directory (the same directory that you arecurrently in). Rename the copy of standard folder to blackandblue or any other name that you wish to choose (remember not to use capitals or spaces). Open your Moodle site and navigate to Site Administration Appearance | Themes | Theme Selector|, and choose the blackandblue theme that you have just created. Y ou might have noticed that the theme shown in the preceding screenshot has a header that says Black and Blue theme. This is because I have added this to the Full site name in the Front Page settings page. Time for action – setting a parent theme Open your web browser and navigate to your Moodle site and log in as the administrator. Go to Site Administration | Appearance | Themes | Theme Selector and choose your blackandblue theme if it is not already selected. Browse to the root of your blackandblue folder, right-click on the config.php file, and choose Open with | WordPad. You need to make four changes to this file so that you can use this theme and a parent theme while ensuring that you still use the default standard theme as your base. Here are the changes: $THEME->sheets = array('user_styles');$THEME->standardsheets = true;$THEME->parent = 'autumn';$THEME->parentsheets = array('styles'); Let's look at each of these statements, in turn. $THEME->sheets = array('user_styles'); This contains the names of all of the stylesheet files that you want to include in this for your blackandblue theme, namely user_styles. $THEME->standardsheets = true; This parameter is used to include the standard theme's stylesheets. If it is set to True, it will use all of the stylesheets in the standard theme. Alternatively, it can be set as an array in order to load individual stylesheets in whatever order is required. We have set this to True, so we will use all of the stylesheets of the standard theme. $THEME->parent = 'autumn'; This variable can be set to use a theme as the parent theme, which is included before the current theme. This will make it easier to make changes to another theme without having to change the actual files. $THEME->parentsheets = array('styles'); This variable can be used to choose either all of the parent theme's stylesheets or individual files. It has been set to include the styles.css file from the parent theme, namely autumn. Because there is only one stylesheet in the Autumn theme, you can set this variable to True. Either way, you will have the same outcome. Save themeblackandblueconfig.php, and refresh your web browser window. You should see something similar to the following screenshot. Note that your blocks may be different to the ones below, but you can ignore this. What just happened? Okay, so now you have a copy of the standard theme that uses the Autumn theme (by Patrick Malley) as its parent. You might have noticed that the header isn't correct and that the proper Autumn theme header isn't showing. Well, this is because you are essentially using the copy of the standard theme and that the header from this theme is the one that you see above. It's only the CSS files that are included in this hierarchy, so any HTML changes will not be seen until you edit your standard theme's header.html file. Have a go hero – choose another parent theme Go back and have a look through some of the themes on Moodle.org and download one that you like. Add this theme as a parent theme to your blackandblue theme's config.php file, but this time choose which stylesheets you want to use from that theme. The Back to School theme is a good one for this exercise, as its stylesheets are clearly labeled. So you Copying the header and footer files To show that you are using the Autumn theme's CSS files and the standard theme's HTML files, you can just go and copy the header.html and footer.html files from Patrick Malley's Autumn theme and paste them into your blackandblue theme's folder. Don't worry about overwriting your header and footer files, as you can always just copy them again from the ac tual standard theme folder. Time for action – copying the header.html and footer.html files Browse to the Autumn theme's folder and highlight both the header.html and footer.html files by holding down the Ctrl key and clicking on them both. Right-click on the selected files and choose Copy. Browse to your blackandblue theme's folder and right-click and choose Paste. Go back to your browser window and press the F5 button to refresh the page. You will now see the full Autumn theme. What just happened? You have copied the autumn theme's header.html and footer.html files into your blackandblue theme, so you can see the full autumn theme working. You probably will not actually use the header.html and footer.html files that you just copied, as this was just an example of how the Moodle theming process works. So you now have an unmodified copy of the standard theme called blackandblue, which is using the autumn theme as its parent theme. All you need to do now to make changes to this theme is to edit your CSS file in the blackandblue theme folder. Theme folder housework However, there are a couple of things that you need to do first, as you have an exact copy of the standard theme apart from the header.html and footer.html files. This copied folder has files that you do not need, as the only file that you set for your theme to use was the user_styles.css file in the config.php file earlier. This was the first change that you made: $THEME->sheets = array('user_styles'); The user_style.css file does not exist in your blackandblue theme's folder, so you will need to create it. You will also need to delete any other CSS files that are present, as your new blackandblue theme will use only one stylesheet, namely the user_styles.css file that you will be creating in the following sections. Time for action – creating our stylesheet Right-click anywhere in your blackandblue folder and choose New Text Document|. Rename this text document to user_styles.css by right-clicking again and choosing Rename. Time for action – deleting CSS files that we don't need Delete the following CSS files by selecting them and then right-clicking on the selected files and choosing Delete. styles_color.css styles_ie6.css styles_ie6.css styles_ie7.css styles_layout.css styles_moz.css {background: #000000;} What just happened? In the last two tasks, you created an empty CSS file called user_style.css in your blackandblue theme's folder. You then deleted all of the CSS files in your blackandblue theme's folder, as you will no longer need them. Remember, these are just copies of the CSS files in the standard theme folder and you have set your theme to use the standard theme as its base in the blackandblue theme's config.php file. Let's make some changes Now you have set up your theme the way that you want it, that is, you are using your own blackandblue theme by using the standard theme as a base and the Autumn theme as the parent. Move on and make a few changes to your user_style.css file so that you can see what effect this has on your theme, and check that all of your config.php file's settings are correct. Remember that all of the current styles are being inherited from the Autumn theme. Time for action – checking our setup Open up your Moodle site with the current theme (which should be blackandblue but looks like the Autumn theme). Navigate to your blackandblue theme's folder, right-click on the user_style.css file, and choose Open. This file should be completely blank. Type in the following line of CSS for the body element, and then save the fi le: body {background: #000000;} Now refresh your browser window. You will see that the background is now black. Note: When using Firebug to identify styles that are being used, it might not always be obvious where they are or which style is controlling that element of the page. An example of this is the body {background: #000000;}code that we just pasted in our user_style.css file. If we had used Firebug to indentify that style, we would not have found it. Instead, I just took a look at the CSS file from the autumn theme. What I am trying to say here is that there will always be an element of poking around and trial and error. What just happened? All seems fine there, doesn't it? You have added one style declaration to your empty user_style.css file to change the background color, and have checked the changes in your browser. You now know how the parent themes work and know that you only need to copy the styles from Firebug into your user_style.css file and edit the style declarations that need to be changed.
Read more
  • 0
  • 1
  • 8476

article-image-creating-and-modifying-filters-moodle-19
Packt
06 May 2010
6 min read
Save for later

Creating and Modifying Filters in Moodle 1.9

Packt
06 May 2010
6 min read
Moodle filters modify content from the database as it is output to the screen, thus adding function to the display. An example of this is the multimedia filter, which can detect references to video and audio files, and can replace them with a "mini-player" embedded in the content. How a filter works Before trying to build a filter, it would help to understand how it works. To begin with, any text written to the screen in Moodle should be processed through the format_text function. The purpose of this function is to process the text, such that it is always safe to be displayed. This means making sure there are no security issues and that any HTML used contains only allowed tags. Additionally, the output is run through the filter_text function, and this is the function we are interested in. This function takes the text destined for the screen, and applies all enabled filters to it. The resulting text will be the result of all of these filters. filter_text applies each enabled filter to the text in the order defined in the filter configuration screen (shown in the following screenshot). The order is important; each filter will be fed the output of the previous filter's text. So it is always possible that one filter may change the text in a way that impacts the next filter. Building a filter Now it's time to build our own filter. To begin with, let's come up with a requirement. Let's assume that our organization, called "Learning is Fun", has a main website at http://2fun2learn.org. Now, we need any instance of the phrase learning is fun to be hyperlinked to the website URL every time it appears on the screen, as in the forum post shown in the following screenshots: We can do this by implementing a policy with our content creators that forces them to create hyperlink tags around the phrase every time they write it. However, this will be difficult to enforce and will be fraught with errors. Instead, wouldn't it be easier if the system itself could recognize the phrase and create the hyperlink for us? That's what our filter will do. Getting started We need a name for our filter. It is the name that will be used for the directory the filter will reside in. We want a name that will describe what our filter does and will be unlikely to conflict with any other filter name. Let's call it "learningisfunlink". To start with, create a new subdirectory in the /filter directory and call it learningisfunlink. Next, create a new file called filter.php. This is the only file required for a filter. Open the new filter.php file in your development environment. The filter only requires one function, which is named after the filter name and suffixed with _filter. Add the PHP open and close tags (<?php and ?>), and an empty function called learningisfunlink_filter that takes two arguments: a course ID and the text to filter. When completed, you should have a file that looks like this: <?phpfunction learningisfunlink_filter($courseid, $text) {return $text;}?> We now have the bare minimum required for the filter to be recognized by the system. It doesn't do what we want yet, but it will be present. Creating the language file Log in to the site (that makes use of your new filter) as an administrator. On the main page of your site, look for the Modules Filters| folder in the Site Administration block. Click on the Manage filters link. If you have the default filter setup, you will see your new filter near the bottom of the list, called Learningisfunlink, as shown in the following screenshot: Now, even though the name is reasonably descriptive, it will be better if it were a phrase similar to the others in the list; something like Main website link. To do this, we need to create a new directory in our /filter/learningisfunlink directory called lang/en_utf8/ (the en_utf8 is the language specific part—English in this case). In this directory, we create a new file called filter_learningisfunlink.php. This name is the concatenation of the phrase filter_ and the name of our filter. In this file, we need to add the following line: $string['filtername'] = "Main website link"; This language string defines the text that will be displayed as the name of our filter, replacing the phrase Learningisfunlink that we saw earlier with Main website link. This file will contain any other strings that we may output to the screen, specifically for this filter. Once we have created this file, returning to the Manage filters page should now show our filter with the name that we provided for it in our language file. Creating the filter code We now have a filter that is recognized by the system and that displays the name we want it to. However, we haven't made it do anything. Let's create the code to add some functionality. Remember, what we want this filter to do is to search the text and add a hyperlink pointing to our website for all occurrences of the phrase "learning is fun". We could simply perform a search and replace function on the text and return it, and that would be perfectly valid. However, for the sake of learning more about the Moodle API, we'll use some functions that are set up specifically for filters. To that end, we'll look at two code constructs: the filterobject class and the filter_phrases function, both of which are contained in the /lib/filterlib.php file. The filterobject class defines an object that contains all of the information required by the filter_phrases function to change the text to the way the filter wants it to be. It contains the phrase to be filtered, the tag to start the replacement with, the tag to end the replacement with, whether to match case, whether a full match is required, and any replacement text for the match. An array of filterobjects is sent to the filter_phrases function, along with the text to search in. It's intended to be used when you have a number of phrases and replacements to apply at one time, but we'll use it anyway. Let's initialize our filter strings: $searchphrase = "learning is fun";$starttag = "<a href="http://2fun2learn.org">";$endtag = "</a>"; Now, let's create our filterobject: $filterobjects = array();$filterobjects[] = new filterobject($searchphrase, $starttag, $endtag); Lastly, let's pass the structure to the filter_phrases function, along with the text to be filtered: $text = filter_phrases($text, $filterobjects); Our function now has the code to change any occurrence of the phrase "learning is fun" to a hyperlinked phrase. Let's go test it
Read more
  • 0
  • 0
  • 2576

article-image-moodle-19-theme-design-customizing-header-and-footer-part-1
Packt
23 Apr 2010
7 min read
Save for later

Moodle 1.9 Theme Design: Customizing the Header and Footer (Part 1)

Packt
23 Apr 2010
7 min read
So, let's get on with it... Important preliminary points In order to continue with the exercises in the article, you will need to understand the importance of web browser compatibility. All web browsers are different, and most of them handle HTML and Cascading Style Sheets (CSS) differently. It is not so much that one web browser is better than another or that one web browser is more accurate at rendering HTML or CSS. Rather, it's that CSS rules are often interpreted differently by software developers who designed these browsers. For web developers and designers, this can be very annoying, but an unfortunate and inevitable reality. So, to make sure that the changes that you make to Moodle's theme files are the same or similar across most of the major web browsers, you will need to install various web browsers, such as Firefox, Internet Explorer, Chrome, Opera, Safari, and so on, and make sure that you remember to test your changes. You shall learn to install the required web browsers as you work through this article. Customizing the header One of the first tasks that you will be asked to do concerning Moodle theming is to customize the main Moodle header file. Most people start by learning to change the Moodle logo for one of their own. The file that you will be editing in the first part of this article is the header.html file. For this article, you will assume the standard theme that comes with Moodle. Time for action – making a copy of the standard theme In this exercise, you will be making a copy of the standard theme so that you can make changes to it without interfering with Moodle's theming process. You need to do this because many of the Moodle themes use the standard theme as the base theme. Navigate to the folder: C:Program FilesApache Software FoundationApache 2.2htdocstheme. Right-click on the standard theme folder and choose Copy, as seen in the following screenshot: Right-click again in some empty space and choose Paste. The copied standard theme will be replicated and have the name Copy of standard, as seen below: Right-click on this folder and choose Rename to rename the folder to mytheme. What just happened? You have just made a copy of the standard theme that comes with Moodle and have relocated and renamed the theme, so you can now make some basic changes without interfering with any other themes in the theme directory. Most themes use the standard theme as the parent theme and then build upon this styled theme. So, if you were to change this theme directly, you would probably mess up most of the themes that are installed in your Moodle site. Adding your own logo Now that you have made a copy of the standard theme, you will go on and replace the Moodle logo with your own. Most oft en, your organization will have a logo that you can use; perhaps you could just copy one from their website. An important point to note here is that the logo that you use should be in the GIF or .png format. The following figure has been created with Adobe Photoshop to demonstrate that it would be best to create a very basic logo if you don't have one. Time for action – copying your logo to your mytheme directory Navigate to the location of your logo. Right-click and choose Copy. Navigate to your Moodle site's thememythemepix directory, right-click, and choose Paste. The result should resemble the following screenshot: What just happened? In this very simple exercise, you have copied the logo that you had or created and placed it in the correct directory in your new mytheme directory. This is now ready for you to use in the header.html file to display your logo. Now you will edit the main header.html file to include your new logo. The header.html file can be found in your site's thememytheme directory. Time for action – adding the logo code to your header.html file Navigate to your mytheme directory, right-click on the header.html file, and choose Open With | WordPad. Open the header.html file with your favorite text editor (WordPad, Notepad, Vim, and so on). As a Windows shortcut, you can right-click on the header.html file and choose Open With | WordPad, as seen below: Top Tip – Text editorsWe have chosen WordPad here as it retains the original markup format. Notepad, on the other hand, can be difficult to use, as it lacks some of the functionalities of WordPad. If you already use another text or HTML editor, then please use it. It's about familiarity here, so it's always best to use that with which you feel comfortable. Find the following lines of code: <?php print_container_start(true, '', 'header-home'); ?> <h1 class="headermain"><?php echo $heading ?></h1> <div class="headermenu"><?php echo $menu ?></div><?php print_container_end(); ?> Insert the following line of code: <img src="<?php echo $CFG->themewww .'/'. current_theme() ?>/pix/logo.gif" alt="Institutions Logo" /> Immediately after: <h1 class="headermain"> As shown here: <?php print_container_start(true, '', 'header-home'); ?> <h1 class="headermain"> <img src="<?php echo $CFG->themewww .'/'. current_theme() ?>/pix/logo.gif" alt="Institutions Logo" /> <?php echo $heading ?></h1> <div class="headermenu"><?php echo $menu ?></div><?php print_container_end(); ?> You can download this code from the Packt website. Save and close header.html. Open your web browser and type in the URL of your local Moodle site. Change the current theme, which should be Autumn, to your theme by navigating to Appearance | Themes | Theme Selector and choosing mytheme. You should see something similar to the following screenshot but with your own logo. What just happened? In this exercise, we have learned where a theme's header.html file is and how to open the header.html file for editing. We also learned what part of the code we should change in order to have our own logo appear on the front page of out Moodle site. Have a go hero – adding another logo Again, it's time for you to have a go yourself at changing and modifying some of the things that you have learned through this article. First, it would be a good idea if you would try to create a new logo and add it to the header.html file in your mytheme folder. This time leave the inner page header as it is. Top Tip – Two headersDuring this exercise, you may have noticed that the header.html file has two instances of the following line of code: <h1 class="headermain">. This is because Moodle loads a slightly different header depending on whether you are on the front page or any other page within the site. This means that the changes we have made will only be visible on the front page and not on any other page at the moment. Why don't you go and check this by opening your local Moodle site and clicking on the Logout link in the top right-hand corner and then clicking the Login link in the same place? This will take you to the login front page of Moodle and you will notice that your logo isn't where it is supposed to be. In most situations, we would want to have our logo on all pages within our Moodle site, so we will have to replicate the last exercise and paste our logo code in the other instance of <h1 class="headermain">.
Read more
  • 0
  • 0
  • 2066

article-image-moodle-19-theme-design-customizing-header-and-footer-part-2
Packt
23 Apr 2010
6 min read
Save for later

Moodle 1.9 Theme Design: Customizing the Header and Footer (Part 2)

Packt
23 Apr 2010
6 min read
Customizing the footer Obviously, the second thing that we are going to do after we have made changes to our Moodle header file is to carry on and change the footer.html file. The following tasks will be slightly easier than changing the header logo and title text within our Moodle site, as there is much less code and subsequently much less to change. Removing the Moodle logo The first thing that we will notice about the footer in Moodle is that it has the Moodle logo on the front page of your Moodle site and a Home button on all other pages. In addition to this, there is the login info text that shows who is logged in and a link to log out. More often than not Moodle themers will want to remove the Moodle logo so that they can give their Moodle site its own branding. So let's get stuck in with the next exercise, but don't forget that this logo credits the Moodle community. Time for action – deleting the Moodle logo Navigate to your mytheme directory and right-click on the footer.html file and choose Open With | WordPad. Find the following two lines of code: echo $loggedinas;echo $homelink; Comment out the second line using a PHP comment: echo $loggedinas;/*echo $homelink; */ Save the footer.html file and refresh your browser window. You should now see the footer without the Moodle logo. What just happened? In this exercise, we learned which parts of the PHP code in the footer.html file control where the Moodle logo appears in the Moodle footer. We also learned how to comment out the PHP code that controls the rendering of the Moodle logo so that it does not appear. You could try to put the Moodle logo back if you want. Removing the login info text and link Now that we have removed the Moodle logo, which of course is completely up to you, you might also want to remove the login info link. This link is used exactly like the one in the top right-hand corner of your Moodle site, insofar as it acts as a place where you can log in and log out and provide details of who you logged in as. The only thing to consider here is that if you decide to remove the login info link from the header.html file and also remove it from the footer, you will have no easy way of logging in or out of Moodle. So it is always wise to leave it either in the header or the footer. You might also consider the advantages of having this here as some Moodle pages such as large courses are very long. So, once the user has scrolled way down the page, he/she has a place to log out if needed. The following task is very simple and will require you to go through similar steps as the"deleting the logo" exercise. The only difference is that you will comment out a different line of code. Time for action – deleting the login info text Navigate to your mytheme directory and right-click on the footer.html file and choose Open With | WordPad (or an editor of your choice). Find the following two lines of code: echo $loggedinas;echo $homelink; Comment out the first line by using a PHP comment as shown below: /* echo $loggedinas; */ echo $homelink; Save the footer.html file and refresh your browser window. You will see the footer without the Moodle logo or the login info link. What just happened? In this task, we learned about those parts of the PHP code in the footer.html that control whether the Moodle login info text appears in the Moodle footer similar to the Moodle logo in the previous exercise. We also learned how to comment out the code that controls the rendering of the login info text so that it does not appear. Have a go hero – adding your own copyright or footer text The next thing that we are going to do in this article is to add some custom footer text where the Moodle logo and the login info text were before we removed them. It's completely up to you what to add in the next exercises. If you would like to just add some text to the footer then please do. However, as part of the following tasks we are going to add some copyright text and format it using some very basic HTML. Time for action – adding your own footer text Navigate to your mytheme directory and right-click on the footer.html file and choose Open With | WordPad. At the very top of the file, paste the following text or choose your own footer text to include: My School © 2009/10 All rights reserved. Save the footer.html and refresh your browser. You will see that your footer text is at the bottom of the page on the right-hand side. However, this text is aligned to the left as all text in a browser would be. Open the footer.html file again (if it isn't open already) and wrap the following code around the footer text that you have just added: <div align="right">My School &copy; 2009/10 All rights reserved</div> Save your footer.html file and refresh your browser. You will see that the text is now aligned to the right. What just happened? We just added some very basic footer text to our footer.html file, saved it, and viewed it in our web browser. We have demonstrated here that it is very easy to add our own text to the footer.html file. We have also added some basic HTML formatting to move the text from the left to the right-hand side of the footer. There are other ways to do so, which involve the use of CSS. For instance, we could have given the <div> tag a CSS class and used a CSS selector to align the text to the right. Have a go hero – adding your own footer logo Now try to see if you can edit the footer.html and add the same logo as you have in the header.html in to the footer. Remember that you can put the logo code anywhere outside of a PHP code block. So try to copy the header logo code and paste it into the footer.html. Finally, based on what we have learned, try to align the logo to the right as we did with the footer text.
Read more
  • 0
  • 0
  • 3390

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

Managing Data in MySQL

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

Configuring MySQL

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

article-image-using-moodle-integrate-foreign-language-course-secondary-school
Guest Contributor
18 Mar 2010
11 min read
Save for later

Using Moodle to integrate a Foreign Language Course in Secondary School

Guest Contributor
18 Mar 2010
11 min read
This article is written by Mariella Proietta. Introduction: technology and the learning process Researchers and practitioners, both agree on the essential role played by technology in the learning process. Yet the discussion on the changes brought about by the adoption of ICT is still controversial. An emerging topic is the importance of technology in motivating students. Academic motivation is a critical need to address, especially in high school education, since motivational features change and can significantly influence the engagement, learning, achievement, and future aspirations and intentions of students (Deci and Ryan 1985; Hardré and Reeve 2003; Pintrich and Schunk 1996). Motivation is a result of interaction between external and internal factors. It depends on individual differences, influence of outside experiences, and from interactions with teachers and peers in school. Different studies have shown the use of technological tools to increase motivation and Computer Assisted Learning (CAL) has been encouraged and developed in every field. The use of Computer Assisted Language Learning (CALL) has produced a great deal of literature from perspectives such as cognitive psychology, constructivism, psycholinguistics and has undertaken different phases from behaviouristic to integrative or integrated. Bax (2003) talks about approaches from restricted CALL, open CALL to integrated CALL. He describes them concluding that teachers’ aim should be to attain a state of 'normalisation' in which the technology is invisible and truly integrated. The expectation that teachers would adopt ICT and change their practices in particular ways has been recently questioned by research which indicates that teachers have not changed in the ways expected and researchers try to understand why. J. Orlando(2009) explores the existing literature on the matter stating that effective practices include frequency of use for knowledge construction, using ICT to enhance teaching efficiency and to extend and transform learning teachers’ practices. She notes that there is a common assumption that teachers move along and complete a determined path of change caused by the ‘techno-centric’ expectation of immediacy of change in their practices as a result of the use of ICT. She proposes a different design considering research as an evolving process, fashioned over the course of the study. This change may produce new data. But the change with ICT is distinctive and complex mainly because ICT resource innovations are continuously and rapidly changing. A new perspective helps to understand how and why changes in teaching practices mediated by ICT occur and contribute to understand the phenomenon of ICT and the impact it is having on teaching practices. Improvement and integration of the learning process in foreign language teaching Recent studies explore the increasing role of educational activities outside the classroom in the teaching and learning of foreign languages by means of hybrid learning arrangements and the integration of e-learning with classical classroom instruction. Bärenfänger (2005) explores the studies on the subject and introduces the elements of resulting pedagogic arrangements such as online references, asynchronous web-based learning, email, online assessment and testing, mentoring and tutoring. The study includes portals, synchronous web-based learning, electronic performance support systems, simulations, knowledge management, self-paced CD-ROM based content, communities of practice, video broadcasts, virtual labs and chat rooms. The author notes that these new tools satisfy the needs of learners, improve the quality of the learning experience, decrease the time a learner needs to achieve a learning goal, improve quality of the learning content and materials, improve re-usability of the learning content and materials. Among the advantages these tools also reduce cost of program delivery, allow a more effective map learning components to objectives and reduce cost of program development. Other studies have shown that distant or blended courses do not interfere with oral proficiency and interaction. According to Blake and others ‘many teachers still harbour deep-seated doubts as to whether or not a hybrid course, much less a completely distance-learning class, could provide L2 learners with a way to reach linguistic proficiency, especially with respect to oral language skills’ (Blake et al., 2008). In their study, they show that classroom, hybrid, and distance L2 learners reach comparable levels of oral proficiency during their first year of study. The Italian context In most Italian secondary schools the language course takes place mainly in the classroom (often three hours a week) with students having the opportunity to practice the four skills in a more conventional way. Some schools offer additional hours in which students are asked to work in the school multimedia laboratory, and integrate their language abilities with ICT. The majority of Italian secondary school students have, at home, a personal computer and an easy access to the web, but most of their time is spent chatting in their mother tongue and using a social network. When they are asked to visit foreign websites, find information in English or other foreign languages, do online language practice or similar activities, only a few of them are capable to accomplish the task, while the remaining students want to do the activities at school under the supervision of the teacher. The result is that most of the time is spent doing, at schools, activities that could be easily done at home. Moreover, very few students write and speak in English to communicate, apart from the simulations during the lesson, and their listening practice is mainly with songs. The procedure planned here tries to solve these problems and aims to improve and integrate the learning process with online activities. Using the platform Moodle to integrate the textbook Second language teachers can find a help to create engaging online language learning activities using the Moodle platform in different web sites, and a recent book has been written by J. Stanford for teachers, trainers, and course planners, with little or no experience of Moodle, who want to create their own language learning activities (Stanford 2009). It offers plenty of suggestions and examples for adapting classroom activities to the virtual learning environment and the author has also created a demo site http://moodleforlanguages.co.uk). What we are trying here is slightly different: we try to use the platform Moodle to support and integrate conventional class language activities. Creating learning tasks with Moodle The tools provided by Moodle can be used to integrate any level course, provide additional work outside the class and experience cooperative learning. According to Brandl ‘as a courseware package and learning System, Moodle has great potential for supporting conventional classroom instruction, for example, to do additional work outside of class, to become the delivery System for blended (or hybrid) course formats, or even to be used as a standalone e-learning platform’ (Brandl, 2005). Moodle and its platform can thus be used to integrate the school course, inviting the students to join the modules and try the new experience. They can be asked by the teacher to attend the platform and receive credits or marks, which will contribute to the end-of-year evaluation. The result of this kind of experience may contribute to support the use of new technologies in secondary schools, and increase foreign language proficiency. Preparing the platform Teachers or instructors should first prepare the platform and its parts before starting the activities, caring that each language skill could be exploited, and then they could invite their students to join the integration course. As regards language learning, among the different features, the quiz-making function has been analysed and used by many instructors and authors. Robb states that Moodle's functions ‘allow you to make different types of quizzes. Quiz types relevant to language teaching are: Multiple choice, True/False, Numerical, Matching, Description, and Cloze. A wide range of options allows you to randomize the questions and multiple-choice items, specify a time frame for availability, choose whether the students receive feedback or not, decide if they are allowed to view the correct answers, and determine how many times they may take the quiz and how it is to be scored (first attempt, highest attempt, average of all attempts or last attempt)’ (Robb, 2004). Planning the procedure Since the intention is not to substitute the textbooks, CDs or CD ROM, but to integrate them with an e-learning environment, the following steps may be followed, to create the module or sections in the platform and provide the interaction needed: The teacher chooses some Units of the textbook (or textbooks) that can be more easily considered as Learning Objects (modular digital resources that are uniquely identified and can be used and reused to support learning. The main idea of 'learning objects' is that educational content is broken down into small chunks that can be reused in various learning environments). Some of the audio material (tracks) on CDs can be saved as audio files in a directory to be used as a resource. Short video sequences can offer dialogues corresponding to the units chosen. Many sites such as the site of the BBC http://www.bbc.co.uk/worldservice/learningenglish and other sites ( e.g. http://www.lingual.net/lingualproductitems/details.php) provide this sort of video material that can be linked or downloaded from the platform. Additional audio material should be prepared, such as listening exercises, whose solutions and answers could be sent via e-mail to the teacher for correction or recorded by the students and put in an area of the platform where other students could access for listening and discussion in a chat room. A particular section of Moodle offers the opportunity to create quizzes of different kinds. Instructors and teachers who are familiar with ‘Macromedia Flash’ or similar programs can also produce interactive web pages with exercises such as drag and drop or true or false. Otherwise, each section could have some links to web sites with plenty of exercises. The teacher has only to take care that there is a great deal of interaction and feedback. Evaluation may be done through different kinds of tests. At the end of each test a mark or score can be given to each student, and added to the general evaluation in the subject. An additional mark may be given to the frequency with which students attend the platform and the areas in which they can swap information. To illustrate the procedure we have created a module choosing some of the contents of Horizons Options pre­intermediate used in Italian secondary schools mostly in the second or third year. The first approach, after the login and the choice of course, may be with a chart similar to figure 1 that can be put in the main frame: The access to each Section can be done either independently or in sequence in the sense that Section 2 can be opened only after having done the main activities in Section 1. The ‘i’ on the right provides general information about the content of the Section. By clicking on one of the titles of the sections, e.g. Clothes and fashion you can open either a frame or a new window similar to the following (figure 2): The exercises provided are mostly interactive and they can be scored independently. A particular area of the platform may be used as a kind of forum where the students write their doubts and the teacher gives explanation. They can also be encouraged to suggest the solution to the questions asked by others. Another area may be used to chat freely in the foreign language. To avoid the unbalance between oral and written skills, particular care should be taken in using tools that allow the recording of the voice and the oral communication. Students could be asked to telephone and record their call or interview a friend and put the recording on the platform. Conclusion The ideas provided in this article are only the starting point for the acquisition of a deeper competence in the use of Moodle for language learning. The choice of the Italian context is influenced by the ongoing experimentation of Moodle in Italian secondary schools, but many suggestions can come only after having used the package and the Learning System for a long time. We should reach what Bax calls normalisation referring ‘to the stage when the technology becomes invisible, embedded in everyday practice and hence ‘normalised’. To take some commonplace examples, a wristwatch, a pen, shoes, and writing - these are all technologies which have become normalised to the extent that we hardly even recognise them as technologies’ (Bax, 2003). What is important, at the moment, is starting to explore new ways of teaching and keeping alive students' interest and motivation using their means of communication.
Read more
  • 0
  • 0
  • 3903

article-image-instructional-material-using-moodle-19-part-1
Packt
29 Jan 2010
8 min read
Save for later

Instructional Material using Moodle 1.9: Part 1

Packt
29 Jan 2010
8 min read
Selecting and organizing the material If you're like most instructors, you love your subject and the idea of sharing information gives you great satisfaction. However, you have probably noticed that it's easy to overload your students, or to give them materials in a way that tends to confuse them. How can you avoid overloading and confusing your students? One of the most effective ways to do so is to make sure that you base your selections of instructional materials on course outcomes and on the learning objectives for each unit. Keep in mind what you'd like your students to be able to do after they complete the course. What is the basic, enduring knowledge they will take with them after the course is over? What kind of fundamental change do you want to occur in terms of the student's abilities? What kind of new skills will they be able to perform? Once you answer these questions, you will have a list of learning outcomes. Keep them in mind as you select the instructional material you wish to use in your course. It is often convenient to develop a map or a diagram that connects your learning outcomes with the course materials and the assessments you will use. Consider what you want your students to learn, and how you'd like them to perform. Also, you shape the sequence you will build and how you'll present the materials. It is often convenient to develop a map or a diagram that connects your learning outcomes with the course materials and the assessments you will use. Consider what you want your students to learn, and how you'd like them to perform. Also, you shape the sequence you will build and how you'll present the materials. Using forums to present your material We'll start with an approach that is very easy to implement, which is ideal if you're just getting started and need a solution that would be good for all kinds of e-learning, including mobile learning and guided independent study. Basically, we'll use the Forum tool to organize all the instructional content. In Moodle, the Forum is the key tool and you'll use it often. Later, as you feel more comfortable, you can add more tools (Book, Chat, Assignment, Choice, and so on). For now, however, we will focus on getting you operational as quickly and easily as possible. Using the Forum tool to structure your course and to organize your content is conceptually very elegant. Students simply move from forum to forum, and they access the material they need. Any comments they have, writing assignments, or discussion items can be completed in the appropriate thread. When you use the Forum tool, you will use the Moodle text editor to create messages. Keep in mind that your messages can contain text, graphics, audio, video, presentations, and more, which allows you flexibility and ease of use. As you plan your course, it's always good to have a certain number of forums dedicated to student success and support. This is where you can post welcome messages, timelines and course calendars, lists of assignments, syllabus, links to useful resources, and a place for students to ask questions and share their experiences. A key student success forum is one that clearly states what you hope to achieve in the course. By listing course outcomes in a separate forum, you'll shape the students' approach to the course content, and they will have a better idea of how to organize the information they will encounter. After you've developed your "student success and support" forums, you start creating a separate forum for each unit, which begins to identify the learning objectives, and the resources you'll put in each one to create a learning environment. It is often a good idea to create a separate forum for each graded assessment. Having a separate forum for each assessment will make your job easier if you have changes to make, or if you want to replace it with an assignment tool. In fact, by populating your course with a series of separate forums, you are creating a flexible template that can be easily modified by replacing a forum with another, or with a different type of tool (Choice, Assignment, Chat, Database, Book, Journal, or more). It is often helpful to create a course map wherein you draw all the elements you'll have in your course. List the course outcomes, and then map each one to the instructional material, activities, and assessments that go with each one. This will help you as you start building your forums. Here is an example of how you can put together a course in which you organize the content around forums: Forum 1: Welcome and Course Overview and Objectives Forum 2: Meet Your Instructor Forum 3: Introduce Yourself Forum 4: Questions for the Instructor Forum 5: Syllabus and Timeline Forum 6: Unit 1: Unit Learning Objectives, Instructional Materials, and Discussion Questions Forum 7: Unit 1: Review for Quiz Forum 8: Unit 1: Quiz Forum 9: Unit 1: Instructional Materials and Discussion Questions As you can see, the structure is very straightforward and avoids the complexity of multiple tools. Keep in mind that more complex tools can always be added later to replace a forum structure. Creating a separate group for each student Start by selecting the activity tool, Forum, and opening a page that requires you to indicate the settings for the forum you wish to add. Remember that each group will consist of only a single student. So, in this process, when we discuss groups, we're really talking about individuals. The following steps illustrate how to create a separate forum for each group in your course: From the Add an activity… drop-down list, select Forum, as shown in the following screenshot: Enter a Forum name and Forum type for the forum. In the following example, I'm using A single simple discussion to create a single-topic forum, where all the postings will be displayed on the same page. This makes the history of the student-teacher discussion very easy to see. This type of forum is most useful for short, focused discussions. By selecting Yes, forever for Force everyone to be subscribed? as shown in the following screenshot, you ensure that all students are subscribed automatically, even students that enroll at a later time. The key setting here is Group mode. When we select Separate groups, we create a separate forum for each group in the class. In the next section, we will create a group for each student. The result is a separate forum for each student, available only to that student and the teacher, where they can hold private conversation. Save the forum settings and continue. Enrolling students If you have not already enrolled students in the course, you should do so before creating the groups. If the students are already enrolled, move to Create a Group for Each Student in the next section. The following steps illustrate how to manually enroll students in your course: Open the course into which you want to enroll the students. Then, from the Administration drop-down box, select Assign roles as shown in the following screenshot: On the Assign roles page select Student, as shown in the following screenshot: Ensure the Role to assign drop-down list is set to Student. Then from the list of potential users on the right, select one user. Click the left-facing arrow to enrol that user in your course (refer to the following screenshot): Repeat this for each student. If you want to remove a student from the course, select the student from the list on the left, and click the right-facing arrow. To exit this page, select the course name from the navigation breadcrumbs at the top of the page. This will put you back into your course's home page, and then you can continue with creating a group for each student. Creating a group for each student After all of your students are enrolled, go into the course and create a group for each student. The following steps illustrate how to create groups and assign students to them: From the Administration block select Groups, as shown in the following screenshot: From the Current role drop-down list as shown in the following screenshot, select Student. This ensures that you are seeing only users who are enrolled as students in this course. Then, in the field above the Add new group button, enter the name of the first group. Name the group after the student for whom you created it. In this example, I created a group for Moodle Student1 called Student1, and I am about to create a group for Moodle Student2 called Student2. After creating all of the groups, add one student to each group. In the following example, you can see that the group Student1 is selected, and Moodle Student1 is a member of that group. Select the group. In the preceding example, you can see the user is about to select the group Student2. Select the student to add to the group. Click the Add selected to group button. Repeat as needed. To assign a student to a group:   To exit this page, select the course name from the navigation breadcrumbs at the top of the page. This will put you back into your course's home page. The student's private forum will look like any other Moodle forum. However, only the student and teacher will have access to it.
Read more
  • 0
  • 0
  • 1214

article-image-instructional-material-using-moodle-19-part-2
Packt
29 Jan 2010
6 min read
Save for later

Instructional Material using Moodle 1.9: Part 2

Packt
29 Jan 2010
6 min read
Keeping discussions on track One of the biggest challenges in using forums for an online class is keeping discussions focused on the topic. This becomes even more difficult when you allow students to create new topics in a forum. Moodle offers two tools that you can use to help keep discussions on track—custom scales and splitting discussions. Use a custom scale to rate relevance Moodle enables you to use a scale to rate student's work. A scale offers you something other than a grade to give the student as feedback. Scales can be used to rate forum postings, assignment submissions, and glossary entries. The following screenshot shows a feedback on the relevance of a posting, given in a custom scale by a teacher: To create and apply a custom scale, follow these steps: Users with the roles Administrator, Course creator, and Teacher can create custom scales. From the Administration block, click on Scales. This displays the Scales page. On the Scales page, click on the Add a new scale button. This displays the Editing scale page. On the Editing scale page: Enter a Name for the scale. When you apply the scale to the forum, you will select the scale by this name. In the Scale box, enter the items on your scale. Separate each item with a comma. Write a Description for your scale. Students can see the description, so use this space to explain how they should interpret the scale. Select the Save changes button. You are now ready to apply the scale. Create or edit the forum to which you want to apply the scale. The key setting on the Editing Forum page is Allow posts to be rated? When you review the student postings in the forum, you can rate each posting using the scale you created, as shown in the following screenshot: When you finish rating the postings, click on the Send in my ratings button at the bottom of the page to save your ratings. Split discussions Users with the role Administrator, Course creator, or Teacher can split a discussion. When you split a discussion at a post, the selected post and the ones below become a new topic. Note that you cannot take a few posts from the middle of a topic and split them into a new discussion. Splitting takes every post that is nested below the selected one and puts it into a new topic. Before the split   After the split   Topic 1              Reply 1-1              Reply 1-2                       Reply 1-2-1                       Reply 1-2-2                       Reply 1-2-3              Reply 1-3              Reply 1-4                       Reply 1-4-1                       Reply 1-4-2    New Topic 1-2               Reply 1-2-1               Reply 1-2-2               Reply 1-2-3  Topic 1                Reply 1-1                Reply 1-3                Reply 1-4                           Reply 1-4-1                Reply 1-4-2   Will splitting change the meaning Splitting a thread can rescue a conversation that has gotten off topic. However, it can also change the meaning of the conversation in ways that you don't expect or want. Note that in the preceding example, after the split, the new topic is moved to the top of the forum. Will that change the meaning of your forum? Let's look at an example. Following is the screenshot showing the fi rst topic in a forum on the October Revolution of Russian history. In this topic, students discuss whether the revolution was a coup or a popular uprising: The teacher made the first posting and several students have posted replies. Some of these replies, as shown in the following screenshot, favor the theory that the revolution was a coup, while others favor the theory of revolution being a popular uprising: Note that the posting by Student2 is a reply(Re) to the posting by Student1. You might have missed that because the reply is not indented. That's because the teacher has selected Display replies flat, with oldest first. If the teacher had selected Display replies in nested form, you would see Student2's reply indented, or nested, under Student1's reply. We can tell that Student2 is replying to Student1 because the subject line indicates it is a reply to Student1 (Re: My vote: popular uprising). The first two postings are pro-uprising. The last posting is pro-coup. It occurs to the teacher that it would facilitate discussion to split the forum into pro-uprising and pro-coup topics. The teacher scrolls down to the pro-coup posting, which just happens to be the last posting in this forum, and clicks on Split, as shown in following screenshot: This will make a new topic out of the pro-coup posting: Will splitting move replies you want to keep in place In this example, the teacher was lucky. Under the pro-coup posting, there were no pro-uprising replies. If there were, those replies would have come with the pro-coup posting, and the teacher would not have been able to make a topic that was completely pro-coup.
Read more
  • 0
  • 0
  • 3598
article-image-lesson-solutions-using-moodle-19-part-1
Packt
21 Jan 2010
10 min read
Save for later

Lesson Solutions using Moodle 1.9: Part 1

Packt
21 Jan 2010
10 min read
One of the most challenging aspects of course development often involves simply determining how to select and organize your material. It is very important to be strategic about the type of material you select. Needless to say, every item used in your course should tie directly to course outcomes, and you should make sure that all your items are used in some way. Beyond that, putting the material in your course can feel fairly confusing. Fortunately, Moodle makes it easy to select, incorporate, and organize your content. Moodle also helps you lead students through the material in a way that will maximize the chances of them finishing your course and successfully achieving learning outcomes. Before we go any further, it is worthwhile to take a moment to clarify lessons in Moodle. The terminology can be a bit confusing. In Moodle, a lesson is an activity that fits well within the object-oriented approach of Moodle. It is important to keep in mind that the idea of a lesson in Moodle is fairly limited, and will work within the overall traditional notion of lessons. Selecting and sequencing content for lessons In this section, we'll discuss the best way to select content for your lessons, and how to arrange it so that the students naturally progress to the kinds of competence they need to demonstrate when they get ready for their final assessments. Create conditions for learning Everyone has experienced the pain of a bad lecture when there is just absolutely nothing that reaches out and captures one's imagination. You squirm, you daydream, and then, when it's over, you can't recall a single thing that was said. In that situation, one can safely say that not much learning took place, not just because the delivery might have been ineffectual, but even more compellingly because the speaker failed to ever connect with his/her audience. The educational psychologist Robert Gagne studied the problem of developing ideal learning conditions and, after years of research published his findings in a book titled Conditions of Learning released in 1965. Basically, he discovered that to create ideal learning conditions, there are nine instructional events that must take place. The first event, which he describes as "gaining attention", is critical. If you intellectually stimulate the learners, you're activating receptors in their brain, and they are more likely to pay attention. Once you've gained their attention, you should develop activities that will do the following: Inform learners of objectives and create levels of expectation Stimulate recall of prior learning that relates to your course objectives Present instructional content Guide your students by creating categories and sequences Encourage performance and practice Provide feedback (either automatically or personally) Assess performance Apply knowledge to job or other activity Gagne's "instructional events" are not set in stone, but they are very useful as you put your course together. Notice that they are heavily weighted towards performance, which is not too surprising as Gagne was a resolute behaviorist. Other theorists such as Vygotsky might lean more heavily toward social learning and put more emphasis on the discussion forums. Employ scaffolding Scaffolding is a concept that was developed by Bruner (1975), who used Vygotsky's notions of social and imitative learning in order to explain how people learn from each others in groups and classrooms. Vygotsky held that children learn as they observe teachers and others and, as they adopt practices, they are coached by others to modify their behaviors until they conform to the norm. Bruner took the idea further and proposed that a good way to help students learn is to have a model (a teacher) perform the activity, and then assist the student until he/she is able to perform independently and freely. Bruner thought of the support that is gradually taken away as "scaffolding". If you learned to ride a bicycle as a child, you probably used training wheels, so it might be more comfortable to think of this as a "training wheel" approach. At any rate, wherever and whenever you can, let your students see partially worked problems, and work on the problems with them. Peers can also be training wheels or scaffolding for each other as well, as they provide partial solutions, model essays, and partially-solved problems in anticipation of being able to do things independently. Use chunking to help build concepts Have you ever felt utterly lost in a maze of too much information?, Have you heard anyone remarking that "he/she couldn't see the forest for the trees"? In each case, the problem was that of too many small bits of information and not enough large, organizing sets or categories. To address that problem, educational psychologists have developed a concept they call "chunking", which is basically grouping small items into sets. Essentially, you are mentally recoding low-information content and grouping them together. Ideally, the total number of units will decrease, and what you'll be left with is a small number of high-information "chunks". Chunks are easier to work with than thousands of individual pieces, just as it's easier to pick up a necklace than a thousand individual beads. As you develop your content, think of ways to organize, classify, and categorize to help students access and retrieve information from their working memory. Keep in mind that these are good activities to employ early in the lesson as you seek to help students master the lower-level and foundational cognitive tasks such as identify, define, and describe. Get students involved early Why make students take risks? Why make them introduce themselves, respond to questions, and interact? While it's true that some students will feel a certain amount of discomfort as they make themselves vulnerable, the rewards for the intellectual and emotional risk-taking are very high. They will feel a sense of affiliation, and the essentially dehumanizing e-learning space will become more human, more socially relevant to their lives. Another key consideration is that students are able to practice higher-level cognitive tasks in the discussion board area. They can evaluate, analyze, and synthesize topics on a deeper level through intellectual interaction with peers. Keep it lively Gaining attention is something that you'll need to do throughout the class. Students will constantly need to be stimulated, refreshed, and refocused. Not only will you stimulate the receptors in their brains, you'll also help them formulate their own conversation with the content. As for questions in their minds, be sure to relate the content to something practical and relevant—in the world, in their lives, in their prior knowledge—and then encourage them to discuss and debate. Keeping it lively not only keeps their attention, it also motivates students to return to the course and will help them maintain a high level of enthusiasm. Keep focused There are a number of ways to keep students focused on what you're wanting them to learn. The key is to mix it up, and not repeat the same attention-getting tactics, or you'll risk having students totally tune it out. Try many different strategies—add points, add a video snippet, interject a question, add a graphic or diagram, incorporate a practice quiz or game. Use media strategically Some instructors fall into the trap of media overload. The students may be studying Shakespeare's Hamlet, so they put up links to a hundred different video clips of Shakespearean plays. Yes, one or two are great, after a while, the overload can be distracting. As you select media, put it in a location where the student needs to pause to reflect on content or relate to it in a new way. You can also sequence the media so that it occurs when students may be starting to get bored or losing their focus. Media can help you refocus the students. Diagnostic and developmental/remedial content With Moodle you can design your course so that it builds in material to help students who may need more time, help, and practice on certain aspects of the lessons. For example, you can build in "Test Yourself!" diagnostic quizzes, which can help pinpoint where a student needs to focus more. This sounds a lot like the old pretest and posttest approach, but the difference is that it occurs within your lesson and students can stop along the way to get help. For example, an algebra course could include little "spot check" diagnostic quizzes. They could lead to a review section that is not required for the entire class, but for special needs. It's like having a private tutor. Reward practice The more the students practice, the more likely they are to feel good about their ability to perform, both in real-life applications as well as in their final assignments or tests. So, be sure to provide many opportunities for students to practice, and also for them to receive feedback, either automated or personalized from you or a peer. However, be careful that your quizzes and practice activities are similar in structure, content, and feel to their "high stakes" assignments. If they are not, the students will be discouraged. Also, be sure that the questions and the levels are the same as in the graded assignments. Don't make the final quiz too hard or too easy. Align content, levels of difficulty, time limitations, and testing conditions to those the students will experience later. Build confidence for final graded performance All the content and the activities in your lesson should build toward the students' final performance, whether a final essay, test, or presentation. By the time they reach the end of the lesson, the students should know what to expect and feel comfortable about what lies ahead. Furthermore, they should have a good idea of where to go when they feel lost or have questions. For example, they may be able to refer to a repository of supplemental readings or solved problems, or they can ask questions in the discussion board. At any rate, they always feel as though there is a supportive presence, either in the course itself or in access to the instructor and fellow students. Getting started: A simple example The following screenshot shows a very basic instructional lesson in Moodle. Note that it is essentially a website, and it contains text, links, and an embedded graphic. In fact, it is written in HTML. It is a brief lesson, and so does not have a large number of components. Essentially, the lesson is introducing a concept (the relationship between distance and perspective). It is engaging the student's curiosity by asking a question and then providing an illustrative graphic. The instruction involves testing the student's knowledge by using a "jump question". If you get it right, you proceed to the next item, and if you get it wrong, you're either taken back to the instructional page or jump to a remedial page. However, the jump question could just as easily ask a student what he/she is interested in learning next, or some other exploratory question. When the student clicks on the Continue button at the bottom of the lesson page, he/she is taken to a question page, as shown next: Each answer displays a different feedback. If the student answers correctly, he/she is taken to the next instructional page. An incorrect answer takes the student to a remedial page. This is the normal sequence for a lesson in Moodle. Later, we'll discuss how we can make the best use of the Lesson module.
Read more
  • 0
  • 0
  • 1486

article-image-lesson-solutions-using-moodle-19-part-2
Packt
21 Jan 2010
8 min read
Save for later

Lesson Solutions Using Moodle 1.9: Part 2

Packt
21 Jan 2010
8 min read
Controlling the flow through a lesson If your lesson questions have all true/false or yes/no answers, you will probably set Maximum number of answers/branches to 2. If you use more than two answers per question, consider whether you want to create a jump page for each answer. If you create a unique jump page for every answer on the question pages, and you use three answers per question, how many cards will there be in your flash card deck? The answer is your lesson will have three pages for each flash card, the card itself, plus two jump pages for remedial information. We don't want to spend all day creating a short lesson. But we still want to show remedial information when a student selects the wrong answer. Consider phrasing your questions, answers, and remedial pages so that one remedial page can cover all of the incorrect responses. The illustration shows this kind of flow. Note that we've reduced the number of remedial pages that have to be created. If you must give a different feedback for each answer to a question, consider using a quiz instead of a lesson. While a remedial page in a lesson can consist of anything that you can put on a web page, a feedback can only consist of text. However, quizzes are usually easier to create than lessons. If a quiz with feedback will suffice, you can probably create it faster than the kind of branching lesson shown in the figure. But if your feedback must be feature rich, there's nothing better than Moodle's Lesson module. Use a lesson to create a deck of flash cards Flash cards are a classic teaching strategy. In addition to a learning experience, flash cards also make a good self-assessment tool for students. You can use a lesson, as if it's an online deck of flash cards. One advantage of using an online system is that log files tell you if a student completed the flash card activity, and how well the student did. Keep it moving Students are accustomed to a flash card activity moving quickly. Showing a remedial page after each incorrect response will slow down the activity. Consider using only question feedback, without remedial pages in between cards. In a flash card lesson, every page will be a question page. In a lesson, a question page can have any content that you can put on a normal web page. So, each page in your flash card lesson can consist of a fully-featured web page, with a question at the bottom and some text-only feedback for each answer. When setting the jumps for each answer on the question page (on the card), make sure that a correct answer takes the student to the next page and an incorrect answer keeps them on the same page. Again, this duplicates our physical experience with flash cards. When we get the correct answer, we move on to the next card. When we get the wrong answer, we try again until we've got it right. Lesson settings that help create a flash card experience For a flash card lesson, you will probably set Practice lesson to Yes so that the grade for this lesson will not show up in the Gradebook. As stated above, setting Maximum grade to 0 will prevent this activity from showing up in the Gradebook. However, it will also prevent a student from seeing his/her score on the activity. If you want the student to see how well he/she did on the lesson, set Practice lesson to Yes and use a maximum grade that makes sense such as one point per correct answer. Allow student review enables a student to go backwards in a lesson and retry questions that he/she got wrong. In a flash card activity, this is usually set to No. Instead, we usually set Action after correct answer to Show an unanswered Page. That means after a student answers a flash card question incorrectly, Moodle might display that card again during the same session. If the student answers the question correctly, that card is not shown again during the same session. This is how most of us are accustomed to using physical flash cards. Number of pages (cards) to show determines how many pages are shown. You usually want a flash card session to be short. If the lesson contains more than this number, the lesson ends after reaching the number set here. If the lesson contains fewer than this number, the lesson ends after every card has been shown. For a flash card lesson, set this to less than the total number of cards. You can use the Slide Show setting to display the lesson in a separate window, and make that window the size of a flash card. This can help create the effect of a deck of cards. When the student uses a physical deck of flash cards, he/she can see approximately how far into the deck he/she is. The Progress bar setting can help to create this effect with your online deck of flash cards Use an ungraded lesson to step through instructions Briefly, precorrection is anticipating mistakes that students might make, and providing instruction to help them avoid those mistakes. Consider, you give a complex assignment to students . You know that even if you supply them with written instructions, they are likely to make mistakes, even when following the instructions. You might also give the students a video demo, and a Frequently Made Mistakes document. You could even host a chat before the assignment to answer any questions they have about how to complete it. If you focus these items on the parts of the assignment that are most likely to cause trouble, they become examples of precorrection. You can use a lesson to give students precorrection for difficult instructions. Place directions that should be read in a specific order on a series of lesson pages. See to it that the students step through those pages. This has several advantages over placing all of the instructions on one page. They are as follows: Moodle will log the students' view of the lesson pages so that you can confirm they have read the instructions. While the length of a lesson page is unlimited, the tendency when creating them is to keep them short. This encourages you to break up the directions into smaller chunks, which are easier for students to understand. You can insert a question page after each step, to confirm the user's understanding of the step. Question feedback and remedial pages can correct the students' understanding, before they move to the next step. If you use this technique, the lesson should probably be a Practice lesson so that the students' grade doesn't affect their final grade for the course. A workaround Less ons are designed to primarily be a teaching tool, and only secondarily an assessment tool. However, if you decide that you prefer to use a lesson for assessment, you can work around this limitation. This workaround enables you to determine if a student answered incorrectly on an initial question or on a remedial question. A low score on remedial questions should prompt action on the teacher's part such as contacting the student and offering additional help. You have seen how a lesson usually consists of an instructional page followed by a question page, and that when a student answers a question incorrectly the lesson can display a remedial page. After the remedial page, you can present another question on the same topic. Now, imagine a lesson that covers three items. Each item has its own instructional page followed by a question page, and a remedial page followed by another question page. So, not counting the entry and exit pages, there would be: Three topic pages Three question pages Three remedial topic pages Three remedial question pages If you were looking at the Gradebook for this lesson, and a student's grade indicated that he/she got two questions wrong, you could determine whether it was because he/she gave: One incorrect response on two of the items Two incorrect responses for the same item If the student answered incorrectly on both the first and the remedial questions for the same item, it could indicate the student is having trouble with that item. But the Gradebook won't tell you that. You will need to drill down from the Gradebook into the lesson to see that student's score for each question. From the Gradebook, you would select the category in which the lesson is placed. In this example, the activities are not categorized: After selecting the category (or just Uncategorised), a table of grades for each student/activity is displayed, which is as shown in the following screenshot: You may see that Student2 did not score well on the lesson. So, select the student's score to drill down into the lesson. Select the Reports tab, then the Overview subtab, and then the grade that you want to investigate: Finally , you may think that you're going to see a detailed report telling you which questions this student got right or wrong, so you would then be able to determine which concepts or facts he/she had trouble with, and help the student with those items. But instead, you see the following screenshot:
Read more
  • 0
  • 0
  • 1429

article-image-working-cxf-tool
Packt
18 Jan 2010
9 min read
Save for later

Working with CXF Tool

Packt
18 Jan 2010
9 min read
Invoking a web service using the Java client A web service exposes a set of operations over the network, typically via HTTP protocol. In order to invoke the web services, the web service client needs to know the following information: What operations are exposed by the web service The input and output message formats required to access the service operations What protocol, for instance HTTP or JMS, to use to invoke the web service The URL location of the web service All of the above information is contained in the standard XML descriptor called WSDL (Web Service Description Language). The WSDL file provides a format contract between the web service provider and the web service client. The web service client typically inspects the WSDL file to determine what operations are exposed by the web service, what parameters need to be supplied to invoke the web service operation and to formulate the request, and invokes the web service over the supported protocol. Similarly, the web service clients need to write the code to inspect the response and convert it into the required format. CXF hides the complexity of creating web service clients by providing the WSDL to Java command line tool, which takes a WSDL file and generates client code. The client code can be used by developers with no changes to invoke the web services. In this section, we will look at how to generate client code from an existing WSDL. For this example, we will take a real world scenario, where we will invoke a .NET service located over the Web using the Java client generated by the WSDL to Java tool. This shows the true power of web service interoperability, where applications implemented in different languages can communicate with each other. The process of generating web service clients does not differ for web services implemented in different languages, as you generate web service clients from WSDL and XML Schema definitions. Before invoking the .NET service, let's examine the WSDL to determine which operations are exposed by the web service. Analyzing the service WSDL definition We will invoke a publicly available .NET web service located at http://www.ignyte.com/webservices/ignyte.whatsshowing.webservice/moviefunctions.asmx?wsdl. This web service retrieves US Theaters and Movie Showtime information based on a valid US zip code and a radius supplied by the web service clients. The .NET web service is a WS-I compliant web service. The Web Services Interoperability Organization (WS-I), an open industry organization, was formed to promote web services interoperability across platforms, operating systems, and programming languages. One concrete product of WS-I is the Basic Profile. Basic Profile narrows the scope of specifications to a reasonable set of rules and guidelines that are best suited to help interoperability. If you type in the given URL in the browser, you see the WSDL definition, as shown in the following screenshot: Let's analyze the important sections of the WSDL file to get an understanding of which operations are exposed by the movie information web service and which message formats are required to invoke the web service. The web service provides two operations, GetTheatersAndMovies and GetUpcomingMovies, as shown in listing below. For this article, we will focus on how to invoke the GetTheatersAndMovies operation. The GetTheatersAndMovies takes the GetTheatersAndMoviesSoapIn message as the input and provides GetTheatersAndMoviesSoapOut as the output message. <wsdl:portType name="MovieInformationSoap"> <wsdl:operation name="GetTheatersAndMovies"> <wsdl:documentation >This method will retrieve a list of all theaters and the moviesplaying today.</wsdl:documentation> <wsdl:input message="tns:GetTheatersAndMoviesSoapIn" /> <wsdl:output message="tns:GetTheatersAndMoviesSoapOut" /> </wsdl:operation></wsdl:portType> The web service client invokes the GetTheatersAndMovies operation to get theater and movie information. The input to the GetTheatersAndMovies operation is the GetTheatersAndMoviesSoapIn XML message. The GetTheatersAndMoviesSoapIn message references the GetTheatersAndMovies element, which defines the actual XML schema definition for the input message. The following is the code listing of GetTheatersAndMovies schema definition: <s:element name="GetTheatersAndMovies"> <s:complexType> <s:sequence> <s:element minOccurs="0" maxOccurs="1" name="zipCode" type="s:string" /> <s:element minOccurs="1" maxOccurs="1" name="radius" type="s:int" /> </s:sequence> </s:complexType></s:element> The GetTheatersAndMovies contains an element zipCode of type String and radius which is of type integer that needs to be passed as input by the web services client as an input to the GetTheatersAndMoviesSoapIn operation. The minOccurs and maxOccurs attribute associated with zipCode and radius is used to specify the minimum and maximum occurrence of the element inside a GetTheatersAndMovies element. The zipCode and radius element can appear only once inside a GetTheatersAndMovies element as it specifies the value of maxOccurs="1". If maxOccurs has the value Unbounded, then it implies that multiple occurrences of the element can exist. Similarly, the GetTheatersAndMoviesResponse specifies the output message format for the response. The following is the code listing of the GetTheatersAndMoviesResponse schema definition. We will break down the schema for better understanding: The GetTheatersAndMoviesResponse schemaThe following shows the definition of GetTheatersAndMoviesResponse. The GetTheatersAndMoviesResponse contains an element ArrayOfTheater. <s:element name="GetTheatersAndMoviesResponse"> <s:complexType> <s:sequence> <s:element minOccurs="0" maxOccurs="1" name="GetTheatersAndMoviesResult" type= "tns:ArrayOfTheater" /> </s:sequence> </s:complexType></s:element> The ArrayOfTheater SchemaThe following shows the definition of ArrayOfTheater schema.The ArrayOfTheater is an array which consists of Theatre elements.The maxOccurs="unbounded" specifies that multiple occurrences of Theatre elements can exist in an ArrayOfTheater element. <s:complexType name="ArrayOfTheater"> <s:sequence> <s:element minOccurs="0" maxOccurs= "unbounded" name="Theater" nillable= "true" type="tns:Theater" /> </s:sequence></s:complexType> The Theater SchemaThe Theater elements consist of the Name and Address elements of type String, which specifies the name and address of the Theater and an array of ArrayOfMovie element. <s:complexType name="Theater"> <s:sequence> <s:element minOccurs="0" maxOccurs="1" name="Name" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="Address" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="Movies" type="tns:ArrayOfMovie" /> </s:sequence></s:complexType> The ArrayOfMovie SchemaThe following is the ArrayOfMovie definition. The ArrayOfMovie is an array which consists of Movie elements. The maxOccurs="unbounded" specifies that multiple occurrences of Movie elements can exist in an ArrayOfMovie element. <s:complexType name="ArrayOfMovie"> <s:sequence> <s:element minOccurs="0" maxOccurs= "unbounded" name="Movie" nillable= "true" type="tns:Movie" /> </s:sequence></s:complexType> The Movie SchemaThe Movie element contains details of movies such as ratings, names of the movies, running times and show times represented as String type. <s:complexType name="Movie"> <s:sequence> <s:element minOccurs="0" maxOccurs="1" name="Rating" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="Name" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="RunningTime" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="ShowTimes" type="s:string" /> </s:sequence></s:complexType> Based on the Schema definitions above, the CXF WSDL2Java tool generates Java code that maps to these XML elements. The web service clients communicate with the web services using these generated Java objects to invoke a Java method representing the GetTheatersAndMoviesoperation and leave the SOAP XML to Java conversion and low level implementation details with the CXF framework. The SOAP address in the WSDL file specifies the location of the service, which is http://www.ignyte.com/webservices/ignyte.whatsshowing.webservice/moviefunctions.asmx, as shown in the listing below: <wsdl:service name="MovieInformation"> <wsdl:port name="MovieInformationSoap" binding= "tns:MovieInformationSoap"> <soap:address location="http://www.ignyte.com/webservices/ ignyte.whatsshowing.webservice/moviefunctions.asmx" /> </wsdl:port> <wsdl:port name="MovieInformationSoap12" binding= "tns:MovieInformationSoap12"> <soap12:address location="http://www.ignyte.com/webservices/ ignyte.whatsshowing.webservice/moviefunctions.asmx" /> </wsdl:port> </wsdl:service></wsdl:definitions> We will now look at how to generate the web service client code for the Movie information web service. Building and running the Java web service clients The source code and build files for the example are available in the wsdl2Java folder of the downloaded source code. We will follow the steps below to build and execute the web service client: Generate the web service clients Analyze the generated artifacts Modify the generated code Build the web service client Run the web service client Generate the web service clients We will use the Ant build script (build.xml) for generating the web service client code and building the project code as shown below. Navigate to the wsdl2java folder of the downloaded source code. Execute the cxfWSDLToJava target by navigating to the wsdl2java folder and running the following command: ant cxfWSDLToJava The following figure shows the output generated upon running the ant command: The cxfWSDLToJava ant target calls the CXF tool apache.cxf.tools.wsdlto.WSDLToJava to generate web service client code based on the URL http://www.ignyte.com/webservices/ignyte.whatsshowing.webservice/moviefunctions.asmx?wsdl The following is a code snippet of ant target cxfWSDLToJava in build.xml: <target name="cxfWSDLToJava"> <java classname="org.apache.cxf.tools.wsdlto.WSDLToJava" fork="true"> <arg value="-client"/> <arg value="-d"/> <arg value="src"/> <arg value="http://www.ignyte.com/webservices/ignyte. whatsshowing.webservice/moviefunctions.asmx?wsdl"/> <classpath> <path refid="cxf.classpath"/> </classpath> </java></target> WSDLToJava generates JAX-WS compliant Java code for the services defined in the WSDL document. Based on the parameters passed, it can generate the starting point of the code for developing the web service client and service. The client option, as shown in above snippet, generates the client code. The following is a list of augments and descriptions supported by the WSDLToJava tool extracted as it is from the CXF website—http://cwiki.apache.org/CXF20DOC/wsdl-to-java.html
Read more
  • 0
  • 0
  • 3678
article-image-developing-web-service-cxf
Packt
07 Jan 2010
9 min read
Save for later

Developing a Web Service with CXF

Packt
07 Jan 2010
9 min read
In this article we will basically study the sample Order Processing Application and discuss the following points: Developing a service Developing a client The Order Processing Application The objective of the Order Processing Application is to process a customer order. The order process functionality will generate the customer order, thereby making the order valid and approved. A typical scenario will be a customer making an order request to buy a particular item. The purchase department will receive the order request from the customer and prepare a formal purchase order. The purchase order will hold the details of the customer, the name of the item to be purchased, the quantity, and the price. Once the order is prepared, it will be sent to the Order Processing department for the necessary approval. If the order is valid and approved, then the department will generate the unique order ID and send it back to the Purchase department. The Purchase department will communicate the order ID back to the customer. For simplicity, we will look at the following use cases: Prepare an order Process the order The client application will prepare an order and send it to the server application through a business method call. The server application will contain a web service that will process the order and generate a unique order ID. The generation of the unique order ID will signify order approval. In real world applications a unique order ID is always accompanied by the date the order was approved. However, in this example we chose to keep it simple by only generating order ID. Developing a service Let's look specifically at how to create an Order Processing Web Service and then register it as a Spring bean using a JAX-WS frontend. The Sun-based JAX-WS specification can be found at the following URL: http://jcp.org/aboutJava/communityprocess/final/jsr224/index.html JAX-WS frontend offers two ways of developing a web service—Code-first and Contract-first. We will use the Code-first approach, that is, we will first create a Java class and convert this into a web service component. The first set of tasks will be to create server-side components. In web service terminology, Code-first is termed as the Bottoms Up approach, and Contract-first is referred to as the Top Down approach. To achieve this, we typically perform the following steps: Create a Service Endpoint Interface (SEI) and define a business method to be used with the web service. Create the implementation class and annotate it as a web service. Create beans.xml and define the service class as a Spring bean using a JAX-WS frontend. Creating a Service Endpoint Interface (SEI) Let's first create the SEI for our Order Processing Application. We will name our SEI OrderProcess. The following code illustrates the OrderProcess SEI: package demo.order; import javax.jws.WebService; @WebService public interface OrderProcess { @WebMethod String processOrder(Order order); } As you can see from the preceding code, we created a Service Endpoint Interface named OrderProcess. The SEI is just like any other Java interface. It defines an abstract business method processOrder. The method takes an Order bean as a parameter and returns an order ID String value. The goal of the processOrder method is to process the order placed by the customer and return the unique order ID. One significant thing to observe is the @WebService annotation. The annotation is placed right above the interface definition. It signifies that this interface is not an ordinary interface but a web service interface. This interface is known as Service Endpoint Interface and will have a business method exposed as a service method to be invoked by the client. The @WebService annotation is part of the JAX-WS annotation library. JAX-WS provides a library of annotations to turn Plain Old Java classes into web services and specifies detailed mapping from a service defined in WSDL to the Java classes that will implement that service. The javax.jws.WebService annotation also comes with attributes that completely define a web service. For the moment we will ignore these attributes and proceed with our development. The javax.jws.@WebMethod annotation is optional and is used for customizing the web service operation. The @WebMethod annotation provides the operation name and the action elements which are used to customize the name attribute of the operation and the SOAP action element in the WSDL document. The following code shows the Order class: package demo.order;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name = "Order")public class Order { private String customerID; private String itemID; private int qty; private double price; // Contructor public Order() { } public String getCustomerID() { return customerID; } public void setCustomerID(String customerID) { this.customerID = customerID; } public String getItemID() { return itemID; } public void setItemID(String itemID) { this.itemID = itemID; } public int getQty() { return qty; } public void setQty(int qty) { this.qty = qty; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; }} As you can see, we have added an @XmlRootElement annotation to the Order class. The @XmlRootElement is part of the Java Architecture for XML Binding (JAXB) annotation library. JAXB provides data binding capabilities by providing a convenient way to map XML schema to a representation in Java code. The JAXB shields the conversion of XML schema messages in SOAP messages to Java code without having the developers know about XML and SOAP parsing. CXF uses JAXB as the default data binding component. The @XmlRootElement annotations associated with Order class map the Order class to the XML root element. The attributes contained within the Order object by default are mapped to @XmlElement. The @XmlElement annotations are used to define elements within the XML. The @XmlRootElement and @XmlElement annotations allow you to customize the namespace and name of the XML element. If no customizations are provided, then the JAXB runtime by default would use the same name of attribute for the XML element. CXF handles this mapping of Java objects to XML. Developing a service implementation class We will now develop the implementation class that will realize our OrderProcess SEI. We will name this implementation class OrderProcessImpl. The following code illustrates the service implementation class OrderProcessImpl: @WebServicepublic class OrderProcessImpl implements OrderProcess { public String processOrder(Order order) { String orderID = validate(order); return orderID; }/** * Validates the order and returns the order ID**/ private String validate(Order order) { String custID = order.getCustomerID(); String itemID = order.getItemID(); int qty = order.getQty(); double price = order.getPrice(); if (custID != null && itemID != null && !custID.equals("") && !itemID.equals("") && qty > 0 && price > 0.0) { return "ORD1234"; } return null; }} As we can see from the preceding code, our implementation class OrderProcessImpl is pretty straightforward. It also has @WebService annotation defined above the class declaration. The class OrderProcessImpl implements OrderProcess SEI. The class implements the processOrder method. The processOrder method checks for the validity of the order by invoking the validate method. The validate method checks whether the Order bean has all the relevant properties valid and not null. It is recommended that developers explicitly implement OrderProcess SEI, though it may not be necessary. This can minimize coding errors by ensuring that the methods are implemented as defined. Next we will look at how to publish the OrderProcess JAX-WS web service using Spring configuration.   Spring-based server bean What makes CXF the obvious choice as a web service framework is its use of Spring-based configuration files to publish web service endpoints. It is the use of such configuration files that makes the development of web service convenient and easy with CXF. Spring provides a lightweight container which works on the concept of Inversion of Control (IoC) or Dependency Injection (DI) architecture; it does so through the implementation of a configuration file that defines Java beans and its dependencies. By using Spring you can abstract and wire all the class dependencies in a single configuration file. The configuration file is often referred to as an Application Context or Bean Context file. We will create a server side Spring-based configuration file and name it as beans.xml. The following code illustrates the beans.xml configuration file: <beans xsi_schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"> <import resource="classpath:META-INF/cxf/cxf.xml" /> <import resource="classpath:META-INF/cxf/cxf-extension- soap.xml" /> <import resource="classpath:META-INF/cxf/cxf-servlet.xml" /> <jaxws:endpoint id="orderProcess" implementor="demo.order.OrderProcessImpl" address="/OrderProcess" /></beans> Let's examine the previous code and understand what it really means. It first defines the necessary namespaces. It then defines a series of <import> statements. It imports cxf.xml, cxf-extension-soap.xml, and cxf-servlet.xml. These files are Springbased configuration files that define core components of CXF. They are used to kick start CXF runtime and load the necessary infrastructure objects such as WSDL manager, conduit manager, destination factory manager, and so on. The <jaxws:endpoint> element in the beans.xml file specifies the OrderProcess web service as a JAX-WS  endpoint. The element is defined with the following three attributes: id—specifies a unique identifier for a bean. In this case, jaxws:endpoint is a bean, and the id name is orderProcess. implementor— specifies the actual web service implementation class. In this case, our implementor class is OrderProcessImpl. address— specifies the URL address where the endpoint is to be published. The URL address must to be relative to the web context. For our example, the endpoint will be published using the relative path /OrderProcess. The <jaxws:endpoint> element signifies that the CXF internally uses JAX-WS frontend to publish the web service. This element definition provides a short and convenient way to publish a web service. A developer need not have to write any Java class to publish a web service.
Read more
  • 0
  • 0
  • 3329

article-image-cxf-architecture
Packt
07 Jan 2010
8 min read
Save for later

CXF architecture

Packt
07 Jan 2010
8 min read
The following figure shows the overall architecture: Bus Bus is the backbone of the CXF architecture. The CXF bus is comprised of a Spring-based configuration file, namely, cxf.xml which is loaded upon servlet initialization through SpringBusFactory. It defines a common context for all the endpoints. It wires all the runtime infrastructure components and provides a common application context. The SpringBusFactory scans and loads the relevant configuration files in the META-INF/cxf directory placed in the classpath and accordingly builds the application context. It builds the application context from the following files: META-INF/cxf/cxf.xml META-INF/cxf/cxf-extension.xml META-INF/cxf/cxf-property-editors.xml The XML file is part of the installation bundle's core CXF library JAR. Now, we know that CXF internally uses Spring for its configuration. The following XML fragment shows the bus definition in the cxf.xml file. <bean id="cxf" class="org.apache.cxf.bus.CXFBusImpl" /> The core bus component is CXFBusImpl . The class acts more as an interceptor provider for incoming and outgoing requests to a web service endpoint. These interceptors, once defined, are available to all the endpoints in that context. The cxf.xml file also defines other infrastructure components such as BindingFactoryManager, ConduitFactoryManager, and so on. These components are made available as bus extensions. One can access these infrastructure objects using the getExtension method. These infrastructure components are registered so as to get and update various service endpoint level parameters such as service binding, transport protocol, conduits, and so on. CXF bus architecture can be overridden, but one must apply caution when overriding the default bus behavior. Since the bus is the core component that loads the CXF runtime, many shared objects are also loaded as part of this runtime. You want to make sure that these objects are loaded when overriding the existing bus implementation. You can extend the default bus to include your own custom components or service objects such as factory managers. You can also add interceptors to the bus bean. These interceptors defined at the bus level are available to all the endpoints. The following code shows how to create a custom bus: SpringBeanFactory.createBus("mycxf.xml") SpringBeanFactory class is used to create a bus. You can complement or overwrite the bean definitions that the original cxf.xml file would use. For the CXF to load the mycxf.xml file, it has to be in the classpath or you can use a factory method to load the file. The following code illustrates the use of interceptors at the bus level: <bean id="cxf" class="org.apache.cxf.bus.spring.SpringBusImpl"> <property name="outInterceptors"> <list> <ref bean="myLoggingInterceptor"/> </list> </property></bean><bean id="myLogHandler" class="org.mycompany.com.cxf.logging. LoggingInterceptor"> ...</bean> The preceding bus definition adds the logging interceptor that will perform logging for all outgoing messages. Frontend CXF provides the concept of frontend modeling, which lets you create web services using different frontend APIs. The APIs let you create a web service using simple factory beans and JAX-WS implementation. It also lets you create dynamic web service clients. The primary frontend supported by CXF is JAX-WS. JAX-WS JAX-WS is a specification that establishes the semantics to develop, publish, and consume web services. JAX-WS simplifies web service development. It defines Java-based APIs that ease the development and deployment of web services. The specification supports WS-Basic Profile 1.1 that addresses web service interoperability. It effectively means a web service can be invoked or consumed by a client written in any language. JAX-WS also defines standards such as JAXB and SAAJ. CXF provides support for complete JAX-WS stack. JAXB provides data binding capabilities by providing a convenient way to map XML schema to a representation in Java code. The JAXB shields the conversion of XML schema messages in SOAP messages to Java code without the developers seeing XML and SOAP parsing. JAXB specification defines the binding between Java and XML Schema. SAAJ provides a standard way of dealing with XML attachments contained in a SOAP message. JAX-WS also speeds up web service development by providing a library of annotations to turn Plain Old Java classes into web services and specifies a detailed mapping from a service defined in WSDL to the Java classes that will implement that service. Any complex types defined in WSDL are mapped into Java classes following the mapping defined by the JAXB specification. As discussed earlier, two approaches for web service development exist: Code-First and Contract-First. With JAX-WS, you can perform web service development using one of the said approaches, depending on the nature of the application. With the Code-first approach, you start by developing a Java class and interface and annotating the same as a web service. The approach is particularly useful where Java implementations are already available and you need to expose implementations as services. You typically create a Service Endpoint Interface (SEI) that defines the service methods and the implementation class that implements the SEI methods. The consumer of a web service uses SEI to invoke the service functions. The SEI directly corresponds to a wsdl:portType element. The methods defined by SEI correspond to the wsdl:operation element. @WebServicepublic interface OrderProcess { String processOrder(Order order);} JAX-WS makes use of annotations to convert an SEI or a Java class to a web service. In the above example, the @WebService annotation defined above the interface declaration signifies an interface as a web service interface or Service Endpoint Interface. In the Contract-first approach, you start with the existing WSDL contract, and generate Java class to implement the service. The advantage is that you are sure about what to expose as a service since you define the appropriate WSDL Contract-first. Again the contract definitions can be made consistent with respect to data types so that it can be easily converted in Java objects without any portability issue. WSDL contains different elements that can be directly mapped to a Java class that implements the service. For example, the wsdl:portType element is directly mapped to SEI, type elements are mapped to Java class types through the use of Java Architecture of XML Binding (JAXB), and the wsdl:service element is mapped to a Java class that is used by a consumer to access the web service. The WSDL2Java tool can be used to generate a web service from WSDL. It has various options to generate SEI and the implementation web service class. As a developer, you need to provide the method implementation for the generated class. If the WSDL includes custom XML Schema types, then the same is converted into its equivalent Java class. Simple frontend Apart from JAX-WS frontend, CXF also supports what is known as 'simple frontend'. The simple frontend provides simple components or Java classes that use reflection to build and publish web services. It is simple because we do not use any annotation to create web services. In JAX-WS, we have to annotate a Java class to denote it as a web service and use tools to convert between a Java object and WSDL. The simple frontend uses factory components to create a service and the client. It does so by using Java reflection API. The following code shows a web service created using simple frontend: // Build and publish the serviceOrderProcessImpl orderProcessImpl = new OrderProcessImpl();ServerFactoryBean svrFactory = new ServerFactoryBean();svrFactory.setServiceClass(OrderProcess.class);svrFactory.setAddress("http://localhost:8080/OrderProcess");svrFactory.setServiceBean(orderProcessImpl);svrFactory.create(); Messaging and Interceptors One of the important elements of CXF architecture is the Interceptor components. Interceptors are components that intercept the messages exchanged or passed between web service clients and server components. In CXF, this is implemented through the concept of Interceptor chains. The concept of Interceptor chaining is the core functionality of CXF runtime. The interceptors act on the messages which are sent and received from the web service and are processed in chains. Each interceptor in a chain is configurable, and the user has the ability to control its execution. The core of the framework is the Interceptor interface. It defines two abstract methods—handleMessage and handleFault. Each of the methods takes the object of type Message as a parameter. A developer implements the handleMessage to process or act upon the message. The handleFault method is implemented to handle the error condition. Interceptors are usually processed in chains with every interceptor in the chain performing some processing on the message in sequence, and the chain moves forward. Whenever an error condition arises, a handleFault method is invoked on each interceptor, and the chain unwinds or moves backwards. Interceptors are often organized or grouped into phases. Interceptors providing common functionality can be grouped into one phase. Each phase performs specific message processing. Each phase is then added to the interceptor chain. The chain, therefore, is a list of ordered interceptor phases. The chain can be created for both inbound and outbound messages. A typical web service endpoint will have three interceptor chains: Inbound messages chain Outbound messages chain Error messages chain There are built-in interceptors such as logging, security, and so on, and the developers can also choose to create custom interceptors.
Read more
  • 0
  • 0
  • 3166
Modal Close icon
Modal Close icon