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

How-To Tutorials - Web Development

1802 Articles
article-image-securing-moodle-data
Packt
03 Mar 2011
7 min read
Save for later

Securing Moodle Data

Packt
03 Mar 2011
7 min read
Moodle Security Learn how to install and configure Moodle in the most secure way possible User information protection Every user within Moodle has a profile which can contain information we may or may not want to show to other users, or at least not to all of them. The level of exposure will depend on the privacy policy we want to adopt. For example, we may want to completely isolate users within a course so that nobody knows who else is participating, or we may want to expose just the user names and nothing else, and so on. Let us first describe how Moodle handles presentation of user profiles. This is important as it will expose internal workings of that subsystem and identify all access points and ways of disabling them if that is what we want to do. User profile page User profile page is used to define personal information about a user within a Moodle. It can contain name, surname, address, telephone, etc. The user profile page is reached by <Moodle URL>/user/view.php?id=<userid>&course=<courseid> where userid and courseid are identifiers of user and course as they are stored in database. This is how Moodle determines whether to show or not the profile page for a particular user:     Logged-on user User to see Condition Show profile User Other user Other user is teacher in at least one course yes     User is teacher in at least one course yes       User has View user profiles capability enabled in current context yes     None of the above no User User None yes When we say teacher we refer to the Moodle roles Teacher and Non-editing teacher. Reaching profile page There are several ways a user can reach the profile page for a particular user. We are presenting them here in order to help the administrator to block potentially unwanted access points to user information. People block Every course upon creation gets a set of predefined blocks. One of these blocks is the people block. When present and visible it gives every user an opportunity to browse all users participating in the current course. This block is visible to any user that has the View participants capability enabled. This capability exists for system and course level. In Moodle 1.9.8 and later, by default this capability is enabled only for the Administrator role on both levels. That way no user other than Administrator will be able to see participants on the system level or in specific course. If by any chance you use an older version of Moodle, then most likely you have this capability enabled on the course level for all standard roles except for guest and authenticated user. Unless you want to open privacy policy on your site we recommend you to disable this capability. Visit the Administration Users | Permissions | Define roles| page, then locate and modify that capability by setting it to "Not set". Apply this at least on the Student role. Forum topics Forum topic offers another way of accessing the user profile. Regardless of the forum type, Moodle displays the author name for every post. This name is actually linked to the profile page for that user. Messaging system Moodle offers a messaging system for internal communications between users. The Messaging system can be accessed from three locations—personal profile page, platform front page, and course content page.   Moodle page Conditions Displayed Profile page Send message to any user capability is enabled Yes Front page Message block is added by Administrator Yes Course content page Message block is added to the course by Administrator or teacher Yes If any of these conditions are fulfilled users will be able to access the messaging system. By default none of these conditions are present for Students and therefore there is no danger of any privacy intrusion. However, it is a common practice in various installations of Moodle to add a messaging block to one or more courses. Any user will be able to communicate with other users within same context (course). The problem with messaging is that it enables any user to locate any other user registered in the platform. We can demonstrate this easily. Open the messaging dialog and switch to the Search tab. In the Name field enter one letter and press the Search button. You will get ALL user accounts that have the specified letter either in name or surname as a result. The search result apart from the actual names of the users also offers a direct link to their personal profile. This is a potentially dangerous feature that can expose more information than we are willing to permit. If messaging is called from a context in which the users have permission to view user profiles he will be able to see any profile in the system. This way user names and profiles are completely open. There is no way to modify this behavior (listing all users) other than disabling the messaging system. Having a messaging system enabled can be a problem if you have a malicious user within your system that wants to get names of all users or a spam-bot that wishes to harvest e-mail addresses. That is the reason we should do something about that. Protecting user profile information We have several options available for protecting access to private information located in personal user profile. You can choose one that is most appropriate for your particular use case. Limit information exposed to all users If we do not have a problem exposing some information of the user in their profile then we can then just hide some fields. To do that visit the Administration Users | Permissions | User policies| page and locate the Hide user fields section. Using this approach you still cannot hide the user e-mail or his actual name which is good for cases where you want users to communicate with each other without knowing too many personal details. Completely block ability to view profiles If you want to completely block access to the user's profiles you have several options explained as follows: Disable View participants capability We already explained that by default every Moodle as of version 1.9.8 has this disabled by default. We are listing it here just for the sake of being complete. Hide messaging system Hiding messaging system means removing access points from user's reach. This means do not add Messages block on the front page and in any course where you wish to avoid users from knowing the other participants. This is useful where you want to have mixed messaging policy for different courses—set of users. Have in mind that this setup gives sort of a false sense of separation. Users from courses which do not have Messages block can still access Messaging system if they type the URL by hand. Disable Messaging system If you do not care for Messaging in your Moodle site you can completely disable it. To do that visit the Administration Security | Site policies| page and uncheck Enable messaging system option. Not using general forums If you have a website where you want to completely isolate only part of users within a course, among other things you can adopt the policy of not adding general forums inside such courses and on the site front page. That way you can still use forums in other courses where you do not have security concerns. Disable View user profiles capability If you want to completely block any possibility of viewing user profiles for specific role(s) you need to modify the View user profile capability and set it to "Not set". Visit the Administration Users | Permissions | Define roles| page, locate and modify that capability for every role you wish to prevent from viewing user profiles.
Read more
  • 0
  • 0
  • 2532

article-image-developing-ejb-30-entity-weblogic-server
Packt
27 Aug 2010
3 min read
Save for later

Developing an EJB 3.0 entity in WebLogic Server

Packt
27 Aug 2010
3 min read
(For more resources on Oracle, see here.) Setting the environment In the following sections, we will learn how to set up the environment. Installing required products First, download and install the following required products; when installing the MySQL database, select the option to add the MySQL bin directory to the Windows system PATH environment variable: Oracle WebLogic Server 11g (http://www.oracle.com/technology/software/products/ias/htdocs/wls_main.html). Oracle Enterprise Pack for Eclipse All-In-One edition (http://www.oracle.com/technology/software/products/oepe/oepe_11113.html). MySQL 5.x database (http://www.oracle.com/us/products/mysql/index.html). Creating a MySQL database table Next, create a database table in the MySQL database as follows: Log in to the MySQL database with the following command: >mysql Set database as test: mysql>use test Run the following SQL script, which creates a Catalog table for the EJB 3 entity: CREATE TABLE Catalog (id INT PRIMARY KEY NOT NULL, journal VARCHAR(100), publisher VARCHAR(100), date VARCHAR(100), title VARCHAR(100), author VARCHAR(100)); The output from the CREATE TABLE SQL script is shown in the following screenshot: The table description may be listed with the desc command, as shown in the following illustration: Configuring WebLogic Server with MySQL database We shall be using a MySQL database for persistence. Therefore, we need to create a data source in WebLogic Server. Start the WebLogic Server and log in to the Administration Console. Creating a data source Select the base_domain | Services | JDBC | Data Sources. Click on New in the Data Sources table. Specify a data source name and a JNDI Name (jdbc/MySQLDS) for the data source. Select Database Type as MySQL and Database Driver as MySQL's Driver (Type 4): com.mysql.jdbc.Driver. Click on Next, as shown in the following screenshot: (Move the mouse over the image to enlarge.) In the Transaction Options window, select Supports Global Transactions and One-Phase Commit. Click on Next, as shown in the following screenshot: Specify the connection properties: Database Name as test, Host Name as localhost, Port as 3306, and Database User Name as root. Specify the Password used when installing MySQL and click on Next, as shown in the following screenshot: In the Test Database Connection window, the Driver Class Name and connection URL are specified, normally filled from the information you entered in the previous screen. Click on Test Configuration to test the connection. Click on Finish, as shown in the following screenshot: A data source gets added to the Data Sources table with its data source JNDI Name as jdbc/MySQLDS, as shown in the following screenshot: Deploying the data source Next, we deploy the data source to a target server. Click on the data source link in the Data Sources table and select the Targets tab. Select the AdminServer checkbox and click on Save, as shown in the following screenshot: The target server changes get applied and saved: Testing the data source To test the data source, click on Test Data Source. If the data source tests without an error, a message indicating the same gets displayed as shown next:
Read more
  • 0
  • 0
  • 2531

article-image-supporting-editorial-team-drupal-6
Packt
21 Oct 2009
16 min read
Save for later

Supporting an Editorial Team in Drupal 6

Packt
21 Oct 2009
16 min read
What you will do In this article, you will: Create a team Add Roles to support the team Define new Node Content types Configure permissions to support the Roles Handle a former (and disgruntled) team member The Creative team Let's take a quick look at Drupal's jargon regarding teams. Users—the logins of the individuals that make up a team Roles—the different 'job descriptions' based on a person's responsibilities Permissions—the granting of authorization to perform a Drupal function As the system administrator, you are authorized to perform any action within the Drupal environment, but you would not want every member of a team to have this absolute capability, or else you would soon have chaos. Let's first create a team. Then, we will look at assimilating that team into the Drupal environment. Our Creative team will be made up of individuals, each having one or more of the responsibilities mentioned below (Note: the titles are not Drupal terms): Copy Writers—are the writers of short articles Feature Writers—are the writers of long pieces, in which style matters a much as content Ad Writers—are the writers of internal and external advertising that will appear in blocks Proofreaders—are the reviewers who check pieces for spelling, grammar and usage errors Associate Editors—are the reviewers that are concerned with style, readability, and continuity Style Editors—are responsible for the formatting of content Graphic Artists—are the creators of the illustrations and images that are used as copy Senior Editor—is responsible for the quality of all of the above Moderator—manages postings by site visitors, such as comments and blog posts Blogger—creates blog entries Administrator—addresses the aspects of the site unrelated to content With our team assembled, let's move on to creating the roles in our site. Roles Drupal comes with three roles installed: creator (also known as userID1), authenticated user and anonymous user. Only the latter two are listed when assigning permissions, because the creator role can do everything, including things that you might not want the administrator to be able to do. It's best not to use the creator's login as the administrator login. A separate administrator role should be created and granted the appropriate permissions. So, looking at the list above, we will need to create roles for all of our team members. Creating roles in Drupal is a quick and easy process. Let's create them. Activity 1: Creating Roles The Name of the role is assigned as per the responsibilities of the team member. Login as the administrator. Select the User management option. Select the Roles option. Enter the name of the role in the text box, as shown in the following screenshot, and then click on the Add role button. We'll add the rest of the roles in the same way. After a couple of minutes, we have the entire team added, as seen in following screenshot. The edit role links are locked for anonymous user and authenticated user, because those roles should remain constant and never be edited or deleted. Node Content types The default installation of Drupal contains two Node Content types namely: Page and Story. Some modules, when activated, create additional Node Content types. One such example is the Blog entry, and another is an Event, which is used when using an event calendar. We're using the term Node Content to differentiate content nodes in Drupal, such as Pages and Stories, from other non-node types of content, such as Blocks, which is the generic term for anything on the page. What is the purpose of having different Node Content types? If we want a feature  writer to be able to create Features, then how do we accomplish that? Currently, we have Stories and Pages as our Node Content types. So, if we give the Feature writer the ability to create a Page, then what differentiates that Page from any other Page on our site? If we consider a Page as a Feature, then anyone who can create a Page has created a Feature, but that's not right, because not every Page is a Feature. Activity 2: Node Content for our Roles Because we have role types that we want to limit to working with their respective Node Content types, we will need to create those Node Content types. We will assign a Node Content type of Feature for Feature Writers, Ads for Ad Writers, and so on. Let's create them. From the admin menu, we'll select Content management. On the Content management page, we'll choose Content types. The Node Content types are listed, and from the top of the page we'll select Add content type. We're going to start with the Feature writer, so in the Name field we'll enter Feature. The next field, Type, determines the term that will be used to construct the default URL for this Node Content type. We'll enter feature as the text value for this field. In the Description field, we'll enter a short description, which will appear next to the Node Content type's link on the admin page, as follows: Next, we'll click on the Workflow settings link to display the additional workflow fields. When our Feature Writer completes a piece, it will not be published immediately. It will have to be proofread and undergo an editorial review. So, we'll deselect the Published and Promote to front page boxes. At this point we've configured the new Node Content type as per our needs, so we'll click on the Save button, and then we can see it listed, as shown in the screenshot below. We already have a Node Content type of Blog entry, which was created by the Blog module. The only other Role that requires its own Node Content type is the Ad Writer. This is because the other Roles defined will only edit existing Node Content,  as opposed to creating it. It is here that we run into trouble. The pieces that are 'grabbed' by Drupal to appear (usually) at the center of the screen, which we have been referring to as Node Content, are nodes, whether a Page, a Story, or now a Feature. The small blocks that appear around the sides, or on top, or at the bottom, are Blocks. Because they are placed in those positions, and are not available for selection as Node Content, they are not nodes. The Benefit of BlocksWhen looking at a typical web page of a CMS site, you will see a main body area with Node Content, such as articles, and also small blocks of information elsewhere on the page, such as in the left and right margins, or along the top or bottom. The main content, nodes, are limited, as to where they appear. However, each of the blocks can be configured to appear on any or every page of the site. That is why ads are best created as blocks, so that they can be placed where they will be the most effective. Nodes are created via the Create content function, and that function is available from the front page to anyone who is granted the permission. Using the admin menu is not necessary. On the other hand, blocks are created and edited from the Block page, which is an admin function. Although we can grant that capability to a user without granting any other admin capabilities, it would be much better if we could have an Ad Writer create ads in the same way that they create other Node Content. The reason for this is that with nodes, separate permission can be given to create a node and to administer a node. With  blocks, there is only one permission. You can create, edit, delete, and rearrange all of the blocks, or none. This opens the door to an accidental disaster. We don't want the Ad Writer doing anything but creating ad copy. So, in order to address this concern, we've added a module to our site: Node blocks. This module allows us designate a Node Content type (other than Page and Story) to be used as a Block. With that in mind, let's create our final Node Content type. Where can you find this module? This module, as well as other modules, can be found at http://drupal.org/project/modules. Activity 3—creating a Block Node Content type We'll start by repeating Steps 1 to 3 from the previous activity. In the Title field, we'll type in Ad. In the Type field, we'll type in ad. For the description, we'll enter Advertisement copy that will be used as blocks. We'll click on Workflow settings and deselect Published and Promoted to front page, as we did with the Feature. There is a new heading in this dialog, Available as Block, as seen in the following screenshot. This comes from the module that we've added. We'll select Enabled, which will make any piece created with this Node Content type available as a Block. That's all we need to do, so now we'll save our new Node Content type   Permissions The way that we enable one user to do something that the other cannot is by creating different user types (which we have done), different Node Content types—where necessary—(which again has been done), and then assign permissions to the user types (which we'll do now). The administrator will not be listed as a user type under Permissions, because if permissions were accidentally removed from the administrator, there might be no other user type that has the permissions to restore them. Activity 4: Granting Permissions Let's now assign to the members of the Creative team the Permissions that suit them best. From the admin menu we'll select User management. On the User management page we'll choose Permissions. The screenshot below shows us the upper portion of the screen. There are numerous permissions, and we now have numerous User types, so the resulting grid is very large. Rather than step-by-step illustrations, I'll simply list each Role and the Permissions that should be enabled in the form of Heading→Permission. Ad Writer node module→access content node module→create ad content node module→delete any ad content node module→delete own ad content node module→edit any ad content node module→edit own ad content node module→view revisions fckeditor module→access fckeditor Because of the number of Node Content types, each having several permissions as seen above, combined with the permissions being alphabetical by verb within the heading, instead of Content type, the necessary permissions are somewhat distant from each other and require scrolling to find them all. Feature Writer node module→access content node module→create feature content node module→delete any feature content node module→delete own feature content node module→edit any feature content node module→edit own feature content node module→view revisions fckeditor module→access fckeditor Blogger blog module→create blog entries blog module→delete own blog entries blog module→edit own blog entries node module→access content node module→view revisions fckeditor module→access fckeditor Associate Editor—The Associate Editor is concerned with content, which means editing it. The ability to create or delete content, to affect where the content appears, and so on, is not required for this Role. fckeditor module→access fckeditor node module→access content node module→edit any ad content node module→edit any feature content node module→edit any page content node module→edit any story content node module→revert revisions node module→view revisions path module→create URL aliases Copy Writer fckeditor module→access fckeditor node module→access content node module→create page content node module→create story content node module→delete own page content node module→delete own story content node module→edit own page content node module→edit own story content node module→view revisions Graphic Artist blog module→edit any blog entry fckeditor module→access fckeditor fckeditor module→allow fckeditor fle uploads node module→access content node module→edit any ad content node module→edit any feature content node module→edit any page content node module→edit any story content Moderator blog module→edit any blog entry comment module→access comments comment module→administer comments fckeditor module→access fckeditor node module→access content node module→edit any ad content node module→edit any feature content node module→edit any page content node module→edit any story content Proofreader blog module→edit any blog entry fckeditor module→access fckeditor node module→access content node module→edit any ad content node module→edit any feature content node module→edit any page content node module→edit any story content Style Editor block module→administer blocks fckeditor module→access fckeditor fckeditor module→allow fckeditor fle uploads node module→access content node module→edit any ad content node module→edit any feature content node module→edit any page content node module→edit any story content Senior Editor block module→administer blocks blog module→delete any blog entry blog module→edit any blog entry comment module→access comments comment module→administer comments fckeditor module→access fckeditor fckeditor module→allow fckeditor fle upload node module→access content node module→delete any ad content node module→delete any feature content node module→delete any page content node module→delete any story content node module→delete revisions node module→edit any ad content node module→edit any feature content node module→edit any page content node module→edit any story content node module→revert revisions node module→view revisions path module→create URL aliases view module→access all views view module→administer views With that, we have assigned the required permissions to all of our team members, which will allow them to do their jobs, but keep them out of trouble! However, what do you do when someone intentionally gets into trouble? The disgruntled team member So, we've been marching along as one big happy team, and then it happens. Someone gets let go, and that someone isn't happy about it, to say the least. Of course, we'll remove that person's login, but there is public access to our site as well, in the form of comments. Is there a way for us to stop this person from looking for ways to annoy us, or worse? Yes! Activity 5: Blocking Let's now perform the tasks necessary to keep disgruntled employees (and trouble-makers) at bay. From the admin menu, select User management. On the User management page, we'll select the Access rules option. We'll choose the Add rule option on the Access rules page. On the Add rule page, we have the option to deny access to a user, email address, or host. The username and email address options will block someone from registering, but will not affect someone already registered. The host name will stop anyone with that host name from accessing the system at all. Wild cards can be used: % will match any number of characters, and _ will match one character. Allow rules can be used to give access to someone who would otherwise be blocked by a host or wild card rule. In our case, let's say that the disgruntled former team member is spamming our comments from a host called spamalot.com, and is doing it from many emails. The first thing we want to do is create a 'deny' rule that will deny access to anyone from that host, as shown in the following figure, and then click on the Add rule button. We're also going to create an email deny rule for %@spamalot.com. We shouldn't have to (as we've already denied the host, which in turn would include all of the emails from that host), but we need to, because the rules testing logic ignores that hierarchy at this time. Let's also say that we've received an email from someone whose email address is its_not_me@spamalot.com, who would like to be a member of our site, and we verify that this person is not our former team member. In such a scenario, we will need to create an Allow rule, as shown in the following screenshot, so that this person can get past our previous Deny rule. Our rules now appear, as shown below, when we click on the List button, which is at the top of the page. It's always good to check and make certain that we've created the rule(s) correctly. If we don't do this, then we might inadvertently block the wrong users. Let's click on the Check rules tab at the top of the Access rules page. In the email box, we'll first try disgruntled@spamalot.com. Next, we'll try its_not_me@spamalot.com. In this last activity we have created some access rules. Drupal uses these access rules to determine who can and cannot access the site. In some cases, you may be having difficulty with a particular user adding comments to your site. Of course, if you set comments to require moderation, then the questionable ones won't appear, but it can still be a pain having to review a steady stream of them. In that case, you can block a specific user. You might be having difficulty with comments from more than one user at a given email domain. You can, if you like, block everyone from that location. On the other hand, your site might be meant for users of a particular domain, perhaps a university. In that case, you can allow users from that domain and only them. Summary In this article we learned about: Roles—defining types of users Permissions—defining capabilities for each role Node Content types—as they apply to Roles Access Rules—for those pesky, misbehaving users These features have been explained and learned with the help of activities where we have: Created a team Added Roles to enable the team Defined new Node Content types to suit the requirements of some team members Configured permissions to support the Roles and Node Content types Handled a former (and disgruntled) team member
Read more
  • 0
  • 0
  • 2529

article-image-animating-built-button
Packt
19 Mar 2013
8 min read
Save for later

Animating a built-in button

Packt
19 Mar 2013
8 min read
(For more resources related to this topic, see here.) Note that there might be more states to a fully functioning button, for example, there is also a Disabled state, but whether a button is disabled or not usually does not depend on mouse movements or positions, it does not have to be animated, and we do not describe it here. Our purpose in this section is not to create a fully functioning button, but rather to demonstrate some generic concepts for re-styling a control and providing custom animations for it. Let's create a Silverlight project containing a single page with the button in its center. The following is the resulting XAML code of the main page: <UserControl x_Class="AnimatingButtonStates.MainPage" > <Grid x_Name="LayoutRoot" Background="White"> <Button Width="100" Height="25" Background="LightGray" Content="Press Me" /> </Grid> </UserControl> We want to re-style this button completely, modifying it shape, border, colors, and creating custom animations for the transition between states. Now, we'll create a very simple custom template for the button by changing the button code to the following code: <!-- Here we provide custom button template --> <Button> <Button.Template> <ControlTemplate TargetType="Button"> <Grid x_Name="TopLevelButtonGrid"> <!--Button Border--> <Border x_Name="ButtonBorder" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" CornerRadius="5" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> </Border> <!-- button content is placed here--> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" /> </Grid> </ControlTemplate> </Button.Template> <Button> If we run the code, as it is, we shall be able to see the button and its Press Me content, but the button will not react visually to mouse over or press events. That is because once we replace the button's template we will have to provide our own solution to the visual changes for different button states. Now, let's discuss how we want the button to look in the different states and how we want it to handle the transitions between states. When the mouse is over the button, we want a blue border to appear. The animation to achieve this can be fast or even instantaneous. When the button is pressed, we want it to scale down significantly and we want the button to scale up and down several times, each time with lower amplitude before achieving a steady pressed state. Note that the control template developers and designers usually try to avoid changing colors within animations (they are considered to be more complex and less intuitive); instead, they try to achieve color-changing effects by changing opacities of several template parts. So to change the border to blue on mouse over, let's create another border element MouseOverBorder with blue BorderBrush, and non-zero BorderThickness within the control template. At normal state, its opacity property will be 0, and it will be completely transparent. When the state of the button changes to MouseOver, the opacity of this border will change to 1. After we add the MouseOverBorder element together with the visual state manager functionality, the resulting template code will look as follows: <Button> <Button.Template> <ControlTemplate TargetType="Button"> <Grid x_Name="TopLevelButtonGrid"> <VisualStateManager.VisualStateGroups> <VisualStateGroup> <VisualStateGroup.Transitions> <!-- duration for the MouseOver animation is set here to 0.2 seconds --> <VisualTransition To="MouseOver" GeneratedDuration="0:0:0.2" /> </VisualStateGroup.Transitions> <VisualState x_Name="Normal" /> <VisualState x_Name="MouseOver"> <VisualState.Storyboard> <Storyboard> <!--animation performed when the button gets into "MouseOver" State--> <DoubleAnimation Storyboard. TargetName="MouseOverBorder" Storyboard.TargetProperty="Opacity" To="1" /> </Storyboard> </VisualState.Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <!--Button Border--> <Border x_Name="ButtonBorder" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" CornerRadius="5" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> </Border> <!--MouseOverBorder has opacity 0 normally. Only when the mouse moves over the button, the opacity is changed to 1--> <Border x_Name="MouseOverBorder" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" CornerRadius="5" BorderBrush="Blue" BorderThickness="2" Opacity="0"> </Border> <!-- button content is placed here--> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" /> </Grid> </ControlTemplate> </Button.Template> </Button> Now, if we start the application, we'll see that the border of the button becomes blue, if the mouse pointer is placed over it, and returns to its usual color when the mouse pointer is moved away from the button, as shown in the following screenshot: The next step is to animate the pressed state. To achieve this, we add a ScaleTransform object to the top-level grid of the button's template: <ControlTemplate TargetType="Button"> <Grid x_Name="TopLevelButtonGrid" RenderTransformOrigin="0.5,0.5"> <Grid.RenderTransform> <!-- scale transform is used to shrink the button when it is pressed --> <ScaleTransform x_Name="OnPressedScaleTransform" ScaleX="1" ScaleY="1" /> </Grid.RenderTransform> ... The purpose of the ScaleTransform object is to shrink the button once it is pressed. Originally, its ScaleX and ScaleY parameters are set to 1, while the animation that starts when the button is pressed changes them to 0.5. This animation is defined within VisualState defined as Pressed: <VisualStateGroup> ... <VisualState x_Name="Pressed"> <VisualState.Storyboard> <Storyboard> <!-- animation performed when the button gets into "Pressed" State will scale down the button by a factor of 0.5 in both dimensions --> <DoubleAnimation Storyboard.TargetProperty="ScaleX" Storyboard.TargetName="TheScaleTransform" To="0.5" /> <DoubleAnimation Storyboard.TargetProperty="ScaleY" Storyboard.TargetName="TheScaleTransform" To="0.5" /> </Storyboard> </VisualState.Storyboard> </VisualState> ... </VisualStateGroup> VisualState defines the animation storyboard to be triggered once the button switches to the Pressed state. We can also add VisualStateTransition to the VisualStateGroup element's Transition property: <VisualStateManager.VisualStateGroups> <VisualStateGroup> <VisualStateGroup.Transitions> ... <VisualTransition To="Pressed" GeneratedDuration="0:0:0.5"> <VisualTransition.GeneratedEasingFunction> <!-- elastic ease will provide a few attenuating bounces before the pressed button reaches a steady state --> <ElasticEase /> </VisualTransition.GeneratedEasingFunction> </VisualTransition> </VisualStateGroup.Transitions> ... </VisuateStateGroup> </VisualStateManager.VisualStateGroups> VisualTransition elements allow us to modify the animation behavior depending on what the original and final states of the transition are. It has properties such as From and To for the purpose of specifying the original and final states. In our case, we set only its To property to Pressed, which means that it applies to transit from any state to the Pressed state. VisualTransition sets the duration of the animation to 0.5 second and adds the ElasticEase easing function to it, which results in the button size bouncing effect. Once we started talking about easing functions, we can explain in detail how they work, and give examples of other easing functions. Easing functions provide a way to modify Silverlight (and WPF) animations. A good article describing easing functions can be found at http://tinyurl.com/arbitrarypathanimations. The easing formula presented in this article is: v = (V2 – V1)/T * f(t/T) + V1 Here v is the resulting animation value, t is the time parameter, T is the time period in question (either time between two frames in an animation with frames or time between the To and From values in the case of a simple animation), V2 and V1 are the animation values at the end and beginning of the animation correspondingly at the absence of easing, and f is the easing function. In the previous formula, we assumed a linear animation (not a spline one). There are a bunch of built-in easing functions that come together with the Silverlight framework, for example, BackEase, BounceEase, CircleEase, and so on. For a comprehensive list of built-in easing functions, please check the following website: http://tinyurl.com/silverlighteasing.. Most easing functions have parameters described on this website. As an exercise you can change the easing function in the previous VisualTransition XAML code, modify its parameters, and observe the changes in button animation. Summary Here we have just learned how to animate a built-in button using Silverlight. Resources for Article : Further resources on this subject: Customized Effects with jQuery 1.4 [Article] Python Multimedia: Fun with Animations using Pyglet [Article] Animating Properties and Tweening Pages in Android 3-0 [Article]
Read more
  • 0
  • 0
  • 2528

article-image-interacting-students-using-moodle-19-part-1
Packt
08 Oct 2009
11 min read
Save for later

Interacting with the Students using Moodle 1.9 (part 1)

Packt
08 Oct 2009
11 min read
We are going to carry out a role-play activity. This activity will be geography-based, but the Moodle activities are the same for any subject. Hopefully, this will help you gain some ideas for your own teaching. Having learned about the course of a river and about the landscape at the location where the river meets the coast, the students are now going to be given the job of developers—planning and designing a riverside campsite. The students will undertake various tasks during the project, all of them within Moodle. We, the teachers, having set the scene, are going to sit back and observe their progress, online. When the entire mini-project is complete, we're going to get them to tell us, personally, how much they feel they have learned. We can use their responses to plan our future Moodle activities. How do we do all this? The words in bold above are examples of activities that we can do in Moodle. There are others too, but for you—as a newbie—these activities are more than enough. To set up any of them, we first need to turn editing on, either via the button on the upper right of the screen, or via the Administration block. Then, in the topic section where we want to add our activity, we click on the space next to Add an activity…. This will bring up a list of options, which might vary depending upon your particular Moodle course. The following screenshot shows some typical options that might show up when you click Add an activity....Be aware that Certificate and Game don't appear in standard Moodle courses. Getting our class to reflect and discuss Have you ever come across a child who is too shy to speak up in class but then produces the most thoughtful written work? Moodle is Godsend for these students, because it has a forum and a chat facility, both of which enable classes and their teachers to have a discussion without actually being together, in the same room. And often, the shy child will happily have their say online, where they can plan it out first and feel comfortable without the interference of their peers. We're going to set some homework where the students will discuss, in general, the kinds of things to keep in mind when planning a riverside campsite. Hopefully, someone will realize it's not a good idea to have it too close to the water. Time for action-setting up a discussion forum on Moodle Let's create an online discussion area for the students to share their views and comments. This discussion area is called the Forum. With editing turned on, click on Add an activity and select Forum. As a result, the following information will appear on the screen. In the Forum type field, click on the drop-down arrow and choose Single Simple Discussion (we'll investigate on the other options later). In the Forum name field, enter some text that will invite your students to click on it to join the discussion. In the Message field, enter your starting topic, with images and hyperlinks, if you wish. Change the option Force everyone to be subscribed to Yes, if you want people to get an email every time somebody adds their comments or suggestions to the forum. Leave the option Read tracking as it is, and people can decide whether to track read or unread messages. The option, Maximum attachment size lets you decide how big a file or an image people can attach with a message. Grade—alter these settings to give each post a mark. But be aware that this will put younger children off. You can put a number in the Post threshold for blocking option if you want to limit the number of posts that a student can make. Click on Save and return to course. What just happened? We have just set up an online discussion area (forum) on a specific topic for our class. Let's go back to our course page and click on the forum that we just prepared. The final output will look like this: Our students will see an icon (usually with two faces) that will prompt them to join the preliminary discussion on where best to locate the campsite. They'll click on the Reply link at the bottom (as you can see in the preceding screenshot), to post their response. How do we moderate the forum? Hopefully, we can just read the students' responses and let them discuss the topic amongst themselves. But as a teacher, we do have three other options: We can edit the response posted by the student (change the wording if it's inappropriate). We can delete the post altogether. We can reply to it when we think it is really important to do so. A student only has the option to reply (as you see if you click on Student view at the upper right of the course page). When we need to get rid of an unsuitable post, or perhaps alter the wording of something one of our students has typed, this extra power we teachers have is helpful. For our starter discussion, we chose a Single Simple Discussion as we wanted the students to focus totally on one issue. However, in other situations, you might need a slightly different type of forum. So the following table gives a brief overview of the other kinds that are available, and explains how you could use them: Name What it does Why use it Single Simple Discussion Only one question they can all answer Best for focused discussions-they can't get distracted Standard forum  Everyone can start a new topic More scope for older students Q and A Pupils must answer first before they can see any replies Useful for avoiding peer pressure issues Each person posts 1 discussion Pupils can post ONE new topic only Handy if you need to restrict posting but still allow some freedom Why use a forum? Here are a few other thoughts on forums, based on my own experiences: A cross-year or cross-class forum can be useful, as the older students can pass on their experiences to the younger students. For example, each year my first year high school students make a volcano as a homework project. As they enter their second year, they use a dedicated forum to pass on their wisdom and answer technical questions sought by the inexperienced first-year students—who are about to begin their own creations. A homework exercise could be set on a forum, as a reflective plenary to the learning done in the class. Once, my class watched a documentary based on the Great New Orleans flood of 2004, and the students were asked, on a forum, to imagine they had been there. They had to suggest some words or phrases to describe their feelings—which we then collated into the next lesson to make poems about the flood. Let's add a little bit of confusion. Instead of simply asking a question, why not make a statement that you know will inspire, annoy, and divide the students. As a result, you can see the variety in the responses. I once posted the topic: “If people live near rivers, and their homes get flooded out, it is surely their own fault for living near rivers. Why should the rest of us have to help them?” In response to this, some violently disagreed with the statement—quoting examples from developing countries, whereas some agreed with the statement—and were then blasted down by their classmates for doing so. But at least the forum got visited! Carrying on the conversation in real time—outside of school A discussion forum, as illustrated above, is a useful tool to get the children to think and to contribute their ideas. It has an advantage over the usual class discussion, in that the shyer pupils are more likely to open up in such discussion forums. However, there is no spontaneity involved. You might post a comment in the morning, and the response may arrive at dinnertime, and so on. Why not combine the advantages of online communication with the advantages of a real time conversation, and make a Moodle chat room? If your students live several miles away from each other, as my students do, and are keen to get on with the project, Moodle chat rooms can have real benefits. We can set a time for the chat—say, Saturday afternoon. This would be a time when we can be present too, if we wish, and the students can move ahead with their plans even though they're not with each other in the classroom. Even though this implementation has its own drawbacks, it provides us with a set-up. Eventually, we can see how it goes and then think about how best we can use it. Time for action-setting up a chat room in Moodle Let's create a chat room where the students can have a chat even when they are not in the same classroom. This way, they can share their views, comments, and suggestions. With editing turned on, go to Add an activity, and select the Chat option. In the Name of this chat room field, enter an appropriate title for the discussion. In the Introduction text field, type in what the discussion is going to be about. For the Next chat time option, choose when you want to open the chat room. For the Repeat sessions option, choose whether you want to chat regularly, or just once. For the Save past sessions option, choose how long, if at all, to keep a record of the conversation. It is up to you to decide whether to allow everyone to view the past sessions or not. For now, you can ignore the Common module settings option. Click on Save and Display. What just happened? We have set up the place and time on Moodle for our students to talk to each other—and even with us if necessary—online. Students will see an icon—usually a speech bubble—on the course page, alongside the name given to the chat. The students just have to click on the icon at the correct time for the chat. When the room is open, they will see this: Clicking on the link will take the students to a box where they'll be able to see their user photo (if they have one) and the time at which they have entered the chat. When others join in, their photos will be shown, and the time of their arrival will be recorded. You talk by typing into the long box at the bottom of the screen, and when submitted, your words appear in the larger box above it. This can get quite confusing if a lot of people are typing at the same time, as the contributions appear one under the other, and do not always follow on from the question or response to which they are referring. Why use Chat? (and why not?) I have to confess that I have switched off the ability for people to use Chat on my school's Moodle site. Chat does have one advantage over the Forum, which is that you can hold discussions in real time with the others who are not physically present in the same room as you. This could be useful on occasions, such as when the teacher is absent from school (but available online). He or she can contact the class at the start of the lesson to check whether they know what they are doing. The students in our school council use Chat for meetings out of school hours, as do our school Governors. You can also read the transcript of a chat (the chat log) after it has happened. However, everyone really has to stay focused on the discussion topic, otherwise, you risk having nothing but a list of trite comments, and no real substance. I've found this to be the case with younger children. Personally, I find a single and a simple discussion in a Forum to be of much more value, than Chat. However, you can try using Chat and see what you think. Your experience could be different from mine.
Read more
  • 0
  • 0
  • 2524

article-image-installing-drupal
Packt
04 Jul 2013
14 min read
Save for later

Installing Drupal

Packt
04 Jul 2013
14 min read
(For more resources related to this topic, see here.) Assumptions To get Drupal up and running, you will need all of the following: A domain A web host Access to the web host's filesystem or You need a local testing environment, which takes care of the first three things For building sites, either a web host or a local testing environment will meet your needs. A site built on a web-accessible domain can be shared via the Internet, whereas sites built on local test machines will need to be moved to a web host before they can be used for your course.  In these instructions, we are assuming the use of phpMyAdmin, an open source, browser-based tool, for administering your database. A broad range of similar tools exist, and these general instructions can be used with most of these other tools. Information on phpMyAdmin is available at http://www.phpmyadmin.net; information on other browser-based database administration tools can be found at http://en.wikipedia.org/wiki/PhpMyAdmin#Similar_products. The domain The domain is the address on the Web from where people can access your site. If you are building this site as part of your work, you will probably be using the domain associated with your school or organization. If you are hosting this on your own server, you can buy a domain for under US $10.00 a year. Enter purchase domain name in Google, and you will have a plethora of options. The web host Your web host provides you with the server space on which to run your site. Within many schools, your website will be hosted by your school. In other environments, you might need to arrange for your own web host by using a hosting company. In selecting a web host, you need to be sure that they run software that meets or exceeds the recommended software versions. Web server Drupal is developed and tested extensively in an Apache environment. Drupal also runs on other web servers, including Microsoft IIS and Nginx. PHP version Drupal 7 will run on PHP 5.2.5 or higher; however, PHP 5.3 is recommended. The Drupal 8 release will require PHP 5.3.10. MySQL version Drupal 7 will run on MySQL 5.0.15 or higher, and requires the PHP Data Objects ( PDO ) extension for PHP. Drupal 7 has also been tested with MariaDB as a drop-in replacement, and Version 5.1.44 or greater is recommended. PDO is a consistent way for programmers to write code that interacts with the database. You can find out more about PDO and how to install it at http://drupal.org/requirements/pdo. Drupal can technically use any database that PDO supports, but MySQL is by far the most tested and best supported. Third-party modules are required to use Drupal with other database systems. You can find these modules listed at http://drupal.org/project/modules/?f[0]=im_vid_3%3A13158&f[1]=drupal_core%3A103&f[2]=bs_project_sandbox%3A0. FTP and shell access to your web host Your web host should also offer FTP access to your web server. You will need FTP (or SFTP) access in order to upload the Drupal codebase to your web space. Shell access, or SSH access, is not essential for basic site maintenance. However, SSH access can simplify maintaining your site, so contracting with a web host that provides SSH access is recommended. A local testing environment Alternatively, you can set up a local testing environment for your site. This allows you to set up Drupal and other applications on your computer. A local testing environment can be a great tool for learning a piece of software. Fortunately, open source tools can automate the process of setting up your testing environment. PC users can use XAMPP (http://www.apachefriends.org) to set up a local testing environment; Mac users can use MAMP (http://www.mamp.info). If you are working in a local testing environment set up via XAMPP or MAMP, you have all the pieces you need to start working with Drupal: your domain, your web host, the ability to move files into your web directory, and phpMyAdmin. Setting up a local environment using MAMP (Mac only) While Apple's operating system includes most of the programs required to run Drupal, setting up a testing environment can be tricky for inexperienced users. Installing MAMP allows you to create a preconfigured local environment quickly and easily using the following steps: Download the latest version of MAMP from http://www.mamp.info/en/index.html. Note that the paid version of the program will download as well. Feel free to pay for the software if you wish, but the free version will be sufficient for our needs. Navigate to where you downloaded the .zip file, and double-click to unzip it. Once it is unzipped, double click on the .pkg file that was contained in the .zip file. Follow the directions in the wizard until you reach the Installation Type screen. If you want to use only the free version of the program, click on the Customize button: In the Custom Install on "Macintosh HD" window, uncheck the MAMP PRO option and click on the Install button to install the application: Navigate to /Applications/MAMP and open the MAMP application. The Apache and MySQL servers will start, and the start page will open in your default web browser. If the start page opens, MAMP is installed correctly. Setting up a local environment using XAMPP (Windows only) Download the latest version of XAMPP from http://www.apachefriends.org/en/xampp-windows.html#641. Download the .zip version. Navigate to where you downloaded the file, right-click, and select Extract All... . Enter C: as the destination and click on Extract . Navigate to C:xampp and double-click the xampp-control application to start XAMPP Control Panel Application : Click on the Start buttons next to Apache and MySql . Open a web browser, and enter http://localhost or http://127.0.0.1 in the address bar, and you should see the following start page: Navigate to http://localhost/security/index.php, and enter a password for MySQL's root user. Make sure to remember this password or write it down in your notebook because we will need it later. Configuring your local environment for Drupal Now that we have the programs required to run Drupal (Apache, MySQL, and PHP), we need to modify some of their settings to match Drupal's system requirements. PHP configuration As mentioned before, Drupal 7 requires Version 5.2.5 or higher, and as of the writing of this book MAMP includes Version 5.4.4 (or you can switch to Version 5.2.17) and XAMPP includes Version 5.4.7. PHP configuration settings are found in the program's php.ini file. For MAMP, the php.ini file is located in /Applications/MAMP/bin/php/[php version number]/conf, where the php version number is either 5.4.4 or 5.2.17. For XAMPP, the php.ini file is located in C:xamppphp. Open the file in a text editor (not a word processor), find the Resource Limits section of the file and edit the values to match the following values: max_execution_time = 60;max_input_time = 120;memory_limit = 128M;error_reporting = E_ALL & ~E_NOTICE The last line is optional and is used if you want to display error messages in the browser, instead of only in the logs. MySQL configuration As mentioned before, Drupal 7 requires MySQL Version 5.0.15 or higher. MAMP includes Version 5.5.25 and XAMPP includes Version 5.5.27. MySQL's configuration settings are contained in a my.cnf or my.ini file. MAMP does not use a my.cnf file by default, so we need to copy the my-medium.cnf file from the /Applications/MAMP/Library/support-files directory to the /Applications/MAMP/conf folder. After copying the file, rename it to my.cnf. For XAMPP, the my.ini file is located in the C:xamppmysqlbin directory. Open the my.cnf or my.ini file in a text editor, find the following settings and edit them to match the following values: # * Fine Tuning#key_buffer = 16Mkey_buffer_size = 32Mmax_allowed_packet = 16Mthread_stack = 512Kthread_cache_size = 8max_connections = 300## * Query Cache Configuration#query_cache_type = 1query_cache_limit = 15Mquery_cache_size = 46Mjoin_buffer_size = 5M# Sort buffer size for ORDER BY and GROUP BY queries, data# gets spun out to disc if it does not fitsort_buffer_size = 10Minnodb_flush_method = O_DIRECTinnodb_file_per_table = 1innodb_flush_log_at_trx_commit = 2innodb_log_buffer_size = 4Minnodb_additional_mem_pool_size = 20M# num cpu's/cores *2 is a good base line for innodb_thread_concurrencyinnodb_thread_concurrency = 4 After you have made the edits, you have to stop and restart the servers for the changes to take effect. Once you have restarted the servers, we are ready to install Drupal! The most effective way versus the easy way There are many different ways to install Drupal. People familiar with working via the command line can install Drupal very quickly without an FTP client or any web-based tools to create and administer databases. The instructions in this book are geared towards people who would rather not use the command line. These instructions attempt to get you through the technical pieces as painlessly as possible, to speed up the process of building a site that supports teaching and learning. Installing Drupal - the quick version The following steps will get you up and running with your Drupal site. This quick-start version gives an overview of the steps required for most setups. A more detailed version follows immediately after this section. Once you are familiar with the setup process, installing a Drupal site takes between five to ten minutes. Download the core Drupal codebase from http://drupal.org/project/drupal. Extract the codebase on your local machine. Using phpMyAdmin, create a database on your server. Write down the name of the database. Using phpMyAdmin, create a user on the database using the following SQL statement: GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTERON databasename.*TO 'username'@'localhost' IDENTIFIED BY 'password'; You will have created the databasename in step 3; write down the username and password values, as you will need them to complete the install. Upload the Drupal codebase to your web folder. Navigate to the URL of your site. Follow the instructions of the install wizard. You will need your databasename (created in step 3), as well as the username and password for your database user (created in step 4). Installing Drupal - the detailed version This version goes over each step in more detail and includes screenshots. Download the core Drupal codebase from http://drupal.org/project/drupal. Extract the codebase on your local machine. The Drupal codebase (and all modules and themes) are compressed into a tarball, or a file that is first tarred, and then gzipped. Such compressed files end in .tar.gz. On Macs and Linux machines, tar.gz files can be extracted automatically using tools that come preinstalled with the operating system. On PC's, you can use 7-zip, an open source compression utility available at http://www.7-zip.org. In your web browser, navigate to your system's URL for phpMyAdmin. If you are using a different tool for creating and managing your database, use that tool to create your database and database user. As shown in the following screenshot, create the database on your server. Click on the Create button to create your database. Store your database name in a safe place. You will need to know your database name to complete your installation. To create your database user, click on the SQL tab as shown in the following screenshot. In the text area, enter the following SQL statement: GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTERON databasename.*TO 'username'@'localhost' IDENTIFIED BY 'password'; For databasename, use the name of the database you created in step 4. Replace the username and password with a username and password of your choice. Once you have entered the correct values, click on the Go button to create the user with rights on your database: Store the username and the password of your database user in a safe place. You will need them to complete the installation. Create and/or locate the directory from where you want Drupal to run. In this example, we are running Drupal from within a folder named drupal7; this means that our site will be available at http://ourdomain.org/drupal7. Running Drupal in a subfolder can make things a little trickier. If at all possible, copy the Drupal files directly into your web root. Using your FTP client, upload the Drupal codebase to your web folder: Navigate to the URL of your site. The automatic install wizard will appear on your screen: Click the Save and continue button with the Standard option selected. Click the Save and continue button with the English (built-in) option selected. To complete the Set up database screen, you will need the database name (created in step 4) and the database username and password (created in step 6). Select MySQL, MariaDB, or equivalent as the Database type and then enter these values in their respective text boxes as seen in the following screenshot: Most installs will not need to use any of settings under ADVANCED OPTIONS . However, if your database is located on a server other than localhost, you will need to adjust the settings as shown in the next screenshot. In most basic hosting setups, your database is accessible at localhost . To verify the name or location of your database host, you can use phpMyAdmin (as shown in the screenshot under step 4) or contact an administrator for your web server. For the vast majority of installs, none of the advanced options will need to be adjusted. Click on the Save and continue button. You will see a progress meter as Drupal installs itself on your web server. On the Configure site screen, you can enter some general information about your site, and create the first user account. The first user account has full rights over every aspect of your site. When you have finished with the settings on this page, click on the Save and continue button. When the install is finished, you will see the following splash screen: Additional details on installing Drupal are available in the handbook at http://drupal.org/documentation/install. Enabling core modules For a full description of the modules included in Drupal core, see http://drupal.org/node/1283408. To see the modules included in Drupal core, navigate to Modules or admin/modules. As shown in the following screenshot, the Standard installation profile enables the most commonly used core modules. (For clarity, we have divided the screenshot of the single screen in two parts.) Assigning rights to the authenticated user role Within your Drupal site, you can use roles to assign specific permissions to groups of users. Anonymous users are all people visiting the site who are not site members; all site members (that is, all people with a username and password) belong to the authenticated user role. To assign rights to specific roles, navigate to People | Permissions | Roles or admin/people/permissions/roles. As shown in the preceding screenshot, click on the edit permissions link for authenticated users. The Comment module: Authenticated users can see comments and post comments. These rights have the comments going into a moderation queue for approval, as we haven't checked the Skip comment approval box. The Node module: Authenticated users can see published content. The Search module: Authenticated users can search the site. The User module: Authenticated users can change their own username. Once these options have been selected, click on the Save permissions button at the bottom of the page. Summary In this article, we installed the core Drupal codebase, enabled some core modules, and assigned rights to the authenticated user role. We are now ready to start building a feature-rich site that will help support teaching and learning. In the next article, we will take a look around your new site and begin to get familiar with how to make your site do what you want. Resources for Article : Further resources on this subject: Creating Content in Drupal 7 [Article] Drupal and Ubercart 2.x: Install a Ready-made Drupal Theme [Article] Introduction to Drupal Web Services [Article]
Read more
  • 0
  • 0
  • 2524
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-creating-design-ez-publish-4-templating-system-part-1
Packt
19 Nov 2009
11 min read
Save for later

Creating a Design with eZ Publish 4 Templating System: Part 1

Packt
19 Nov 2009
11 min read
eZ Publish templating In the first part of this article, we will introduce the basics of the eZ Publish templating system, which will help us to better understand the rest of the article Templating eZ Publish has its own templating system based on the decoupling of layout and content. This will help us to assign a custom layout to any content object in different sections. Moreover, just as other templating platforms, such as Smarty (http://www.smarty.net), eZ Publish has its own markup to help developers with control structure operations, subtemplating, and on-the-fly content editing. It also exposes a particular function to fetch and filter content from a database. The official eZ Publish website has a constant, up-to-date reference with the entire templating markup. We suggest you to use the following link every time that you need to know more details about the available arguments:http://ez.no/doc/ez_publish/technical_manual/4_0/templates/ The templating markup All of the eZ Publish templating code should be placed between curly brackets. When the CMS will parse our template file and find the curly brackets, it will start executing the related code. Escaping the curly bracketsIf we need to use curly brackets, for example to write a javascript function inside our template, we need to use the {literal} operator. {literal}<script type="text/javascript">function alertMe() { window.alert('Harkonen approaching!');}</script>{/literal} Control structure operators We can divide these function into two main families: Conditional (IF-THEN-ELSE) Looping (FOR-FOREACH-WHILE) Whereas the first one should be used to change the template behavior according to some predefined condition, the other one will help us to seek and manage array and content structures. Conditional control Conditional control is sometimes useful for changing the output when some data is received by the system. For example, we would need a different CSS class for a particular value, or to change the <div> class, if the current month is the same as the one displayed, as shown below: {def $current_month=currentdate()|datetime(custom, '%F')}{if $node.name|eq($current_month) }<span class="this-month">{else}<span class="default-month">{/if}{undef $current_month} In the first line, we define a $current_month variable that has a value of the name of the month (for example, October), retrieved by the datetime() operator. Then we use the IF conditional control to choose the correct class. In the last line, we delete the variable previously created, by releasing it from system memory. Loop control As stated above, the loop control structure can be used to iterate through an array. We can, for example, create an unordered list (<ul>) from an array of items. <ul>{foreach $items as $item} <li>{node_view_gui content_node=$item view=line}</li>{/foreach}</ul> This will be rendered as: <ul> <li>1st item</li> <li>2nd item</li> <li>3rd item</li> ...</ul> As you can see, the FOREACH structure is similar to the PHP structure. In this example, the most interesting line is the definition of the list object. This we can literally read as: render the content node (node_view_gui) from a specific node (content_node=$issue) using the line view template (view=line). Fetch functions With the fetch functions, we can retrieve all of the information about a content object for a module. The fetch functions can also be used to create custom queries to retrieve only the information we need, and not everything. eZ Publish exposes many fetch functions, which can be read about on the documentation site at http://ez.no/doc/ez_publish/technical_manual/4_0/reference/template_fetch_functions The most important, and most used, fetch functions are those regarding the content, sections, and user modules. For example, we can fetch the root content object by using the following code in our template: {$object = fetch('content', 'object', hash('id', '1'))} We can then use the $object variable to display the object inside the HTML code. Generic template functions and operators The CMS gives us a lot of functions and operators, all of them described in the reference manual of the eZ System documentation site. As a thumb rule, we should remember that to execute a particular function, we have to use the following syntax: {function_name parameter1=value1 ... parameterN=valueN } All parameters are separated by spaces and can be specified in no particular order. If we want to manage the operators, we have to remember that they accept the parameters passed in a specific order, separated by a comma. Moreover, an operator should handle a parameter passed to it with a pipe (|). {$piped_parameter|my_operator( parameter1, ..., parameterN ) } Every time we see a pipe after a variable, we have to remember that we are passing a value to an operator. We used the datetime() operator in the previous example for the conditional control functionality. As a reference to API functions and operators, you can use the official variable documentation that is constantly updated on the eZ System site:http://ez.no/doc/ez_publish/technical_manual/4_0/reference/template_operatorshttp://ez.no/doc/ez_publish/technical_manual/4_0/reference/template_functions Layout variables By default, the page layout template can access some of the variables passed by the CMS. These variables, named Layout variables, can be used to render system and user information, or to change the output. These variables are automatically configured by eZ Publish when it analyzes and executes the code related to a view. One of the most important variables is $module_result, which contains the results generated by the module and the view that is being executed. A module is an HTTP interface that interacts with eZ Publish. A module consists of a set of views that contain the code to be executed. For example, if we call the following URL, the system executes the login view code of the user module:http://www.example.com/index.php/user/login. As an API reference, you can use the official variable documentation that is constantly updated on the eZ System site:http://ez.no/doc/ez_publish/technical_manual/4_0/templates/the_pagelayout/variables_in_pagelayout Overriding a template eZ Publish offers a set of standard templates that are useful, but they cannot cover all the possible design needs. To solve this issue, the CMF provides a fallback system that allows us to load different templates based on specific rules. This system is usually referred to as overriding, and allows us to change the template for each module's view by overriding the default template when the user is in a particular context. Embedding HTML inside the WYSIWYG XML editor, pt.2 We have to override a standard behavior of eZ Publish to create a generic HTML block inside the WYSIWYG XML editor. We use a content style named html for the online editor and we will work on it for the frontend to render it correctly. First, we have to create a file named literal.tpl and place it in the design folder of our extension. The following code will do exactly what we need: # mkdir -p /var/www/packtmediaproject/extension/packtmedia/design/magazine/templates/datatype/view/ezxmltags/# cd /var/www/packtmediaproject/extension/packtmedia/design/magazine/templates/datatype/view/ezxmltags/# touch literal.tpl Next, we will open the literal.tpl file in our preferred IDE. Now we will add the code that will, by default, render everything surrounded by a <pre> tag and the raw HTML code, if the class is html: {if ne( $classification, 'html' )} <pre {if ne( $classification|trim, '' )} class="{$classification|wash}"{/if}>{$content|wash( xhtml )}</pre>{else} {$content}{/if} This code will check to see if the $classification variable is different from the "html" string in order to add the <pre> tag and then, again, it will add a class attribute to the <pre> tag if the $classification variable is not null. To use it, we only need to reset the cache from the shell prompt by using the following command: cd /var/www/packmediaproject/php bin/php/ezcache.php --clear-all --purge The ezcache.php file is a PHP shell script that can be used to clear and manage the eZ Publish cache. This file has many parameters, which can be viewed by using the --help parameter. Creating a new design Before starting work on the eZ Webin template code, we need to create a wireframe in order to decide on the layout structure. We will use this structure to override the standard layout files. A wireframe is a basic visual guide that is used in web design to suggest the structure of a website and the relationships between its pages. Wireframe editorsThere are a lot of commercial and free wireframe editors. To create our site's wireframes, we will use the Firefox plugin called Pencil(http://www.evolus.vn/Pencil/).We have chosen Pencil because it is open source and works on every platform that runs the Firefox browser.If you need something more complete, you should take a look at Balsamiq (http://www.balsamiq.com/) or at OmniGraffle (http://www.omnigroup.com/applications/OmniGraffle/) if you have an Apple computer. Our site will have at least six different page layouts: The homepage The issue page, where we will display the cover and the articles list The issue archive page, by month and by years The staff profile page, where we will display the latest articles that the editor has written, along with his profile The article and the forum pages, with the default layout based on the eZ Webin design Now we will illustrate the first four layouts because we will work on them, overriding their standard eZ Webin layout. The homepage Starting from the homepage, we can see that the site will have, in the top-left corner, a logo for the magazine and a place-holder for a banner. Under these, we will have the main navigation menu and the main content area. We have chosen a three-column layout in order to easily manage the content that we want to show. In the homepage, the first column will show the latest news and the middle column will show the information and cover of the latest issue. The last column will have two boxes—one with the most important article from the latest issue and the other with the forum thread. Issue page The issue page will show some information of a specific magazine issue. In this page, the middle box of the homepage will shift towards the left, and in the right column there will be the highlighted article for the issue. At the bottom of the page, we will find all of the other articles. The issue archive We have to remember that our magazine is released monthly, so we need an archive page where we can collect all of the past issues. The issue archive page, which can be reached by clicking on the main navigation menu, will again show some information from the latest issue. (We need to sell our articles!) The rightmost column of the template will show all of the covers for the current or selected year. At the bottom of the page, we will create a box with links to the past issues grouped by years and months. The staff profile page The staff profile page will display information from a staff profile, such as his avatar, biography, and the latest articles that he has written. The staff profile page will have three columns. The first column will show information regarding the editor's profile, the middle column will show all of the articles the editor has written (paged five by five) and the third will be used for banners or other images. >> Continue Reading: Creating a Design with eZ Publish 4 Templating System: Part 2
Read more
  • 0
  • 0
  • 2522

article-image-content-modeling
Packt
22 Oct 2009
12 min read
Save for later

Content Modeling

Packt
22 Oct 2009
12 min read
Organizing content in a meaningful way is nothing new. We have been doing it for centuries in our libraries—the Dewey decimal system being a perfect example. So, why can't we take known approaches and apply them to the Web? The main reason is that a web page has more than two dimensions. A page on a book might have footnotes or refer to other pages, but the content only appears in one place. On a web page, content can directly link to other content and even show a summary of it. It goes way beyond just the content that appears on the page—links, related content, reviews, ratings, etc. All of this brings extra dimensions to the core content of the page and how it is displayed. This is why it's so important to ensure your content model is sound. However, there is no such thing as the "right" content model. Each content model can only be judged on how well it achieves the goals of the website now and in the future. The Purpose of a Content Model The idea of a content model is new, but it has similarities to both a database design and an object model. The purpose of both of these is to provide a foundation for the logic of the operation. With a database design, we want to structure the data in a meaningful way to make storage and retrieval effective. With an object model, we define the objects and how they relate to each other so that accessing and managing objects is efficient and effective. The same applies to a content model. It's about structuring the content and the relationships between the classes to allow the content to be accessed and displayed easily. The following diagram is a simple content model that shows the key content classes and how they relate to each other. In this diagram, we see that resources belong to a collection which in turn belongs to a context. Also, a particular resource can belong to more than one collection. As stated before, there is no such thing as the "right" model. What we are trying to achieve is the most "effective" model for the project at hand. This means coming up with a model that will provide the most effective way of organizing content so that it can be easily displayed in the manner defined in the functional specification. The way a content model is defined will have an impact on how easy it is to code templates, how quickly the code will run, how easy it is for the editors to input content, and also how easy it is to change down the track. From experience, rarely is a project completed and then never touched again. Usually, there are changes, modifications, updates, etc. down the track. If the model is well structured, these changes will be easy, if not, they can require a significant amount of work to implement. In some cases, the project has to be rebuilt entirely and content re-entered to achieve the goals of the client. This is why the model is so important. If done well, it means the client pays less and has a better-running solution. A poor model will take longer to implement and changes will be more difficult to implement. What Makes a Good Model? It's not easy to define exactly what makes a good model. Like any form of design, simplicity is the key. The more the elements, the more complex it gets. Ideally, a model should be technology independent, but there are certain ways in which eZ publish operates that can influence how we structure the content model. Do we always need a content model? No, it depends on the scale of the project. Smaller projects don't really need a formal model. It's only when there are specific relationships between content classes that we need to go to the effort of creating a model. For example, a basic website that has a number of sections, e.g., About Us, Services, Articles, Contact, etc., doesn't need a model. There's no need for an underlying structure. It's just content added to sections. The in-built content classes in eZ publish will be enough to cater for that type of site. It's when the content itself has specific relationships e.g., a book belongs to a category or a product belongs to a product group, which belongs to a division of the business—this is when you need to create a model to capture the objects and the relationships between them. T o start with, we need to understand the content we are dealing with. The broad categories are existing/known content and new content. If we know the structure of the content we are dealing with and it already exists, this can help to shape the model. If we are dealing with content that doesn't exist yet (i.e. is to be written or created for this project) it's harder to know if we are on the right track. For example, when dealing with products, generally the product data will already exist in a database or ERP system. This gives us a basis from which to work. We can establish the structure of the content and the relationships from the existing data. That doesn't mean that we simply copy what's there, but it can guide us in the right direction. Sometimes the structure of the data isn't effective for the way it's to be displayed on the Web or it's missing elements. (As a typical example, in a recent project, the product data was stored in three places—the core details were in the Point of Sale system, product details and categorization were in a spreadsheet, and the images were stored on a file system.) So, the first step is to get an understanding of all the content we are dealing with. If the content doesn't exist as yet, at least get some examples of what it is likely to be. Without knowing what you are dealing with, you can't be sure your model will accommodate everything. T his means you'll need to allow for modifications down the track. Of course we want to minimize this but it's not always possible. Clients change their minds so the best we can do is hope that our model will accommodate what we think are the likely changes. This really can only be done through experience. There are patterns in content as well as how it's displayed. Through these patterns e.g., a related-content box on each page, we can try to foresee the way things might alter and build room for this into the model. A good example was that on a recent project, for each object, there was the main content but there were also a number of related objects (widgets) that were to be displayed in the right-hand column of the page. Initially, the content class defined the specific widgets to be associated with the object. The table below contains the details of a particular resource (as shown in the previous content model). It captures the details of the "research report" resource content class. Attribute Type Notes Title Text line Short Title Text Line If present, will be used in menus and URLs Flash Flash Navigator object Hero Image Image (displays if no flash) Caption Rich text   Body* Rich Text   Free Form Widgets Related Objects Select one or more Multimedia Widget Related Object Select one This would mean that when the editor added content, they would pick the free-form widgets and then the multimedia widget to be associated with the research report. Displaying the content would be straightforward as from the parent object we would have the object IDs for each widget. The idea is sound but lacks flexibility. It would mean that the order in which the object was added would dictate the order in which it was displayed. It also means that if the editor wants to choose to add a different type of widget, they couldn't unless the model was changed, i.e., another attribute was added to the content class. We updated the content class as follows: Attribute Type Notes Title* Text line Short Title Text Line If present, will be used in menus and URLs Flash Flash Navigator object Hero Image Image (displays if no flash) Caption Rich text   Body* Rich Text   Widgets Related Objects Select one or more This approach is less strict and provides more flexibility. The editor can choose any widget and also select the order. In terms of programming the template, there's the same amount of work. But, if we decide to add another widget type down the track, there's no need to update the content class to accommodate it. Does this mean that anytime we have a related object we should use the latter approach? No, the reason we did it in this situation is that the content was still being written as we were creating the model, and there was a good chance that once the content was entered and we saw the end result, the client was going to say something like "can we add widget x" to the right-hand column of a context object? In a different project, in which a particular widget should only be related to a particular content class, it's better to enforce the rule by only allowing that widget to be associated with that content class. Defining a Content Model The process of creating a content model requires a number of steps. It's not just a matter of analyzing the content; the modeler also needs to take into consideration the domain, users, groups, and the relationships between different classes within the model. To do this, we start with a walkthrough of the domain. Step 1: Domain Walkthrough The client and domain experts walk us through the entire project. This is a vital part of the process. We need to get an understanding of the entire system, not just the part that is captured in the final solution. The model that we end up creating may need to interact with other systems and knowing what they are and how they work will inform the shape of the model. A good example is with e-commerce systems, any information captured on a sale will eventually need to be entered into the existing financial system (whether is it automated or manual). Without an understanding of the bigger picture, we lack the understanding of how the solution we are creating will fit in with what the business does. That's when there is an existing business process. Sometimes there is no business process and the client is making things up as they go along, e.g. they have decided to do online shopping but they have never dealt with overseas orders so don't know how that will work and have no idea how they would deal with shipping costs. One of the typical problems that will surface during the domain walkthrough is that the client will try to tell you how they want the solution to work. By doing this, they are actually defining the model and interactions. This is something to be wary of. It is unlikely that they would be aware of how best to structure a solution; what you want to be asking is what they currently do, what's their current business process. You want to deal with facts that are in existence so that you can decide how best to model the solution. To get the client back on track ask questions like: How do you currently do "it" (i.e. the business process)? What information to you currently capture? How do you capture that information? What format is that information in? How often is the information updated? Who updates it? This gives you a picture of what is currently happening. Then you can start to shape the model to ensure that you are dealing with the real world, not what the client thinks they want. Sometimes they won't be able to answer the question and you'll have to get the right person from the business involved to get the answers you want. Sometimes you discover that what the client thought was happening is not really what happens. Another benefit of this process is gaining a common understanding. If both you and the client are in the room when the process for calculating shipping costs is being explained by the Shipping Manager, you'll both appreciate how complex the process is. If the client thinks it's easy, they won't expect it to cost much. If they are in the room when the shipping manager explains there are five different shipping methods and each has its own way of calculating the costs for a shipment based on their own set of international zones, you know modeling that part of the system is not going to be straightforward unlike what the client initially thought. What this means is that the domain walkthrough gives you a sense of what's real, not what people think the situation is. It's the most important part of the process. Assumptions that "shipping costs" are straightforward, so you don't need to worry about that, can be a disaster later down the track when you find out it's not the case. Also, don't necessarily rely on requirements documents (unless you have written them yourself). A statement in a requirements document may not reflect what really happens; that's why you want to make sure you go through everything to confirm that you have all the facts. Sometimes, a particular requirement can be stated in the document but when you go through it in more detail, ask a few questions, pose a few scenarios, the client changes their mind on what it is that they really want as they realize what they thought they wanted is going to be difficult or expensive to implement. Or, you put an alternative approach to them and they are happy to achieve the same result in a different manner that is easier to implement. This is a valuable way to work out what's real and what really matters.
Read more
  • 0
  • 0
  • 2522

article-image-integrating-zk-other-frameworks
Packt
20 Oct 2009
7 min read
Save for later

Integrating ZK with Other Frameworks

Packt
20 Oct 2009
7 min read
Integration with the Spring Framework Spring is one of the most complete lightweight containers, which provides centralized, automated configuration, and wiring of your application objects. It improves your application's testability and scalability by allowing software components to be first developed and tested in isolation, then scaled up for deployment in any environment. This approach is called the POJO (Plain Old Java Object) approach and is gaining popularity because of its flexibility. So, with all these advantages, it's no wonder that Spring is one of the most used frameworks. Spring provides many nice features: however, it works mainly in the back end. Here ZK may provide support in the view layer. The benefit from this pairing is the flexible and maturity of Spring together with the easy and speed of ZK. Specify a Java class in the use attribute of a window ZUL page and the world of Spring will be yours. A sample ZUL looks like: <?xml version="1.0" encoding="UTF-8"?> <p:window xsi_schemaLocation="http://www.zkoss.org/2005/zul http://www.zkoss.org/2005/zul " border="normal" title="Hello!" use="com.myfoo.myapp.HelloController"> Thank you for using our Hello World Application. </p:window> The HelloController points directly to a Java class where you can use Spring features easily. Normally, if a Java Controller is used for a ZUL page it becomes necessary sooner or later to call a Spring bean. Usually in Spring you would use the applicationContext like: ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); UserDAO userDAO = (UserDAO) ctx.getBean("userDAO"); Then the userDAO is usable for any further access. In ZK there is a helper class SpringUtil. It wrapps the applicationContext and simplifies the code to: UserDAO userDAO = (UserDAO) SpringUtil.getBean("userDAO"); Pretty easy, isn't it? Let us examine an example. Assume we have a small web application that gets flight data from a flight table. The web.xml file looks like: <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xsi_schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>IRT-FLIGHTSAMPLE</display-name> <filter> <filter-name>hibernateFilter</filter-name> <filter-class> org.springframework.orm.hibernate3.support.OpenSessionInViewFilter </filter-class> </filter> <filter-mapping> <filter-name> hibernateFilter </filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext-jdbc.xml ,classpath:applicationContext-dao.xml ,classpath:applicationContext-service.xml ,classpath:applicationContext.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <session-config> <!-- Default to 30 minute session timeouts --> <session-timeout>30</session-timeout> </session-config> <mime-mapping> <extension>xsd</extension> <mime-type>text/xml</mime-type> </mime-mapping> <servlet> <description> <![CDATA[The servlet loads the DSP pages.]]> </description> <servlet-name>dspLoader</servlet-name> <servlet-class> org.zkoss.web.servlet.dsp.InterpreterServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>dspLoader</servlet-name> <url-pattern>*.dsp</url-pattern> </servlet-mapping> <!-- ZK --> <listener> <description> Used to cleanup when a session is destroyed </description> <display-name>ZK Session Cleaner</display-name> <listener-class> org.zkoss.zk.ui.http.HttpSessionListener </listener-class> </listener> <servlet> <description>ZK loader for ZUML pages</description> <servlet-name>zkLoader</servlet-name> <servlet-class> org.zkoss.zk.ui.http.DHtmlLayoutServlet </servlet-class> <!-- Must. Specifies URI of the update engine (DHtmlUpdateServlet). It must be the same as <url-pattern> for the update engine. --> <init-param> <param-name>update-uri</param-name> <param-value>/zkau</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>zkLoader</servlet-name> <url-pattern>*.zul</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>zkLoader</servlet-name> <url-pattern>*.zhtml</url-pattern> </servlet-mapping> <servlet> <description>The asynchronous update engine for ZK </description> <servlet-name>auEngine</servlet-name> <servlet-class> org.zkoss.zk.au.http.DHtmlUpdateServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>auEngine</servlet-name> <url-pattern>/zkau/*</url-pattern> </servlet-mapping> <welcome-file-list id="WelcomeFileList"> <welcome-file>index.zul</welcome-file> </welcome-file-list> </web-app> Furthermore let's have a small ZUL page that has the interface to retrieve and show flight data: <?xml version="1.0" encoding="UTF-8"?> <p:window xsi_schemaLocation="http://www.zkoss.org/2005/zul http://www.zkoss.org/2005/zul " id="query" use="com.myfoo.controller.SampleController"> <p:grid> <p:rows> <p:row> Airline Code: <p:textbox id="airlinecode"/> </p:row> <p:row> Flightnumber: <p:textbox id="flightnumber"/> </p:row> <p:row> Flightdate: <p:datebox id="flightdate"/> </p:row> <p:row> <p:button label="Search" id="search"/> <p:separator width="5px"/> </p:row> </p:rows> </p:grid> <p:listbox width="100%" id="resultlist" mold="paging" rows="21" style="font-size: x-small;"> <p:listhead sizable="true"> <p:listheader label="Airline Code" sort="auto" style="font-size: x-small;"/> <p:listheader label="Flightnumber" sort="auto" style="font-size: x-small;"/> <p:listheader label="Flightdate" sort="auto" style="font-size: x-small;"/> <p:listheader label="Destination" sort="auto" style="font-size: x-small;"/> </p:listhead> </p:listbox> </p:window> As you can see, the use attribute of the ZUL page is the link to the SampleController. The SampleController handles and controls the objects. Let's have a short look at the SampleController sample code: public class SampleController extends Window { private Listbox resultlist; private Textbox airlinecode; private Textbox flightnumber; private Datebox flightdate; private Button search; /** * Initialize the page */ public void onCreate() { // Components resultlist = (Listbox) this.getPage().getFellow("query").getFellow("resultlist"); airlinecode = (Textbox) this.getPage().getFellow("query").getFellow("airlinecode"); flightnumber = (Textbox) this.getPage().getFellow("query").getFellow("flightnumber"); flightdate = (Datebox) this.getPage().getFellow("query").getFellow("flightdate"); search = (Button) this.getPage().getFellow("query").getFellow("search"); search.addEventListener("onClick", new EventListener() { public void onEvent(Event event) throws Exception { performSearch(); } }); } /** * Execute the search and fill the list */ private void performSearch() { //(1) List<Flight> flightlist = ((FlightService) SpringUtil.getBean("flightService")). getFlightBySearch(airlinecode.getValue(), flightnumber.getValue(), flightdate.getValue(),""); resultlist.getItems().clear(); for (Flight aFlightlist : flightlist) { // add flights to list } } } /* (1)-shows the integration of the Spring Bean*/ Just for completion the context file for Spring is listed here with the bean that is called. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="txProxyTemplate" abstract="true" class="org.springframework.transaction. interceptor.TransactionProxyFactoryBean"> <property name="transactionManager"> <ref bean="transactionManager"/> </property> <property name="transactionAttributes"> <props> <prop key="save*">PROPAGATION_REQUIRED</prop> <prop key="add*">PROPAGATION_REQUIRED</prop> <prop key="remove*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> <bean id="flightService" parent="txProxyTemplate"> <property name="target"> <bean class="com.myfoo.services.impl.FlightServiceImpl"> <property name="flightDAO"> <ref bean="flightDao"/> </property> </bean> </property> </bean> </beans> In short we have learned how to use Spring with ZK and about the configurations. We have seen that the integration is quite smooth and also powerful.
Read more
  • 0
  • 0
  • 2521

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

Getting Started with Internet Explorer Mobile

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

Background Animation

Packt
19 Dec 2013
4 min read
(For more resources related to this topic, see here.) Background-color animation Animating the background color of an element is a great way to draw our user's eyes to the object we want them to see. Another use for animating the background color of an element is to show that something has happened to the element. It's typically used in this way if the state of the object changes (added, moved, deleted, and so on), or if it requires attention to fix a problem. Due to the lack of support in jQuery 2.0 for animating background-color, we'll be using jQuery UI to give us the functionality we need to create this effect. Introducing the animate method The animate() method is one of the most useful methods jQuery has to offer in its bag of tricks in the animation realm. With it, we’re able to do things like, move an element across the page or alter and animating the properties of colors, backgrounds, text, fonts, the box model, position, display, lists, tables, generated content, and so on. Time for action – animating the body background-color Following the steps below, we're going to start by creating an example that changes the body background color. Start by creating a new file (using our template) called background-color.html and save it in our jquery-animation folder. Next, we'll need to include the jQuery UI library by adding this line directly under our jQuery library by adding this line: <script src = "js/jquery-ui.min.js"></script> A custom or stable build of jQuery UI can be downloaded from http://jqueryui.com, or you can link to the library using one of the three Content Delivery Networks (CDN) below. For fastest access to the library, go to http://jqueryui.com, scroll to the very bottom and look for the Quick Access section. Using the jQuery UI library JS file there will work just fine for our needs for the examples in this article. Media Template: http://code.jquery.com Google: http://developers.google.com/speed/libraries/devguide#jquery-ui Microsoft: http://asp.net/ajaxlibrary/cdn.ashx#jQuery_Releases_on_the_CDN_0 CDNJS: http://cdnjs.com/libraries/jquery Then, we'll add the following jQuery code to the anonymous function: var speed = 1500; $( "body").animate({ backgroundColor: "#D68A85" },speed); $( "body").animate({ backgroundColor: "#E7912D" },speed); $( "body").animate({ backgroundColor: "#CECC33" },speed); $( "body").animate({ backgroundColor: "#6FCD94" },speed); $( "body").animate({ backgroundColor: "#3AB6F1" },speed); $( "body").animate({ backgroundColor: "#8684D8" },speed); $( "body").animate({ backgroundColor: "#DD67AE" },speed); What just happened? First we added in the jQuery UI library to our page. This was needed because of the lack of support for animating the background color in the current version of jQuery. Next, we added in the code that will animate our background. We then set the speed variable to 1500 (milliseconds) so that we can control the duration of our animation. Lastly, using the animate() method, we set the background color of the body element and set duration to the variable we set above named speed. We duplicated the same line several times, changing only the hexadecimal value of the background color. The following screenshot is an illustration of colors the entire body background color animates through: Chaining together jQuery methods It's important to note that jQuery methods (animate() in this case) can be chained together. Our code mentioned previously would look like the following if we chained the animate() methods together: $("body")   .animate({ backgroundColor: "#D68A85"}, speed)  //red   .animate({ backgroundColor: "#E7912D"}, speed)  //orange   .animate({ backgroundColor: "#CECC33"}, speed)  //yellow   .animate({ backgroundColor: "#6FCD94"}, speed)  //green   .animate({ backgroundColor: "#3AB6F1"}, speed)  //blue   .animate({ backgroundColor: "#8684D8"}, speed)  //purple   .animate({ backgroundColor: "#DD67AE"}, speed); //pink Here's another example of chaining methods together: (selector).animate(properties).animate(properties).animate(properties) Have a go hero – extending our script with a loop In this example we used the animate() method and with some help from jQuery UI, we were able to animate the body background color of our page. Have a go at extending the script to use a loop, so that the colors continually animate without stopping once the script gets to the end of the function. Pop quiz – chaining with the animate() method Q1. Which code will properly animate our body background color from red to blue using chaining? $("body")   .animate({ background: "red"}, "fast")   .animate({ background: "blue"}, "fast"); $("body")   .animate({ background-color: "red"}, "slow")   .animate({ background-color: "blue"}, "slow"); $("body")   .animate({ backgroundColor:"red" })   .animate({ backgroundColor:"blue" }); $("body")   .animate({ backgroundColor,"red" }, "slow")   .animate({ backgroundColor,"blue" }, "slow");
Read more
  • 0
  • 0
  • 2520

article-image-extending-opencms-developing-custom-widget
Packt
16 Oct 2009
8 min read
Save for later

Extending OpenCms: Developing a Custom Widget

Packt
16 Oct 2009
8 min read
Structured Content Types Support for structured content is a key feature of OpenCms. Structured content types allow different templates to be used to re-skin a site, or to share content with other sites that have a different look. Structured content types are defined by creating XSD schemas and placing them into modules. Once a new content type has been defined, the Workplace Explorer provides a user interface to create new instances of the content and allows it to be edited. There are some sample content types and templates that come with the Template One group of modules. These content types are very flexible and allow a site to be built using them right away. However, they may not fit our site requirements. In general, site requirements and features will determine the design of the structured content types and templates that need to be developed. BlogEntry Content Type For designing a blog website it is required that the content type contains blog entries. The schema file for the BlogEntry content type looks like the following : <!-- ======================================================== Content definition schema for the BlogEntry type ========================================================== --> <!-- 1. Root Element --> <xsd:schema elementFormDefault="qualified"> <!-- 2. Define the location of the schema location --> <xsd:include schemaLocation="opencms://opencms-xmlcontent.xsd"/> <!-- 3. Root element name and type of our XML type --> <xsd:element name="BlogEntrys" type="OpenCmsBlogEntrys"/> <!-- 4. Definition of the type described above --> <xsd:complexType name="OpenCmsBlogEntrys"> <xsd:sequence> <xsd:element name="BlogEntry" type="OpenCmsBlogEntry" minOccurs="0" maxOccurs="unbounded"/> </xsd:sequence> </xsd:complexType> <!-- 5. Data field definitions --> <xsd:complexType name="OpenCmsBlogEntry"> <xsd:sequence> <xsd:element name="Title" type="OpenCmsString" minOccurs="1" maxOccurs="1" /> <xsd:element name="Date" type="OpenCmsDateTime" minOccurs="1" maxOccurs="1" /> <xsd:element name="Image" type="OpenCmsVfsFile" minOccurs="0" maxOccurs="1" /> <xsd:element name="Alignment" type="OpenCmsString" minOccurs="1" maxOccurs="1" /> <xsd:element name="BlogText" type="OpenCmsHtml" minOccurs="1" maxOccurs="1" /> <xsd:element name="Category" type="OpenCmsString" minOccurs="0" maxOccurs="10" /> </xsd:sequence> <!-- 6. locale attribute is required --> <xsd:attribute name="language" type="OpenCmsLocale" use="required"/> </xsd:complexType> <!—optional code section --> <xsd:annotation> <xsd:appinfo> <!-- Mappings allow data fields to be mapped to content properties --> <mappings> <mapping element="Title" mapto="property:Title" /> <mapping element="Date" mapto="attribute:datereleased" /> </mappings><!-- Validation rules for fields --> <validationrules> <rule element="BlogText" regex="!.*[Bl]og.*" type= "warning" message="${key.editor.warning.BlogEntry. dontallowblog|${validation.path}}"/> </validationrules> <!-- Default values for fields --> <defaults> <default element="Date" value="${currenttime}"/> <default element="Alignment" value="left"/> </defaults> <!-- user interface widgets for data fields --> <layouts> <layout element="Image" widget="ImageGalleryWidget"/> <layout element="Alignment" widget="SelectorWidget" configuration="left|right|center" /> <layout element="Category" widget="SelectorWidget" configuration="silly|prudent|hopeful|fearful| worrisome|awesome" /> <layout element="BlogText" widget="HtmlWidget"/> </layouts> <!-- UI Localization --> <resourcebundle name="com.deepthoughts.templates.workplace"/> <!-- Relationship checking --> <relations> <relation element="Image" type="strong" invalidate="node" /> </relations> <!-- Previewing URI --> <preview uri="${previewtempfile}" /> <!-- Model Folder for content models --> <modelfolder uri="/system/modules/com.deepthoughts.templates /defaults/" /> </xsd:appinfo> </xsd:annotation> </xsd:schema> The BlogEntry content type file is named as blogentry.xsd and it placed in the folder named schemas in modules. Designing a Custom Widget Referring to the highlighted code in BlogEntry content type schema file we can see that the category field is populated from a drop-down list provided by SelectorWidget. The SelectorWidget obtains its values from the static configuration string defined within the blog schema file. This design is problematic as we would like category values to be easily changed or added. Ideally, the list of category values should be able to be updated by site content editors. Fortunately, we can create our own custom widget to handle this requirement. An OpenCms widget is a Java class that implements the I_CmsWidget interface, located in the org.opencms.widgets package. The interface contains a number of methods that must be implemented. First there are some methods dealing with instantiation and configuration of the widget: newInstance: This returns a new instance of the widget. setConfiguration: This method is called after the widget has been initialized to configure it. The configuration information is passed as a string value coming from the declaration of the widget within the schema file of the content type using it. getConfiguration: This is called to retrieve the configuration information for the widget. Next, there are some methods used to handle the rendering. These methods are called by widget enabled dialogs that might be used in a structured content editor or an administration screen. The methods provide any Javascript, CSS, or HTML needed by the widget dialogs: getDialogIncludes: This method is called to retrieve any Javascript or CSS includes that may be used by the widget. getDialogInitCall: This method may return Javascript code that performs initialization or makes calls to other Javascript initialization methods needed by the widget. getDialogInitMethod: This method may return Javascript code containing any functions needed by the widget. getDialogHtmlEnd: This method is called at the end of the dialog and may be used to return an HTML or Javascript needed by the widget. getDialogWidget: This method returns the actual HTML and Javascript used to render the widget along with its values. getHelpBubble: This method returns the HTML for displaying the help icon relating to this widget. getHelpText: This method returns the HTML for displaying the help text relating to this widget. Lastly, there are some methods used to get and set the widget value: getWidgetStringValue: This method returns the value selected from the widget. setEditorValue: This method sets the value into the widget. All these methods have base implementations in the A_CmsWidget class. In most cases, the base methods do not need to be overridden. As such, we will not cover all the methods in detail. If it is necessary to override the methods, the best way to get an idea of how to implement them is to look at the code using them. All widgets are used in dialog boxes which have been enabled for widgets, by implementing the I_CmsWidgetDialog interface. There are two general instances of these dialogs, one is used for editing structured XML content, the other is found in any dialog appearing in the Administration View. The two classes implementing this interface are: org.opencms.workplace.CmsWidgetDialog org.opencms.workplace.editors.CmsXmlContentEditor The CmsWidgetDialog class is itself a base class, which is used by all dialogs found in the Administrative View. Before designing a new widget, it is useful to examine the existing widget code. The default OpenCms widgets can be found in the org.opencms.widgets package. All the widgets in this package subclass the A_CmsWidget class mentioned earlier. Often, a new widget design may be subclassed from an existing widget. Designing the Widget As mentioned earlier, we would like to have a widget that obtains its option data values dynamically rather than from a fixed configuration string value. Rather than create a widget very specific to our needs, we will use a flexible design where the data source location can be specified in the configuration parameter. The design will allow for other data sources to be plugged into the widget. This way, we can use a single widget to obtain dynamic data from a variety of sources. To support this design, we will use the configuration parameter to contain the name of a Java class used as a data source. The design will specify a pluggable data source through a Java interface that a data source must implement. Furthermore, a data source can accept parameters via the widget configuration string. With this design, an example declaration for a widget named CustomSourceSelectWidget would look like this: <layout element="Category" widget="CustomSourceSelectWidget" configuration="source='com.widgets.sources.MySource'| option1='some config param'| option2='another param'" /> This declaration would appear in the schema of a content type, using the widget as covered earlier. The configuration parameter consists of name/value pairs, delimited by the vertical bar character. Each name/value pair is separated by the equal to sign and the value is always enclosed in single quotes. The design requires that at least the source parameter be specified. Additional parameters will depend upon the specific data source being used. The example declaration specifies that the data field named Category will use the CustomSourceSelectWidget widget for its layout. The configuration parameter contains the name of the Java class to be used to obtain the data source. The data source will receive the two parameters named option1 and option2 along with their values. Next, lets move on to the code to see how this all gets implemented.
Read more
  • 0
  • 0
  • 2519

article-image-iphone-customizing-our-icon-navigation-bar-and-tab-bar
Packt
09 Dec 2011
7 min read
Save for later

iPhone: Customizing our Icon, Navigation Bar, and Tab Bar

Packt
09 Dec 2011
7 min read
  (For more resources on iPhone, see here.) The application icon and essential interaction elements such as the Navigation Bar and Tab Bar are crucial for the success of our work. The user will be tapping the icon every time they go to use our app, and interact with our navigation elements throughout their entire experience in our application. If we want success, we must focus on making these components attractive and functional. Attention to detail and the presentation of these pieces will be key, and we'll need to produce our best work if we want to stand out in a sea of apps. Designing an application icon and preparing it for the user home screen It's often said that a book shouldn't be judged by its cover, but the harsh reality of mobile development is that an app is often judged by its icon. This rounded rectangle will appear on the home screen of every user, and it's important that we create something that is attractive and also a good indication as to what the user should expect after downloading our application. In this recipe, we'll create a strategy for successful app icon design. Getting ready Adobe Photoshop will be our primary tool in the design of our app icon. It may also be helpful to grab some paper and a pencil so that we can sketch out any concepts we may have before we begin working on our computer. How to do it... The application icon is a primary component of any work. Appearing in the App Store, on a user's home screen, in Spotlight searches, and more, it's an important part of our job. Let's take a look at several steps that will be useful in the creation of our app icon: We should start by with either a rough sketch or Photoshop mockup of our intended design. We should create this mock up at several sizes to help represent the different resolutions at which our icon will be viewed. After we've developed an idea that we believe is going to scale well, its time to sit down in Photoshop or Illustrator and begin work on our icon. At this point, we need to determine what size canvas we want to design our icon on. Apple requires that our icon be available at a variety of sizes, with a 512 by 512 pixel square currently being the largest required format, but we should be prepared in case this requirement changes in the future and design our icon accordingly. There are two different ways we can go about making our icon "future proof". We can go about designing the icon in a vector format using an application like Adobe Illustrator. Vector drawings will always be the best way to ensure that our icon will scale to any size, but they can be a bit more difficult to create. If we're more comfortable using a raster image manipulation program like Photoshop, it's best to create our icon at a resolution well above what we'll ever need for the App Store, starting with a canvas of 4096 by 4096 pixels square or greater. Such a large raster size will give us a piece of art that will print comfortably on sizes as large as 13 inches when printed at 300 DPI, while also easily scaling down to whatever size we need for the App Store. Once we've decided which format we're most comfortable with, its time to go about creating our icon. Once we've completed our icon, it is time to prepare it for inclusion into our application. This icon should then be named apple-touch-icon.png and placed inside of our application bundle. iOS will then automatically add the glare effect to the top half of the icon, as seen throughout the interface. The Info.plist is a file that allows us to customize a bunch of different application attributes. We'll learn how to use it to remove the icon gloss effect in an upcoming recipe titled Removing the app icon's gloss effect. After finishing our icon, we may also want to run a small focus group, much like we would in order to gain feedback on our user interface design.We can quickly set up a simple website with a form asking for opinions on our design or even email an image of the icon to friends and family in order to facilitate feedback. When looking to gather opinion on our icon, we want to better understand a user's first impression of our icon. For a good portion of purchase decisions, the icon may be the only bit of insight into our app that the user has before tapping the buy button. We want to make sure that on first impression, the typical user associates our icon with quality, simplicity, and value. If our icon looks amateur, users probably won't consider our application for purchase. How it works... Icon design is tough, primarily because we're required to design a small square that represents our application's purpose, quality, and value. It's truly a challenge to design something that works well at 512 pixels and 27 pixels. Let's take a look at how the steps above work together to create a good icon. Resolution flexibility is arguably the difficult part of icon design, as our work needs to look great at 512 pixels by 512 pixels and at 27 by 27 pixels. Small details that look great at a high resolution can really make an icon indecipherable when scaled down to the lowest resolution required: In the above screenshot, we can quickly see how an icon becomes less legible as it decreases in size. It's necessary to provide the icon to Apple in several different sizes, which can vary depending upon the iOS device we're developing our application for and the current operating system requirements from Apple. These file sizes have varied significantly throughout the life of iOS, so we should verify the current requirements in the iOS Development Center before their creation. Sebastiaan De With keeps an excellent Photoshop file for iOS icon design, complete with resolution requirements, which he updates every time Apple changes the icon requirements. We can find the file here at http://blog.cocoia.com/2010/iphone-4-icon-psd-file/ and it should reference it while designing a new icon. When building our icon, we should really take time to think about what our icon should look like and what users will think when they first set eyes on it in the App Store. This set process works because it systematically creates a piece of work that will be optimized for the various needs of iOS. There's more... It may take a bit of practice to get a firm grasp on what makes a great or poor icon. Here are a few helpful ideas, just in case we're struggling to develop an icon that we're happy with. Dropping the text We should always refrain from including a great deal of text in our app icon. Text tends to become illegible when scaled down to small resolutions such as 27 x 27, so it is often best to keep text out of our icon. If we absolutely must include text in our icon, we should use short words that are large in size and in a bold typeface. Great gradients From an art design perspective, we'll probably be including an artistic gradient in our icon to offer the illusion of brushed metal or progressive lighting. But choosing a strong color palate for a gradient can be difficult. Dezigner Folio has created a large library of fresh, modern gradients that they've offered up for free use in any project. For the entire library, feel free to visit their website at http://www.dezinerfolio.com/2007/05/03/ultimate-web-20-gradients-v30-release. If all else fails.... If we're having a rough time with icon design and all else fails, we can always hire a freelance artist or design firm to help out with the production of our application icon. A quick search of Google can help us find a multitude of artists who have become specialists in the field of icon design. Finding a talented designer can actually be quite affordable, with many freelance artists charging a hundred dollars or less for a high quality icon. As icons can be produced in Photoshop, local graphic designers or students can help out at affordable rates as well.  
Read more
  • 0
  • 0
  • 2514
article-image-drupal-6-attachment-views-page-views-and-theming
Packt
24 Feb 2010
9 min read
Save for later

Drupal 6: Attachment Views, Page Views, and Theming

Packt
24 Feb 2010
9 min read
Looking at just about anything worth doing, a question will often arise beginning with the words, "How do I." Often the challenge can seem daunting. Then, one finally intuits, discovers or otherwise stumbles upon the answer and simultaneously is offered several alternative opinions, each being offered as the best way to accomplish the same goal. This is the case whether planning a vacation route, taking a photograph, or creating part or all of an application. There are a number of ways to accomplish what we will be doing in the article. If you spend any time on the Drupal IRC (Internet Relay Chat) channels, you will most likely receive varying opinions as to the best approach and, perhaps, come away more confused than when you started. Sometimes, there is no clear answer. One approach would be to write custom code. Another might be to use the Panels module. Each approach is valid, and has different pros and cons in terms of features, effort, learning curve, and time. Here, we're going to face each challenge in the same way, with attachment views, which means less coding, less time, and a smaller learning curve. A view is originally a relational database term, referring to a temporary arrangement of information in the database so that it can be presented in a meaningful way which is different than the underlying table layout. The Views module accomplishes the same thing, and provides the glue to tie itself in to the rest of Drupal and, especially, the ability to theme the result with templates. In other words, it gives you the ability to look at Drupal content in a way you would otherwise be unable to (without custom code). What is an Attachment view? A view is the dynamic display of one or more pieces of related content based on one or more criterion. What does that mean in practice? Let's consider a simple example. Let's say we have created a number of nodes of the content type 'Story' and assign one or more taxonomy terms to each. Having done that, we want to be presented with a list of teasers for each Story that has 'travel' as one of its taxonomy terms. It's a fairly common requirement. If you're familiar with Joomla!, for example, it could be accomplished by means of a Section or Category Blog page. The fact, though, is that the architecture that makes Drupal so extensible results in there being no manner in which to accomplish this using a core module. Enter the Views module, which will allow us to specify that we want a page on which we want to view x number of nodes, their selection based on certain criteria, which in this case will be nodes containing the taxonomy term 'travel'. That, in a nutshell, describes views at their simplest. Now, how about Attachment views? Well, to continue using the same example, let's say that our requirement has changed, and we don't always want a page based on every node having to do with travel, but want to be able to select destinations from a list of regions shown on the same page, as illustrated in the following figure. The box on the left shows the available travel regions, each of which is a taxonomy term, with Asia having been chosen. The boxes on the right are node teasers, each of which has Asia among its taxonomy terms. How can we accomplish this? One method would be to code a custom page in PHP and display it. That would work, but it would also set the page in stone to some extent, bypassing the flexibility that Drupal provides. We could also create a menu of destination regions and put it in the sidebar as a block. That would work too, but the menu would not be dynamic, and would have to be edited each time a region was added, changed, or removed. One further option would be to have two separate views. How can we have two views though? We could create one as a block, but let's say that the design calls for the selection choices to be in the content area of the page. So, that means we need to find a way to have both views as content. Enter Attachment views. Reviewing the view requirements The business for which our website is being built is a commercial builder's. As with most construction businesses, subcontractors represent the major source of labor. On this site, Subcontractors will be the user type that will need to register, in order to subsequently review jobs and bid for them. There will be other authenticated user types, such as management, job supervisors and admin, but they will have user records created for them and will not need to register. Customers will be anonymous users. To that end, a custom profile has been created for subcontractors, to capture the necessary information. We're using the content_profile module so that each subcontractor profile will be a node. We are going to have a menu from which the user will select a contractor for which the details will be displayed. For a given view, we can create various displays. A view to be displayed like a node will have a Page display—'Page' can be thought of as a web page—and one that is to be displayed as a block will have a Block display. Considering our menu of subcontractors, and the display of a subcontractor's details, in conjunction with the terms 'Page display' and 'Attachment display', the reasonable inference is that the Attachment view will be the menu-style list of subcontractors, and the Page display will be the subcontractor details, the page being larger than an attachment, and the details being larger than the menu. However, that's not necessarily the case, and in subsequent examples we'll invert that assignment of content to display. The description of the subcontractor list may bring the thought 'Block' to mind. Often a block can be used in place of an Attachment display, and in fact, the option to create a Block display in the view is just one selection away from the Attachment type. We're using Attachment displays rather than Block displays because Attachments are not as entity-like in their construction, and are easier to place anywhere within the page content than Blocks, which are more easily placed in regions adjacent to the content area. Attachment views do not include paging as do Page views. We are only going to be showing one subcontractor's details at a time, so there is no paging issue there. However, when we list the subcontractors to select from, there could be dozens, or even hundreds, and that will require us to have paging available for that display, so the Page display for our view will be the subcontractor list. We'll build that first. Activity 2-1–Subcontractor page view The Subcontractor page will allow the user to view the details of a subcontractor chosen from a dynamic list. That is, the list of subcontractors will not be something separate that requires editing whenever a subcontractor is added or removed, and the list will be in the content area of the page and not in a navigational menu. Let's create a new view. We're going to create a node view named subs, as shown in the following screenshot: Click Next and the Views panel is presented. The panel will allow us to customize the view settings. We'll start by creating a Page display for the view. The Views page will always attempt to provide you with a real-time preview based on your settings. Often, the settings are being established in an order that is not conducive to creating the preview, because some information is missing. In that event, you will see a pink warning about this, for example, Fields is the display type but no fields have been chosen. Use the warnings as a way to tweak your memory about what you have left to do, but don't worry about them, as long as there are none remaining when you think you're done. We'll click on Title and change the view title, as shown in the following screenshot. Click Update default display when you are finished. Let's look at some of the other configuration options in Basic Settings. Leave the style settings as it is. A style plugin isn't needed, because the view will eventually be themed, and since it will only be showing one record it doesn't require a table or grid. We'll also leave the Row style set as Fields, as we want the profile data to be displayed as a vertical list of fields. Again, changes can be made when the view is themed. We won't use AJAX at this time. We do want to use paging with this display. It's likely that the subcontractor list will be large, and so we'll only want a small amount being shown at one time. We'll change the Use pager setting to "yes", and from the config options choose Mini pager. Leave the More link setting at no, we don't need a More link, and likewise, since each record is a separate subcontractor node, we're not concerned about unique records. As this view is meant only for use by the management of Guild Builders, we'll want to restrict access to it. Change the Access setting to restrict access to a specific role. A role called management has already been created for use by the management staff of Guild Builders. There will probably be more roles added later, such as one for staff and another for the subcontractors themselves. We'll assign access to the management role. We won't be caching the view, nor exposing the form in a block, so we'll leave the settings caching at one and expose form in block at no. There will be a page header and footer, but they can be added later. Empty text won't be an issue, because the node selection will come from a list based on existing nodes. That takes us to the end of the Basic Settings pane. Let's move on to Sort criteria.
Read more
  • 0
  • 0
  • 2513

article-image-methods-animation-effects-jquery-14
Packt
29 Jan 2010
6 min read
Save for later

Methods for Animation Effects with jQuery 1.4

Packt
29 Jan 2010
6 min read
Some of the examples in this article use the $.print() function to print results to the page. Pre-packaged effects These methods allow us to quickly apply commonly-used effects with a minimum of configuration. .show() Display the matched elements. .show([duration][, callback]) Parameters duration (optional): A string or number determining how long the animation will run callback (optional): A function to call once the animation is complete Return value The jQuery object, for chaining purposes. Description With no parameters, the .show() method is the simplest way to display an element. $('.target').show(); The matched elements will be revealed immediately with no animation. This is roughly equivalent to calling .css('display', 'block'), except that the display property is restored to whatever it was initially. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline. When a duration is provided, .show() becomes an animation method. The .show() method animates the width, height, and opacity of the matched elements simultaneously. Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The 'fast' and 'slow' strings can be supplied to indicate durations of 200 and 600 milliseconds, respectively. If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole. We can animate any element, such as a simple image: <div id="clickme">Click here</div><img id="book" src="book.png" alt="" width="100" height="123" /> With the element initially hidden, we can show it slowly. $('#clickme').click(function() {$('#book').show('slow', function() {$.print('Animation complete.');});}); .hide() Hide the matched elements. .hide([duration][, callback]) Parameters duration (optional): A string or number determining how long theanimation will run callback (optional): A function to call once the animation is complete Return value The jQuery object, for chaining purposes. Description With no parameters, the .hide() method is the simplest way to hide an element. $('.target').hide(); The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css('display', 'none'), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline, and then is hidden and shown, it will once again be displayed inline. When a duration is provided, .hide() becomes an animation method. The .hide() method animates the width, height, and opacity of the matched elements simultaneously. When these properties reach 0, the display style property is set to none to ensure that the element no longer affects the layout of the page. Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The 'fast' and 'slow' strings can be supplied to indicate durations of 200 and 600 milliseconds, respectively. If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole. We can animate any element, such as a simple image: <div id="clickme">Click here</div><img id="book" src="book.png" alt="" width="100" height="123" /> With the element initially shown, we can hide it slowly. $('#clickme').click(function() {$('#book').hide('slow', function() {$.print('Animation complete.');});}); .toggle() Display or hide the matched elements. .toggle([duration][, callback]).toggle(showOrHide) Parameters (first version) duration (optional): A string or number determining how long the animation will run callback (optional): A function to call once the animation is complete Parameters (second version) showOrHide: A Boolean indicating whether to show or hide the elements Return value The jQuery object , for chaining purposes. Description With no parameters, the .toggle() method simply toggles the visibility of elements: $('.target').toggle(); The matched elements will be revealed or hidden immediately with no animation. If the element is initially displayed, it will be hidden; if hidden, it will be shown. The display property is saved and restored as needed. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline. When a duration is provided, .toggle() becomes an animation method. The .toggle() method animates the width, height, and opacity of the matched elements simultaneously. When these properties reach 0 after a hiding animation, the display style property is set to none to ensure that the element no longer affects the layout of the page. Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The 'fast' and 'slow' strings can be supplied to indicate durations of 200 and 600 milliseconds, respectively. If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole. We can animate any element, such as a simple image: <div id="clickme">Click here</div><img id="book" src="book.png" alt="" width="100" height="123" /> We will cause .toggle() to be called when another element is clicked. $('#clickme').click(function() {$('#book').toggle('slow', function() {$.print('Animation complete.');});}); With the element initially shown, we can hide it slowly with the first click: A second click will show the element once again: The second version of the method accepts a Boolean parameter. If this parameter is true, then the matched elements are shown; if false, the elements are hidden. In essence, the following statement $('#foo').toggle(showOrHide); is equivalent to: if (showOrHide) {$('#foo').show();}else {$('#foo').hide();} There is also an event method named .toggle().
Read more
  • 0
  • 0
  • 2512
Modal Close icon
Modal Close icon