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
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials

7019 Articles
article-image-drupal-6-social-networking-communicating-users
Packt
14 Oct 2009
6 min read
Save for later

Drupal 6 Social Networking: Communicating with Users

Packt
14 Oct 2009
6 min read
Getting started We are going to look at a few different modules, some of which we will use. These need to be installed first, so let's do that now to save us time. The modules We need to download the following modules: Addresses module (http://drupal.org/project/addresses) enable the Addresses, Addresses - Phone/Fax and Addresses - Users components. Simplenews module (http://drupal.org/project/simplenews) And extract them to our sites/all/modules folder, and enable them via the administration interface. A look back We have already looked at one very important aspect to communicate with our users—user e-mail settings. Within the User settings page (Administer | User management | User settings), we have a group of settings under the heading User e-mail settings. These are various email templates that are sent to our users upon certain events, such as registration, account activation, password reset, account being blocked or account being deleted. The content of these emails can be very important depending on the nature of the web site. In our Dino Space site, we may use a very informal, welcoming and fun tone for our automated emails. But for a business-oriented social network, we would want to use a much more formal tone. Modules Don't forget, many modules also have their own email templates for sending emails to users, all of which can normally be changed easily from their respective sections in the administration area. Communicating on an individual basis As we have installed the contact form module on our site, we can also communicate with our users on an individual basis using the contact forms on their profiles. This is handy for those times when we do need to contact an individual user, maybe because of complaints against them by other members of the community, or perhaps to invite them to become a moderator or contributor to the site. Alternatively, we can contact the user directly via their email addresses listed in their accounts, as this is viewable from the administration area. Inactive users We may wish to contact users who have not been active on the site for a long time, to remind them that the site is still there, and that they would be welcome to become active in the community once again. Drupal records the time a user was last active, which allows us to easily sort the list of users by their activity. A module (Inactive user) is available for Drupal 5, which is intended to contact inactive users automatically, but (at the time of writing this) one is not available for Drupal 6. You may wish to keep watch on the modules list on the Drupal.org web site to see if anything comes up in future http://drupal.org/project/inactive_user Communicating with individuals publicly Don't forget, we also have access to all of the communication methods available for our users to communicate with one another, such as replying to posts, commenting on content, or posting on their profiles. So if we need to contact a user, and we can contact them publicly, we can use these features. Mailing lists Drupal has a number of modules available for sending emails to our users. Many of them are still currently under heavy development, or had their development stopped after the release of a previous version of Drupal. One of these modules is Simplenews, which is a native Drupal system for managing newsletters. One limitation of the Simplenews module, and most of the modules available, is that it can't send to all our users; it requires users to subscribe to the mailing list. We can manage the Simplenews module via Administer | Newsletter. The features available to us are quite comprehensive. Let's have a look at how the module works: Newsletters are created and managed from here Users subscribe to various Newsletters Users can be imported into Newsletters to become a subscriber A message is sent to a newsletter (this is referred to as an issue) by creating Newsletters content Issues which have been sent are saved within the module Issues which have not yet been sent are saved within the module as drafts By default, we have a newsletter, which is generic to our site based on our site name. From here we can also create new Newsletters should we wish so. The Subscriptions tab allows us to see and manage the subscriptions to our various newsletters, the Sent issues tab lists issues sent out to the newsletter lists, and the Drafts tab lists issues which are still being written. From within the Settings tab, we can set how new issues for newsletters are created, as well as the email address shown as the sender of issues. Don't forget to set the permissions; you want your users to be able to subscribe to newsletters. Users can subscribe to newsletters from within their account, or we can enable blocks for the relevant newsletters we have on our site. To send an "issue" to our newsletter list, we need to create the issue as a new content element via Create content | Newsletter issue. We enter the subject of our email as the Title, select the newsletter to send the message to from the Newsletter drop-down list, and the message is entered into the Bodybox. Beneath these options, we have some newsletter specific-options within the Newsletter sending options box. These options allow us to set the priority of the email message (this is often ignored by email clients), if we wish to request a receipt to see if a user has read the message (this is also often ignored by email clients) and finally, we can select a sending method. There are three sending methods, which are: Don't send now—this won't send the message, and will save it as a draft. Send one test newsletter to the test address—this will send the email message to the test email addresses, which we can set in the administration area. This allows us to review the newsletter, as if we were a subscriber, make any final alterations and then send it to our list. Send newsletter—this sends the email to our newsletter list. How to send an email to all our users? We can use the module to send an email to all of our users, by taking advantage of the subscriber import feature. Within Administer | Content management | Newsletters | Subscriptions, we have the ability to Import subscriptions, as shown in the following screenshot: Importing subscribers consists of entering the E-mail addresses (separated by a comma) and selecting the newsletter which we wish the user to subscribe to. To get all of our current members to subscribe to the mailing list, we could export all of our users' email addresses directly from the Drupal database, using a tool such as phpMyAdmin. If we use the tool correctly, we can even get the data in a comma-separated list ready to be pasted into the form.
Read more
  • 0
  • 0
  • 1697

article-image-enhancing-user-experience-wordpress-27part-1
Packt
14 Oct 2009
6 min read
Save for later

Enhancing User Experience with WordPress 2.7(Part 1)

Packt
14 Oct 2009
6 min read
As a blogger, I read loads of blog posts every day, on many different blogs. Very often, I'm scared to see how many blogs have a non user-friendly interface. How often does it happen that you can't click on the logo to go back to the blog homepage, or can't find what you're looking for by using the search engine? It is a well known fact that in blogging the content is king, but a nice, user friendly interface makes your blog look a lot more professional, and much easier to navigate. In this article, I'll show you what can be done for enhancing user experience and making your blog a better place. Replacing the Next and Previous links by a paginator When a web site, or blog, publishes lots of articles on a single page, the list can quickly become very long and hard to read. To solve this problem, paginations were created. Pagination allows displaying 10 articles (for example) on a page. If the user wants, then he or she can go to the next page, or click on a page number to directly go to the related page. I definitely don't understand why WordPress still doesn't have a built-in pagination system. Instead, at the bottom of each page you'll find a Next link to go to the next page, and a Previous link to go back. This works fine when you're on page two and would like to go to page three, but what if you're on page one, and remember a very interesting article which was located on page eight? Are you going to browse page per page until you find your article? The answer is yes, because you don't have the choice. You can't jump from page one to page eight. In this recipe, I'll show you how to integrate a pagination plugin in your WordPress blog theme. One very good point of this recipe is that the plugin file is embedded in your theme, so if you're a theme designer, you can distribute a theme which has a built-in pagination system. Getting ready To execute this recipe you need to grab a copy of the WP-PageNavi plugin, which can be found at http://wordpress.org/extend/plugins/wp-pagenavi/. I have used version 2.40 of the Wp-PageNavi plugin in this example. Once you have downloaded it, unzip the zip file but don't install the plugin yet. How to do it Open the WP-PageNavi directory and copy the following files into your WordPress theme directory (For example, http://www.yourblog.com/wp-content/ theme/yourtheme). wp-pagenavi.php wp-pagenavi.css Once done, edit the index.php file. You can do the same with other files, such as categories.php or search.php as well. Find the following code (or similar) in your index.php file: <div class="navigation"> <div class="alignleft"><?php next_posts_link('Previous entries') ?></div> <div class="alignright"><?php previous_posts_link('Next entries') ?></div></div> Replace that with the following code: <?php include('wp-pagenavi.php'); if(function_exists('wp_pagenavi')) { wp_pagenavi(); } ?> Save the index.php file. If you visit your blog now, you'll see that nothing has changed. This is because we have to call a function in the wp-pagenavi.php file. Open this file and find the following code (line 61): function wp_pagenavi($before = '', $after = '') {global $wpdb, $wp_query; We have to call the pagenavi_init() function, so let's do this in the following way: function wp_pagenavi($before = '', $after = '') {global $wpdb, $wp_query;pagenavi_init(); //Calling the pagenavi_init() function Now, save the file and refresh your blog. The pagination is now displayed! This is great news, but the pagination doesn't look good. To solve this problem, you simply have to integrate the wp-pagenavi.css file that you copied earlier in your theme directory. To do so, open the header.php file from your theme and paste the following line between the <head> and </head> tags: <link rel="stylesheet" href="<?php echo TEMPLATEPATH.'/pagenavi. css';?>" type="text/css" media="screen" /> Visit your blog homepage one more time. The pagination looks a lot better. You may have to edit the wp-pagenavi.css file in order to make your pagination look and feel ft your blog style. How it works In this recipe, you have discovered a very useful technique that I often use on my blogs, or in the themes that I distribute—the integration of a WordPress plugin into a theme. When the plugin is integrated into your theme as I have shown you in this example, there's no activation process needed. All of the work is done directly from the theme. The WP-PageNavi plugin itself works by using two values—the number of posts to be displayed per page and the first post to be displayed. Then, it executes the relevant query to WordPress database to get the posts. The pagination bar is calculated by using the total number of posts from your blog, and then dividing this value by the number of posts per page. One good point of this technique is that the plugin is integrated in your blog and you can redistribute the theme if you want. The end user will not have to install or configure anything. Highlighting searched text in search results I must admit that I'm not a big fan of the WordPress built-in search engine. One of its weakest features is the fact that searched text aren't highlighted in the results, so the visitor is unable to see the searched text in the context of your article. Getting ready Luckily, there's a nice hack using regular expressions to automatically highlight searched text in search results. This code has been created by Joost de Valk who blogs at www.yoast.com. How to do it This useful code is definitely easy to use on your own blog: Open your search.php file and find the following: echo $title; Replace it with the following code: <?php $title = get_the_title(); $keys= explode(" ",$s); $title = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt"></strong>',$title);?> Save the search.php file and open the style.css file. Append the following line to it: strong.search-excerpt { background: yellow; } You're done. Now, the searched text will be highlighted in your search results. How it works This code is using PHP regular expressions to find the searched terms in the text returned by WordPress. When an occurrence has been found, it is wrapped in a <strong> HTML element. Then, I simply used CSS to define a yellow background to this element.
Read more
  • 0
  • 0
  • 1920

article-image-creating-your-first-web-page-using-expressionengine-part-1
Packt
14 Oct 2009
8 min read
Save for later

Creating Your First Web Page Using ExpressionEngine: Part 1

Packt
14 Oct 2009
8 min read
Toast for Sale! To demonstrate the power of ExpressionEngine, we are going to use a fictitious business as an example throughout this article. Our website is in the business of selling toast (heated bread with melted butter) online. With this example, we will be able to explore many of the nuances of building a complete website with ExpressionEngine. Though unlikely that we would really want to sell toast over the internet, the concepts of our example should be transferable to any website. In this article, we want to introduce the world to our business, so we are going to create a 'News from the President' webpage. This will allow the President of our company to communicate to customers and investors the latest goings-on in his business. Inside the Control Panel When you first log into the control panel, there are lots of options. Let us take a quick tour of the control panel. First, we will need to log into ExpressionEngine. If you are using XAMPP to follow along with this article, go to http://localhost/admin.php or http://localhost/system/index.php to log in. It is assumed that you are using XAMPP with http://localhost/ addresses. If you are following along on an actual website, substitute http://localhost/ for your website domain (for example, http://www.example.com/). It is required to move the login page to the root of our website to mask the location of our system directory The first page we see is the CP Home. We can return to this page anytime by selecting CP Home from the menu at the top-right of the screen, above the main menu. In the left column, we have EllisLab News Feed. Below, we have Most Recent Weblog Entries as well as any Recent Comments or trackbacks visitors may have left. In our case, our site is brand new, so there will be no recent comments or trackbacks, and only 1 recent weblog entry (Getting Started with ExpressionEngine). Clicking on the link will take you directly to that entry. On the right, there is a Bulletin Board (a way for you to pass messages to other members of your control panel), the Site Statistics and a Notepad (we can write anything here, and it will be available every time we log-in). Across the top is the main menu bar, and at the top-right are links to your website (My Site), this page (CP Home), the ExpressionEngine user-guide (User Guide), and to log-out (Log-out). The Publish and Edit links in the main menu bar are where you can create new entries and edit existing entries. The Templates link is where we can create new templates and edit existing templates. We will spend most of our time in these sections. The Communicate tab is where we can manage bulk-emails to our website members. At this time we do not have any members to email (other than ourselves), but as our site grows larger, this feature can be a useful communication/marketing tool. Be careful to avoid sending unsolicited bulk emails (or spam) using this feature. In many countries, there are laws governing what can or cannot be done. In the United States, commercial emails must meet very specific guidelines set by the Federal Trade Commission (http://www.ftc.gov/spam/). The Modules tab is where we can manage all the modules that come with ExpressionEngine, as well as optional third-party modules that we may wish to install. We can download additional modules from http://expressionengine.com/downloads/addons/category/modules/. The My Account tab is where we can edit our login preferences, including our username and password. We can also edit the look and feel of the control panel home page from this screen, as well as send private messages to other members. Much of this page is irrelevant when we are the only member of the site (as we are right now). The Admin tab is where most of the configuration of ExpressionEngine takes place, and we will spend a lot of time here. By default, most of the ExpressionEngine settings are already properly set, but feel free to browse and explore all the options that are available. Full documentation on each of the options is available at http://expressionengine.com/docs/cp/admin/index.html. This concludes our brief tour of ExpressionEngine. Now we are going to delve into one of the most important parts of the control panel—templates. Templates and URLs The basic concept in ExpressionEngine is that of a template. Go to any ExpressionEngine-powered website and you will undoubtedly be looking at a template. Templates are what the outside world sees. At its most basic, a template in ExpressionEngine is a HTML (or CSS or JavaScript) file. If we wanted to, we could use a template exactly like a HTML file, without any problems. We could create an entire website without ever using any other part of ExpressionEngine. However, we can take templates a lot further than that. By using ExpressionEngine tags inside our templates, we can take advantage of all the features of ExpressionEngine and combine it with all the flexibility that HTML and CSS offers in terms of layout and design. We are not limited to pre-defined 'cookie-cutter' templates that have been carefully adapted to work with ExpressionEngine. This is why ExpressionEngine is very popular with website designers. On the flip side, this is also why there is such a learning curve with ExpressionEngine. There is no point-and-click interface to change the look and feel of your website; you have to have some experience with HTML to get the most out of it. Let us take a closer look at templates and how they relate to URLs: If you are not already logged in, log into ExpressionEngine at either http://localhost/admin.php or http://www.example.com/admin.php. Click on the Templates button on the top of the screen. Templates are stored in groups. There is no 'right' way to group templates—some sites have all their templates in a single group and other sites have lots of template groups. We are going to create a new template group for each section of our website. ExpressionEngine does come pre-installed with two template groups: the site template group and the search template group. As a new user, it is best not to delete these template groups in case you want to refer to them later. In the next screen we can give our template group a name; let us use toast. There is an option to Duplicate an Existing Template Group which copies all the templates from one template group into our new template group. This can be useful if we are creating one template group that will work very similarly to the one that we already created, but as this is our first template group, we are going to start from scratch. Checking the box Make the index template in this group your site's home page? means that visitors will see the toast website in place of the ExpressionEngine example site. If you are using the XAMPP test server, go ahead and check this box. Hit Submit to create the template group. We will be returned to the Template Management screen. A message will appear saying Template Group Created, and the new template will appear in the box of groups on the left-hand side. Left-click on the New Template group in the Choose Group box on the left-hand side. Each template group comes with an initial template, called index. Remembering that a template is like an HTML file, a template group is like a directory on our server. The index template is the equivalent of the index.html file—when a visitor visits our template group, the index template is displayed first. For that reason, the index template cannot be renamed or deleted. Let us edit the index template to see what it does. Click on the word index. A template is essentially just text (although it usually contains HTML, CSS, or ExpressionEngine code). When we first create a template, there is no text, and therefore all we see is an empty white box. Let us write something in the box to demonstrate how templates are seen by visitors. Type in a sentence and click Update and Finished. Just like HTML files and directories, templates and template groups relate directly to the URL that visitors see. In the URL http://www.example.com/index.php/toast/index, the index.php is what distinguishes this as an ExpressionEngine page. Then comes the template group name, in our case called toast. Finally, we have the template name, in this case index. Go to the previous URL (with or without the index.php as appropriate, for example, http://www.example.com/toast/index or http://localhost/toast/index) and the template we just edited should appear. Now try typing the template group without specifying which template to load. The index template is always returned. What happens if we do not specify the template group, and just go to our base domain (http://localhost/ or http://www.example.com/)? In this case, the toast template of the default template group is returned. The default template group is indicated on the templates screen with an * before the template group name and underneath the list of template groups.
Read more
  • 0
  • 0
  • 4529

article-image-creating-better-selling-experience-drupal-e-commerce
Packt
14 Oct 2009
5 min read
Save for later

Creating a Better Selling Experience with Drupal e-Commerce

Packt
14 Oct 2009
5 min read
Doug is an avid dinosaur and model enthusiast, and runs his own shop and museum selling model dinosaurs and offering information and facts on various dinosaurs. For the purpose of this article, we will create an e-commerce website named 'Doug's Dinos!' for Doug and his business. Making Things Easier Although Doug's store is relatively simple for his customers to use, it is missing three key features that would make their time on the website easier, these are: An overview of the shopping cart Search features Ability to auto-create user accounts At the moment, without a search feature the only way for users to find products is by manually browsing through the website and stumbling across a product they like. Adding a Shopping Cart We can add a shopping cart to our theme so that customers can continue browsing the website but still know how much is in their shopping cart, and easily get to it later. To add this block, we need to go to the Blocks section, which is under Site Building within the Administer area. Within the Blocks section, we need to ensure we have all our themes selected (or do this for each theme we are using) and then change the Region of the Shopping cart to the left sidebar. Once we click on the Save blocks button, the shopping cart block is displayed in our theme: Adding Search Capabilities Doug tested the website with a few friends and family members, and their main issue with it was the difficulty in finding products they wanted. The first thing we need to do is install the Search module, which is grouped under the Core - optional section of Modules in the Administer area. With the module installed, we now need to enable the Search feature from the Blocks section; otherwise the search box won't be displayed on the website. We can select this feature by going to Administer | Site Building | Blocks, then set it up in the same way as for the shopping cart and save the settings. We now have a search box on our website under the header but above the main menu! Let's try searching for one of our products, for instance T-Rex. Notice something? No results found! This seems quite strange as we have a product with T-Rex in the name, so why didn't we get any results? The reason for this is that Drupal has not yet been indexed. Drupal uses a cron job to create the index of the site. Without the indexing done Search options cannot work. The Search settings under Administer | Site configuration allow us to specify how many pages are indexed per "cron run" and allow us to set the site to be re-indexed. Cron JobsA cron job is a setting on your web host's server (if you have cPanel hosting, it is available under "crontab") that performs tasks at specific times. Drupal has a special page that performs various tasks; this can be called by a cron job so that it regularly opens the page and runs the tasks. This setting depends on having set up a cron job to periodically call the cron.php file. For more information on setting up cron jobs, you should contact your web host. Typically it involves a crontab setting in your hosting control panel such as cPanel. We can manually run the cron task, by opening the cron.php file in our web browser. In this case we just open: http://www.dougsdinos.com/cron.php. Once we have opened this page, let's try searching for T-Rex again. This time we will get some results! Customers will now be able to find products and other content on Doug's website much more easily! Auto-Creating User Accounts If a customer is not a user on our site, we can automatically create a user account for them once they have placed their order; this saves the inconvenience of using an anonymous purchase policy where the user has to log in or register, but it gives the user the added convenience of having their details saved for future orders. This is something Doug wants to enable to make things easier for regular customers on this site. The first thing we need to do is install the module. The module is called EC Useracc and is listed in the E-Commerce Uncategorized group of modules. Now under E-Commerce configuration we have a new option called User Account; let's take a look at it. This has the following settings: Confirmation e-mail Welcome mail Days to confirm expiry The Confirmation e-mail is to see if the customer wants to create a user account; this email expires after the number of days set in the Days to confirmation expiry setting has passed, and the Welcome mail is the email sent when the account is created. These emails can be configured on the Mail page. These settings don't actually enable the feature though; we have installed the module and looked at the global settings, but to actually get it to work we need to set how we would like each product to work in relation to this module. If we go to edit any product, there is a new section, which was not there previously, called User account provision; this is what we need to change. As Doug wants this feature enabled, we need to check the option Create an account for the user when this product is purchased. The other option, Block the user's account when this product expires, relates to using recurring billing in products (mainly non-tangible products i.e. services) such as a customer support contract or a magazine subscription.
Read more
  • 0
  • 0
  • 1455

article-image-implementing-document-management-alfresco-3-part2
Packt
14 Oct 2009
4 min read
Save for later

Implementing Document Management in Alfresco 3- part2

Packt
14 Oct 2009
4 min read
Library services Library services are common document management functions for controlling the users through permissions, for creating multiple instances of a document(versioning), and for providing users with access into a document to make the changes (checking-in or checking-out). Versioning You might have more than one person who can edit a document. What if somebody edits a document and removes a useful piece of information? Well, you can make use of the versioning features of Alfresco to resolve such issues. Versioning allows the history of previous versions of a content to be kept. The content needs to be Versionable, in order for versions to be kept. You can enable versioning in four different ways: Individually: To enable versioning for an individual content object item, go to the View Details page and click on the Allow Versioning link. The next screenshot illustrates how to enable versioning on an individual content item. Using Smart Spaces: A business rule can be set for a space to allow versioning of all of the content or selected content within that space. By Type: By default, versioning is disabled for all of the content types in the Alfresco content model. Versioning can be enabled for a specific content type, irrespective of the location of the content. Globally: Alfresco can be configured globally to enable versioning for all content throughout the site. Enable versioning for sample file that you have already uploaded to the system. Go to the Intranet > Marketing Communications > Switch to open source ECM > 02_Drafts space and view the details of Alfresco_CIGNEX.doc file. Click on the Allow Versioning link to enable versioning, as shown in the following screenshot. You will immediately notice that a version with a version number of 1.0 is created. At the time of writing this article (Alfresco version 3.1), reverting back to an older version of the content is not supported. There is a plan to support this feature in future releases of Alfresco. The workaround is to download the older version and upload it again as the current version. For a checked out content, the version is updated when the content is checked in. The version number is incremented from the version number of the content object that was checked out. Auto Versioning Auto versioning can be enabled by editing the content properties and selecting the Auto Version checkbox. If auto versioning is enabled, then each Save of the content results in an incremented version number, when the content is edited directly from the repository. Each Update (upload) of the content also results in a new version (with an incremented version number) being created. If auto versioning is not enabled, then the version number is incremented only when the content is checked in. Check In and Check Out By using the versioning feature, you can ensure that all of the changes made to a document are saved. You might have more than one person who can edit a document. What if two people edit a document at once, and you get into a mess with two new versions? To resolve this issue, you'll need to use the library services. Library services provide the ability to check out a document, reserving it for one user to edit, while others can only access the document in read-only mode. Once the necessary changes have been made to the document, the user checks in the document, and can either replace the original, or create a new version of the original. Check Out locks the item and creates a working copy that can be edited (both the content and the details). Check In replaces the original item with the working copy, and releases the lock.
Read more
  • 0
  • 0
  • 1993

article-image-autoproxy-spring-aspect-oriented-programming-aop
Packt
14 Oct 2009
5 min read
Save for later

Autoproxy in Spring Aspect-Oriented Programming (AOP)

Packt
14 Oct 2009
5 min read
Autoproxy with classic Spring By using the class ProxyFactoryBean, AOP can be used in a classic way. But writing separately for each bean on which we want to apply an advisor is not a pleasant thing to see, especially if they are many. So let's consider it as a practicable way only if the beans to be configured in that modality are few. On the other hand, if the beans to which we have to apply AOP are many, in order to avoid finding ourselves with very long configuration files, we adopt another tactic: We use the auto proxy creator's system, which allows us to automatically create proxies for the beans and prevent using ProxyFactoryBean. There are two classes made available by Spring to allow the auto proxy creator: BeanNameAutoProxyCreator and DefaultAdvisorAutoProxyCreator. BeanNameAutoProxyCreator BeanNameAutoProxyCreator just has a list of beans names to which proxy can be created automatically. The way in which the autoproxy is created is really simple. It implements the BeanPostProcessor interface, which in its implementation replaces the bean (target) with a proxy. Example: This is the interface describing an animal. package org.springaop.chapter.three.autoproxy.domain;public interface Animal { public Integer getNumberPaws(); public Boolean hasTail(); public boolean hasFur(); public Boolean hasHotBlood(); } The (interface) Bird extends Animal. package org.springaop.chapter.three.autoproxy.domain;public interface Bird extends Animal{ public Boolean hasBeak(); public Boolean hasFeathers(); } The class that implements the Animal interface to describe Cat: package org.springaop.chapter.three.autoproxy.domain;public class Cat implements Animal{ public boolean hasFur() { return true; } public Integer getNumberPaws() { return 4; } public Boolean hasTail() { return true; } public Boolean hasHotBlood() { return true; } public void setSpecies(String species) { this.species = species; } public String getSpecies() { return species; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } private String species, colour;} The class that implements Animal and Bird to describe a Seabird: package org.springaop.chapter.three.autoproxy.domain;public class Seabird implements Animal,Bird{ public Integer getNumberPaws() { return 2; } public Boolean hasTail() { return false; } public Boolean hasBeak() { return true; } public Boolean hasFeathers() { return true; } public boolean hasFur() { return false; } public Boolean hasHotBlood() { return false; } public String getName() { return name; } public void setName(String name) { this.name = name; } private String name;} AnimalAdvice containing just the log with the target class, the invoked method, and the result. package org.springaop.chapter.three.autoproxy;import org.aopalliance.intercept.MethodInterceptor;import org.aopalliance.intercept.MethodInvocation;public class AnimalAdvice implements MethodInterceptor { public Object invoke(MethodInvocation invocation) throws Throwable { Logger log = Logger.getLogger(Constants.LOG_NAME); StringBuilder sb = new StringBuilder(); sb.append("Target Class:").append(invocation.getThis()).append("n").append(invocation.getMethod()).append("n"); Object retVal = invocation.proceed(); sb.append(" return value:").append(retVal).append("n"); log.info(sb.toString()); return retVal; }} The configuration file applicationContext.xml: <beans xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="tiger" class="org.springaop.chapter.three.autoproxy.domain.Cat"> <property name="species" value="tiger"/> <property name="colour" value="tear stripes"/></bean> <bean id="albatross" class="org.springaop.chapter.three.autoproxy.domain.Seabird"> <property name="name" value="albatross"/></bean> <!-- Pointcut --> <bean id="methodNamePointcut" class="org.springframework.aop.support.NameMatchMethodPointcut"> <property name="mappedNames"> <list> <value>has*</value> <value>get*</value> </list> </property> </bean> <!-- Advices --> <bean id="animalAdvice" class="org.springaop.chapter.three.autoproxy.AnimalAdvice"/> <!-- Advisor --> <bean id="animalAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor"> <property name="pointcut" ref="methodNamePointcut"/> <property name="advice" ref="animalAdvice"/> </bean> <bean id="autoProxyCreator" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <property name="proxyTargetClass" value="true"/> <property name="beanNames"> <list> <value>tiger</value> <value>albatross</value> </list> </property> <property name="interceptorNames"> <list> <value>animalAdvisor</value> </list> </property> </bean> </beans> Application context contains two beans, tiger and albatross. The methodNamePointcut acts on the methods starting with has and get. The animalAdvice (around advice) contains the logics to be executed, the animal advisor that links the animalAdvice to the methodNamePointcut, and the autoProxyCreator, where we declare just the beans' names and the list of interceptors' names. package org.springaop.chapter.three.autoproxy;public class AutoProxyTest { public static void main(String[] args) { String[] paths = { "org/springaop/chapter/three/autoautoproxy/applicationContext.xml" }; ApplicationContext ctx = new ClassPathXmlApplicationContext(paths); Cat tiger = (Cat)ctx.getBean("tiger"); tiger.hasHotBlood(); Bird albatross = (Bird)ctx.getBean("albatross"); albatros.hasBeak(); }} The test class invokes two methods on the beans tiger and albatross. Output:
Read more
  • 0
  • 0
  • 5917
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 €18.99/month. Cancel anytime
article-image-managing-users-and-their-profiles-drupal-6-social-networking
Packt
14 Oct 2009
10 min read
Save for later

Managing Users and their Profiles in Drupal 6 Social Networking

Packt
14 Oct 2009
10 min read
What are we going to do and why? Before we get started, let's have a closer look at what we will be doing, and why. Our users can interact with the web site, and they can have their own blog. Apart from this, there are very few provisions for the users to tell everyone else about themselves, and expand their profiles with something more personal. With a site like ours, it would be useful to know more about our users including: Their pet dinosaur's name Breed of dinosaur Their pet dinosaur's birthday The dinosaur's hobbies and so on Their web address (if they have one) Location / City / Area More information about the user themselves This can be added to user profiles using the Profile module, which is a core module within Drupal, and simply needs to be enabled and configured. Many web sites allow users to upload an image to be associated with their accounts, which could be either a small photo of themselves, or a small image known as an avatar. Drupal allows this, but it has some drawbacks which can be fixed using Gravatar. Gravatar is a social avatar service, whereby users set up their avatars, and other web sites automatically pick up their avatars by sending a request to the Gravatar service with the users' emails. This is convenient for our users, as it saves them having to upload their avatars to our site, and reduces the amount of data stored on our site as well as the data being sent and received from our site. This module needs to be downloaded, installed and configured for our users to make use of its features. With the upload module enabled, users can upload their own avatars directly to the site, if they choose to do so. This is because not all users would be members of Gravatar, nor would they all wish to sign up to a third-party service. With the rise in the number of web sites and social networks that users of the Internet are members of, having to log in to different web sites on a daily basis can put off users if they have to sign up to another web site. OpenID helps prevent this as users need to remember only one username and password. It works by allowing users to login by providing a web address, instead of their usernames and passwords. This web site is their identity with an OpenID provider (maybe it is their own web site or another social network—MySpace and other social networking web sites are OpenID providers). When they log in with these identities, they will be taken to these web sites to log in before being returned to our site. If they have already logged in into their OpenIDs, they will return to the web site as new users. More information on OpenID is available from http://openid.net/. This is a core module which just needs to be enabled. There are two important points to be noted about OpenID. Firstly, it is decentralized, which means log in details are not tied to a specific provider, and secondly, it is offered as an alternative log in method—users without an OpenID (or those who don't know they have an OpenID!) can still log in or sign up as normal. Users have their own blogs which they can use, but they are not personalized blogs. By installing the blog theme module, we can allow our users to select different themes for use in their blogs. This way, visitors to one particular user's blog (for example 'Bob') will see the theme that Bob chose. Once users get to know each other more, they become more interested in each other's posts and topics, and may wish to look up a specific user's posts and contributions. The Tracker module allows users to track one another's contributions to the site. This is a core module, which just needs to be enabled and set up. Now that we have a better idea of what we are going to do, let's get started! Install the modules To make things easier for us, let's install and enable all the relevant modules first. This saves us having to do this again and again at a later stage. The modules which we require are: Profile (a core module) Tracker (a core module) OpenID (a core module) Gravatars (http://drupal.org/project/gravatar) Blog Theme (http://drupal.org/project/blogtheme) We need to download the relevant modules (ensuring we download ones which are compatible with Drupal 6.x), and extract the ZIP files into the /sites/all/modules folder. As we have not downloaded and installed any new modules on our Drupal installation yet, we will need to create the folder modules within the /sites/all/ directory. The reason there are sites/all and a sites/default directories is because Drupal can support multiple web sites running off one installation, and this defines which modules are available to which of the installations. Core modules are located elsewhere, which is why we don't have a modules folder already in this location containing the core modules. Now all the modules just have to be enabled via the Site Building | Modules section of the Administration area. Users, roles, and permissions Let's have a more detailed look at users, roles, and permissions and also how they work. These are all areas of the administration area, within the User management section. The other options within this section (Access rules, Gravatar, Profiles and User settings) will be looked at later in this article. Users When a visitor signs up for our site, a user account is created for him/her. From the Users area, we can view a list of existing users, create new ones and edit them. Within the context of editing a user, not only can we edit their details, such as their usernames or passwords, but we can also suspend their user accounts or delete their user accounts permanently from our social network. We want our site to become popular, which means that we want to have lots of users. When we get lots of users, it will become more difficult to navigate through their list, and this is when searching, sorting, and filtering them come in handy—which is what we are going to look at now. For each user, the user list displays: The username The status of the user account (active or blocked) Roles associated with the account Length of time the user has been a member for The time passed since the user was last active on our site A link to edit the user Viewing / searching / sorting / filtering Clicking the username will take us to their user profile. We can sort the list of users by clicking the heading in any of the columns to sort the list by that column. One particular use of doing this is that we can see all blocked users, ????so we can quickly reactivate an account should we need to, or see who the newest members are. We can also filter the accounts displayed using the Show only users where panel. This allows us to filter the list based on whether the account is active or not, or against specific roles assigned to users. Creating a user At the top of the users page, we have the Add user link. This takes us to the new user page, where we are required to fill out the Username, E-mail address, Password, and Confirm Password again for the user. We can also opt to notify the users of their new accounts, which will send them an email informing them that they have a new account with the Dino Space social network. Editing To edit an account, we just need to click the edit link which corresponds to the account, which takes us to the edit page. We can edit the user's Username, E-mail address, Password, account Status and settings pertaining to modules, which give users additional settings too. Careful!If you edit these settings, the users may not be able to log in to their accounts. If you change a user's Username without his/her request, you should let him/her know through email. Suspending / blocking a user Within the edit page, we have an option entitled Status, which can be set to either Blocked or Active. This would allow us to block a user from accessing our site, for instance if they had been posting inappropriate material repeatedly, even after being contacted and asked to stop. Why block? Why not just delete?If we were to just delete a user who was posting inappropriate material, or doing something we didn't want, then he/she could just sign up again. Blocking the user prevents him/her from signing up with the same email address and username. Of course, he/she could sign up again with a different email address and a different username. But this helps us to keep things under control. Deleting a user At the bottom of the edit user screen, there are two buttons: Save and Delete. The Save button will confirm and save any changes made to the user's account, and the delete button will permanently remove the user from our social network. When to delete a userA user may request to be removed from the web site, in which case, we can use this feature. Roles Users are grouped into roles, which in turn have permissions assigned to them. By default, there are two roles within Drupal. These two roles are: anonymous users authenticated users These roles can be edited, but they can neither be renamed nor deleted. This is why the Operations column in the table below is locked. The anonymous user role is the role for any user who is not logged-in, and so the permissions associated with it are those which a guest user has. Whereas the role of an authenticated user suits all those users who are logged-in. Additional roles which are added can apply to any number of users. At this stage, we must select which users have which roles assigned to them. Users can change their roles and get more active within the network with features such as Organic Groups, but it is out of the scope of this article. Editing the permissions of a role allows us to select which permissions are granted to users who have that role assigned to their account. New roles are simply created by entering the name of a new role into the text box and then clicking the Add role button and selecting the permissions to be granted to those users. Permissions The Permissions section provides us with a grid view for roles and the permissions assigned to them. All the permissions which can be granted are listed down theside (for example, create blog entries) and the roles along the top. The use of this view, if we were to install a new module with new permissions related to it, is that we could easily update all of our roles to have the desired permissions directly from the grid view. The Save permissions link at the bottom of the page saves the changes made.
Read more
  • 0
  • 0
  • 3080

article-image-developing-wiki-seek-widget-using-javascript
Packt
14 Oct 2009
8 min read
Save for later

Developing Wiki Seek Widget Using Javascript

Packt
14 Oct 2009
8 min read
If you’re searching for details of a particular term in Google, you’re most probably going to see a link for relevant articles from wikipedia.org in the top 10 result list. Wikipedia, is the largest encyclopedia on the Internet, and contains huge collections of articles in many languages. The most significant feature of this encyclopedia is that it is a Wiki, so anybody can contribute to the knowledge base. A Wiki, (a new concept of web2.0), is a collection of web pages whose content can be created and changed by the visitor of the page with simplified mark-up language. Wikis are usually used as knowledge management systems on the web. Brief Introduction to Wikipedia Wikipedia has defined itself as : … a free, multilingual, open content encyclopedia project operated by the United States-based non-profit Wikimedia Foundation. Wikipedia is built upon an open source wiki package called MediaWiki. MediaWiki uses PHP as a server side scripting language and MySql as the database. Wikipedia uses MediaWiki’s wikitext format for editing the text, so the user (without any necessary  knowledge of HTML and CSS) can edit them easily. The Wikitext language (also called Wiki Markup) is a markup language which gives instruction on how outputted text will be displayed. It provides a simplified approach to writing pages in a wiki website. Different types of wiki software employ different styles of Wikitext language. For example, the Wikitext markup language has ways to hyperlink pages within the website but a number of different syntaxes are available for creating such links. Wikipedia was launched by Jimmy Wales and Larry Sanger in 2001 as a means of collecting and summarizing human knowledge in every major language. As of April 2008, Wikipedia had over 10 million articles in 253 languages. With so many articles, it is the largest encyclopedia ever assembled. Wikipedia articles are written collaboratively by volunteers, and any visitor can modify the content of article. Any modification must be accepted by the editors of Wikipedia otherwise the article will be reverted to the previous content. Along with popularity, Wikipedia is also criticized for systematic bias and inconsistency since the modifications must be cleared by the editors. Critics also argue that it’s open nature and the lack of proper sources for many articles makes it unreliable. Searching in Wikipedia To search for a particular article in Wikipedia, you can use the search box in the home page of wikipedia.org.Wikipedia classifies its articles in different sub-domains according to language; “en.wikipedia.org” contains articles in English language whereas “es.wikipedia.org” contains Spanish articles. Whenever you select “english” language in the dropdown box, the related articles will be searched over “en.wikipedia.org” and so on for the another language. You can also search the articles of Wikipedia from a remote server. For this, you have to send the language and search parameters to http://www.wikipedia.org/search-redirect.php via the GET method Creating a Wiki Seek Widget Up till now, we’ve looked at the background concept of Wikipedia. Now, let’s start building the widget. This widget contains a form with three components. A textbox where the visitors enters the search keyword, a dropdown list which contains the language of the article and finally a submit button to search the articles of Wikipedia. By the time we’re done, you should have a widget that looks like this: Concept for creating form Before looking at the JavaScript code, first let’s understand the architecture of the form with the parameters to be sent for searching Wikipedia. The request should be sent to http://www.wikipedia.org/search-redirect.php via the GET method. <form action="http://www.wikipedia.org/search-redirect.php" ></form> If you don’t specify the method attribute in the form, the form uses GET, which is the default method. After creating the form element, we need to add the textbox inside the above form with the name search because we’ve to send the search keyword in the name of search parameter. <input type="text" name="search" size="20" /> After adding the textbox for the search keyword, we need to add the dropdown list which contains the language of the article to search. The name of this dropdown-list should be language as we’ve to send the language code to the above URL in the language parameter. These language codes are two or three letter codes specified by ISO. ISO has assigned three letter language codes for most of the popular languages of the world. And, there are a few languages that are represented by two letter ISO codes. For example, eng and en are the three and two letter language code for English. Some of the article languages of Wikipedia don’t have ISO codes, and you have to find the value of the language parameter from Wikipedia. For example, articles in the Alemannisch language is als. Here is the HTML code for constructing a dropdown list in major languages : <select name="language"><option value="de" >Deutsch</option><option value="en" selected="selected">English</option><option value="es" >Español</option><option value="eo" >Esperanto</option><option value="fr" >Français</option><option value="it" >Italiano</option><option value="hu" >Magyar</option><option value="nl" >Nederlands</option></select> As you can see in the above dropdown list, English is the default language selected. Now, we just need to add a submit button in the above form to complete the form for searching the article in wikipedia. <input type="submit" name="go" value="Search" title="Search in wikipedia" /> Put all the HTML code together to create the form. JavaScript Code As we’ve already got the background concept of the HTML form, we just have to use the document.write() to output the HTML to the web browser. Here is the JavaScript code to create the Wiki Seek Widget : document.write('<div>');document.write('<form action="http://www.wikipedia.org/search-redirect.php" >');document.write('<input type="text" name="search" size="20" />');document.write('&nbsp;<select name="language">');document.write('<option value="de" >Deutsch</option>');document.write('<option value="en" selected="selected">English</option>');document.write('<option value="es" >Español</option>');document.write('<option value="eo" >Esperanto</option>');document.write('<option value="fr" >Français</option>');document.write('<option value="it" >Italiano</option>');document.write('<option value="hu" >Magyar</option>');document.write('<option value="nl" >Nederlands</option>');document.write('</select>');document.write('&nbsp;<input type="submit" name="go" value="Search" title="Search in wikipedia" />');document.write('</form>');document.write('</div>'); In the above code, I’ve used division (div) as the container for the HTML form. I’ve also saved the above code in a wiki_seek.js file. The above JavaScript code displays a non-stylish widget. To make a stylish widget, you can use style property in the input elements of the form. Using Wiki Seek widget To use this wiki seek widget we’ve to follow these steps: First of all, we need to upload the above wiki_seek.js to a web server so that it can be used by the client websites. Let’s suppose that is uploaded and placed in the URL : http://www.widget-server.com/wiki_seek.js Now, we can widget in any web pages by placing the following JavaScript Code in the website. <script type="text/javascript" language="javascript"src="http://www.widget-server.com/wiki_seek.js"></script> The Wiki Seek widget is displayed in any part of web page, where you place the above code.
Read more
  • 0
  • 0
  • 3687

article-image-synchronous-communication-and-interaction-moodle-19-multimedia
Packt
14 Oct 2009
5 min read
Save for later

Synchronous Communication and Interaction with Moodle 1.9 Multimedia

Packt
14 Oct 2009
5 min read
These options can be helpful for distance education, providing new ways of communicating and interacting with our students (and between them) when we are not all in the same physical space. Because Moodle does not provide effective synchronous communication tools (the chat activity could overload the server), the aforementioned tools are presented as extensions that can support our courses, giving them a new level of interaction. In distance courses with considerable duration, such communication can be a motivation and a way of providing support to students when we are online at the same time. Communicating in real-time using text, audio, and video Google Chat is a service from Google that allows text, audio, and video chat amongst Google Mail users meaning, we'll need a Google account. The audio conversation is usually called Voice over IP (VoIP), but as bandwidth allowances increase, the use of video is becoming common. With this tool we can: Meet with colleagues or students, individually or in groups Participate in a distant event (for example, attend a conference) Conduct interviews Teach how to play an instrument (by using the webcam) Teach gestural language (by using the webcam) I find it really useful to use VoIP in distance courses, not only to give feedback to students and get to know them better, but also to create opportunities for students to interact with each other during group tasks outside of these tutor-students meeting times. A good time to use this application is in Module 10 – What's good music—a theme that fits well with an online debate about how to define quality criteria for music. Students will be required to work in groups and debate on what they think is good music and how it can be assessed. This discussion will be facilitated by using this tool. Chat and group chat The chat option is available in Google Mail, on the sidebar on the left. For a start, we can configure some settings, especially privacy settings, by going to Options | Chat settings…: In the section Auto-add suggested contacts, we should select the option Only allow people that I've explicitly approved to chat with me and see when I'm online option, as shown in the screenshot below: We can also disable chat history if we don't want to keep a record of our chat. There is another option during a chat to go "off record", meaning that if the chat history is on, this portion of the conversation (that takes place whilst this option is selected) will not be archived. We are now ready to start a chat. We can search for contacts in the same Google Mail Chat sidebar, using the search form that is available (Search, add or invite) and double-click on the name of the contact that is displayed, or in the Chat link of the pop-up window that is displayed: Because the chat is synchronous, it's obvious that the (two or more) people chatting must be online. We can check if a person is online or not by looking at the small icon next to the people we've located, or in our chat list. If they have a grey, round icon on the left of their name, they are offline (or invisible and don't want to be bothered). If the color is green (available), yellow (idle), or red (busy) it's possible to chat to them. In the pop-up, we can also add the person to the chat list below the search form. After starting the chat, a window similar to the one shown below opens in the lower-right corner of the Google Mail account, and we can start talking: When we are chatting with someone, we can click on the Video & More | Group Chat option to invite one or more friends to join the conversation: A new window will appear, in which we can chat with the participants. Note that if we click on the arrow in the blue bar at the top of our chat window, the window will pop-up from its position in the Google Mail window and we can access it as an independent window. If we paste a URL from a YouTube video into the chat window, a preview of the video will be integrated directly into our conversation, as shown in the screenshot below: Transferring files The easiest way to send files to participants for reading, or supporting discussion or commenting upon is either by using Google Mail, or by uploading them to Moodle or Google Docs and sharing these with the chat participants. This can be useful in many online discussions. Voice and video chat Chat, as we saw, is available by default in Google Mail, on the leftmost sidebar. To add audio and voice capabilities to this chat, we have to install a plug-in that is available at http://mail.google.com/videochat, for Windows and Mac users (again, sorry to Linux users). After installing this plug-in, we can start an audio or video conversation (only one-to-one). If our contacts have a camera or microphone, we can click on the Video & more option again, and the following two options will be available: In the case of voice chat, a call will be started, and we will also keep the text chat functionality: In the case of video chat, the same applies. In the upper area, a video of the person that we are chatting with will be displayed, and in the lower corner, if we have a webcam, our video will be displayed: Image source: Scmoewes (2005). Jimi. Retrieved March 30, 2009,from http://www.flickr.com/photos/cmoewes/30989105/ For distance courses or even in e-learning, Google chat is an option. But if we need more complex functionality, including audio conferencing and desktop sharing, there are other tools that are available. We will now look at one in particular, called Dimdim.
Read more
  • 0
  • 0
  • 1843

article-image-creating-your-first-web-page-using-expressionengine-part-2
Packt
14 Oct 2009
7 min read
Save for later

Creating Your First Web Page Using ExpressionEngine: Part 2

Packt
14 Oct 2009
7 min read
Viewing Our First Entry Now one question remains: where do we have to go to see our entry? The answer is that our entry is not yet on our website. That is because the entry does not appear in a template and everything on an ExpressionEngine website must go into a template before it can be viewed. Follow these instructions to point a template to our new weblog. Click on Templates in the menu bar. Select Create a New Template Group, and call the New Template Group to be news. Leave all the other options at their default and click Submit. Select the news template group, and then click on the index template to edit it. To include a weblog in a template, we use a tag. A tag is a unique ExpressionEngine piece of code that is used in templates to include extra functionality. In this case, we want to include a weblog, so we need a weblog tag. A tag has two parts: variables and parameters. Parameters are always part of the opening tag whereas variables are used between the opening tag and the closing tag. In the news/index template we will add in the weblog tag as well as some standard HTML code. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html > <head> <title>News from the President</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> </head> <body> <h1>Toast for Sale!</h1> <h2>News from the President</h2> {exp:weblog:entries weblog="toastnews"} <h3>{title}</h3> {summary} {body} {extended} {/exp:weblog:entries} </body> </html> The indentation helps to demarcate related sections and therefore make the code more readable, but is certainly not required. Click Update and Finished to save our updates. The difference between Update and Update and Finished is that Update will keep you in the template editing screen so that you can continue to make further edits, whereas Update and Finished returns you to the main templates screen. Now view the news template at http://localhost/news or www.example.com/news to see how it looks. It should look like the following screenshot. Notice how the {title} has been changed to reflect the actual title of our entry (and so has {summary} and {body}). What happens if we post two entries? Let us try it and see! Back in the control panel, select Publish | Toast News and write a second entry with a different title, URL title, and so forth. Hit Submit, and then visit http://localhost/news or http://www.example.com/news to see what happens. It should look like as follows: For our final enhancement, let us edit the template to include variables for the author name and the date of the entry. To do this, add the highlighted code as shown next: <body> <h1>Toast for Sale!</h1> <h2>News from the President</h2> {exp:weblog:entries weblog="toastnews"} <h3>{title}</h3> {summary} {body} {extended} <p class="footnote">Written by {author} on {entry_date format="%F %j%S"}</p> {/exp:weblog:entries} </body> {author} is a variable that returns the name of the person who was logged in when the entry was created. {entry_date} is a variable that displays the date that the entry was written on. format is a parameter of the entry_date variable that is used to specify how the date should be formatted. %F is the month of the year spelled out; %j is the day of the month; and %S is the suffix (for example, nd or th). So %F %j%S is rendered as 'February 7th'. For a complete list of date formats, visit http://expressionengine.com/docs/templates/ date_variable_formatting.html.   Revisit http://localhost/news or http://www.example.com/news, and you can now see the author name underneath both entries. Make Our Weblog Pretty Using CSS Our weblog, whilst functional, is not exactly the prettiest on the web. We will spruce it up with some more HTML and CSS. This section will not introduce any new ExpressionEngine features but will demonstrate how to incorporate standard CSS into our templates. An understanding of HTML and CSS will be invaluable as we develop our ExpressionEngine site. Please note that this article can only demonstrate the basics of using HTML with CSS in an ExpressionEngine website. If you are already familiar with using HTML and CSS, then you will only need to go through the section in the first part (Creating and Linking to a Styling Template) to create the CSS template and link to it from the HTML template. Creating and Linking to a Styling Template As with a more conventional HTML/CSS website, our CSS code will be separated out from our HTML code, and placed in its own template (or file). This requires creating a new CSS template and modifying our existing template to identify the main styling elements, as well as to link to the CSS template. First, let us go back into our news template and add the following code (highlighted). The trick with writing HTML with CSS is to identify the main sections of the HTML code using the <div> tag. <body> <div id="header"> <h1>Toast for Sale!</h1> <h2>News from the President</h2> </div> <div id="content"> {exp:weblog:entries weblog="toastnews"} <h3>{title}</h3> <div class="contentinner"> {summary} {body} {extended} </div> <p class="footnote">Written by {author} on {entry_date format="%F %j%S"}</p> {/exp:weblog:entries} </div> </body> Here we have identified three sections using the <div> tag. We have encapsulated our website title in a header section. We have wrapped up all of our ExpressionEngine entries into a content section. Finally, we have created a contentinner section that contains just the text for each ExpressionEngine entry, but does not include the title. Also note that footnote is a section. What is the difference between an id and a class in our <div> tags? A section defined with an id only appears once on a page. In our case, the header only appears once, so we can use the id. A section defined with a class may appear multiple times. As the contentinner section will appear on the page for each entry present there, we have used a class for this section. Next, we want to create a CSS template that tells us what to do with these sections. To do this, go back to the main Templates page, select the toast template group, and then select New Template. Call the new template toast_css. Under Template Type select CSS Stylesheet instead of Web Page. Leave the Default Template Data as None – create an empty template and hit Submit. Before we start editing our new CSS template, we must be sure to tell the HTML template about it. Select to edit the index template in the news template group. Insert the following highlighted commands between the <head> and </head> tags to tell the HTML template where the CSS template is. <head> <title>News from the President</title> <link rel='stylesheet' type='text/css' media='all' href='{path=toast/toast_css}' /> <style type='text/css' media='screen'>@import "{path=toast/toast_css}";</style> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> </head>
Read more
  • 0
  • 0
  • 2062
article-image-importing-structure-and-data-using-phpmyadmin
Packt
12 Oct 2009
9 min read
Save for later

Importing Structure and Data Using phpMyAdmin

Packt
12 Oct 2009
9 min read
A feature was added in version 2.11.0: an import file may contain the DELIMITER keyword. This enables phpMyAdmin to mimic the mysql command-line interpreter. The DELIMITER separator is used to delineate the part of the file containing a stored procedure, as these procedures can themselves contain semicolons. The default values for the Import interface are defined in $cfg['Import']. Before examining the actual import dialog, let's discuss some limits issues. Limits for the transfer When we import, the source file is usually on our client machine; so, it must travel to the server via HTTP. This transfer takes time and uses resources that may be limited in the web server's PHP configuration. Instead of using HTTP, we can upload our file to the server using a protocol such as FTP, as described in the Web Server Upload Directories section. This method circumvents the web server's PHP upload limits. Time limits First, let's consider the time limit. In config.inc.php, the $cfg['ExecTimeLimit'] configuration directive assigns, by default, a maximum execution time of 300 seconds (five minutes) for any phpMyAdmin script, including the scripts that process data after the file has been uploaded. A value of 0 removes the limit, and in theory, gives us infinite time to complete the import operation. If the PHP server is running in safe mode, modifying $cfg['ExecTimeLimit'] will have no effect. This is because the limits set in php.ini or in user-related web server configuration file (such as .htaccess or virtual host configuration files) take precedence over this parameter. Of course, the time it effectively takes, depends on two key factors: Web server load MySQL server load The time taken by the file, as it travels between the client and the server,does not count as execution time because the PHP script starts to execute only once the file has been received on the server. Therefore, the $cfg['ExecTimeLimit'] parameter has an impact only on the time used to process data (like decompression or sending it to the MySQL server). Other limits The system administrator can use the php.ini file or the web server's virtual host configuration file to control uploads on the server. The upload_max_filesize parameter specifies the upper limit or the maximum file size that can be uploaded via HTTP. This one is obvious, but another less obvious parameter is post_max_size. As HTTP uploading is done via the POST method, this parameter may limit our transfers. For more details about the POST method, please refer to http://en.wikipedia.org/wiki/Http#Request_methods. The memory_limit parameter is provided to avoid web server child processes from grabbing too much of the server memory—phpMyAdmin also runs as a child process. Thus, the handling of normal file uploads, especially compressed dumps, can be compromised by giving this parameter a small value. Here, no preferred value can be recommended; the value depends on the size of uploaded data. The memory limit can also be tuned via the $cfg['MemoryLimit'] parameter in config.inc.php. Finally, file uploads must be allowed by setting file_uploads to On. Otherwise, phpMyAdmin won't even show the Location of the textfile dialog. It would be useless to display this dialog, as the connection would be refused later by the PHP component of the web server. Partial imports If the file is too big, there are ways in which we can resolve the situation. If we still have access to the original data, we could use phpMyAdmin to generate smaller CSV export files, choosing the Dump n rows starting at record # n dialog. If this were not possible, we will have to use a text editor to split the file into smaller sections. Another possibility is to use the upload directory mechanism, which accesses the directory defined in $cfg['UploadDir']. This feature is explained later in this article. In recent phpMyAdmin versions, the Partial import feature can also solve this file size problem. By selecting the Allow interrupt… checkbox, the import process will interrupt itself if it detects that it is close to the time limit. We can also specify a number of queries to skip from the start, in case we successfully import a number of rows and wish to continue from that point. Temporary directory On some servers, a security feature called open_basedir can be set up in a way that impedes the upload mechanism. In this case, or for any other reason, when uploads are problematic, the $cfg['TempDir'] parameter can be set with the value of a temporary directory. This is probably a subdirectory of phpMyAdmin's main directory, into which the web server is allowed to put the uploaded file. Importing SQL files Any file containing MySQL statements can be imported via this mechanism. The dialog is available in the Database view or the Table view, via the Import subpage, or in the Query window. There is no relation between the currently selected table (here author) and the actual contents of the SQL file that will be imported. All the contents of the SQL file will be imported, and it is those contents that determine which tables or databases are affected. However, if the imported file does not contain any SQL statements to select a database, all statements in the imported file will be executed on the currently selected database. Let's try an import exercise. First, we make sure that we have a current SQL export of the book table. This export file must contain the structure and the data. Then we drop the book table—yes, really! We could also simply rename it. Now it is time to import the file back. We should be on the Import subpage, where we can see the Location of the text file dialog. We just have to hit the Browse button and choose our file. phpMyAdmin is able to detect which compression method (if any) has been applied to the file. Depending on the phpMyAdmin version, and the extensions that are available in the PHP component of the web server, there is variation in the formats that the program can decompress. However, to import successfully, phpMyAdmin must be informed of the character set of the file to be imported. The default value is utf8. However, if we know that the import file was created with another character set, we should specify it here. An SQL compatibility mode selector is available at import time. This mode should be adjusted to match the actual data that we are about to import, according to the type of the server where the data was previously exported. To start the import, we click Go. The import procedure continues and we receive a message: Import has been successfully finished, 2 queries executed. We can browse our newly-created tables to confirm the success of the import operation. The file could be imported for testing in a different database or even in a MySQL server. Importing CSV files In this section, we will examine how to import CSV files. There are two possible methods—CSV and CSV using LOAD DATA. The first method is implemented internally by phpMyAdmin and is the recommended one for its simplicity. With the second method, phpMyAdmin receives the file to be loaded, and passes it to MySQL. In theory, this method should be faster. However, it has more requirements due to MySQL itself (see the Requirements sub-section of the CSV using LOAD DATA section). Differences between SQL and CSV formats There are some differences between these two formats. The CSV file format contains data only, so we must already have an existing table in place. This table does not need to have the same structure as the original table (from which the data comes); the Column names dialog enables us to choose which columns are affected in the target table. Because the table must exist prior to the import, the CSV import dialog is available only from the Import subpage in the Table view, and not in the Database view.   Exporting a test file Before trying an import, let's generate an author.csv export file from the author table. We use the default values in the CSV export options. We can then Empty the author table—we should avoid dropping this table because we still need the table structure. CSV From the author table menu, we select Import and then CSV. We can influence the behavior of the import in a number of ways. By default, importing does not modify existing data (based on primary or unique keys). However, the Replace table data with file option instructs phpMyAdmin to use REPLACE statement instead of INSERT statement, so that existing rows are replaced with the imported data. Using Ignore duplicate rows, INSERT IGNORE statements are generated. These cause MySQL to ignore any duplicate key problems during insertion. A duplicate key from the import file does not replace existing data, and the procedure continues for the next line of CSV data. We can then specify the character that terminates each field, the character that encloses data, and the character that escapes the enclosing character. Usually this is . For example, for a double quote enclosing character, if the data field contains a double quote, it must be expressed as "some data " some other data". For Lines terminated by, recent versions of phpMyAdmin offer the auto choice, which should be tried first as it detects the end-of-line character automatically. We can also specify manually which characters terminate the lines. The usual choice is n for UNIX-based systems, rn for DOS or Windows systems, and r for Mac-based system (up to Mac OS 9). If in doubt, we can use a hexadecimal file editor on our client computer (not part of phpMyAdmin) to examine the exact codes. By default, phpMyAdmin expects a CSV file with the same number of fields and the same field order as the target table. But this can be changed by entering a comma-separated list of column names in Column names, respecting the source file format. For example, let's say our source file contains only the author ID and the author name information: "1","John Smith" "2","Maria Sunshine" We'd have to put id, name in Column names to match the source file. When we click Go, the import is executed and we get a confirmation. We might also see the actual INSERT queries generated if the total size of the file is not too big. Import has been successfully finished, 2 queries executed.INSERT INTO `author` VALUES ('1', 'John Smith', '+01 445 789-1234')# 1 row(s) affected.INSERT INTO `author` VALUES ('2', 'Maria Sunshine', '333-3333')# 1 row(s) affected.
Read more
  • 0
  • 0
  • 13349

article-image-documenting-your-python-project-part1
Packt
12 Oct 2009
7 min read
Save for later

Documenting Your Python Project-part1

Packt
12 Oct 2009
7 min read
Documenting Your Project Documentation is work that is often neglected by developers and sometimes by managers. This is often due to a lack of time towards the end of development cycles, and the fact that people think they are bad at writing. Some of them are bad, but the majority of them are able to produce fine documentation. In any case, the result is a disorganized documentation made of documents that are written in a rush. Developers hate doing this kind of work most of the time. Things get even worse when existing documents need to be updated. Many projects out there are just providing poor, out-of-date documentation because the manager does not know how to deal with it. But setting up a documentation process at the beginning of the project and treating documents as if they were modules of code makes documenting easier. Writing can even be fun when a few rules are followed. This article provides a few tips to start documenting your project through: The seven rules of technical writing that summarize the best practices A reStructuredText primer, which is a plain text markup syntax used in most Python projects A guide for building good project documentation The Seven Rules of Technical Writing Writing good documentation is easier in many aspects than writing a code. Most developers think it is very hard, but by following a simple set of rules it becomes really easy. We are not talking here about writing a book of poems but a comprehensive piece of text that can be used to understand a design, an API, or anything that makes up the code base. Every developer is able to produce such material, and this section provides seven rules that can be applied in all cases. Write in two steps: Focus on ideas, and then on reviewing and shaping your text. Target the readership: Who is going to read it? Use a simple style: Keep it straight and simple. Use good grammar. Limit the scope of the information: Introduce one concept at a time. Use realistic code examples: Foos and bars should be dropped. Use a light but sufficient approach: You are not writing a book! Use templates: Help the readers to get habits. These rules are mostly inspired and adapted from Agile Documenting, a book by Andreas Rüping that focuses on producing the best documentation in software projects. Write in Two Steps Peter Elbow, in Writing with Power, explains that it is almost impossible for any human being to produce a perfect text in one shot. The problem is that many developers write documentation and try to directly come up with a perfect text. The only way they succeed in this exercise is by stopping the writing after every two sentences to read them back, and do some corrections. This means that they are focusing both on the content and the style of the text. This is too hard for the brain and the result is often not as good as it could be. A lot of time and energy is spent in polishing the style and shape of the text, before its meaning is completely thought through. Another approach is to drop the style and organization of the text and focus on its content. All ideas are laid down on paper, no matter how they are written. The developer starts to write a continuous stream and does not pause when he or she makes grammatical mistakes, or for anything that is not about the content. For instance, it does not matter if the sentences are barely understandable as long as the ideas are written down. He or she just writes down what he wants to say, with a rough organization. By doing this, the developer focuses on what he or she wants to say and will probably get more content out of his or her brain than he or she initially thought he or she would. Another side-effect when doing free writing is that other ideas that are not directly related to the topic will easily go through the mind. A good practice is to write them down on a second paper or screen when they appear, so they are not lost, and then get back to the main writing. The second step consists of reading back the whole text and polishing it so that it is comprehensible to everyone. Polishing a text means enhancing its style, correcting its faults, reorganizing it a bit, and removing any redundant information it has. When the time dedicated to write documentation is limited, a good practice is to cut this time in two equal durations—one for writing the content, and one to clean and organize the text. Focus on the content, and then on style and cleanliness. Target the Readership When starting a text, there is a simple question the writer should consider: Who is going to read it? This is not always obvious, as a technical text explains how a piece of software works, and is often written for every person who might get and use the code. The reader can be a manager who is looking for an appropriate technical solution to a problem, or a developer who needs to implement a feature with it. A designer might also read it to know if the package fits his or her needs from an architectural point of view. Let's apply a simple rule: Each text should have only one kind of readers. This philosophy makes the writing easier. The writer precisely knows what kind of reader he or she is dealing with. He or she can provide a concise and precise documentation that is not vaguely intended for all kinds of readers. A good practice is to provide a small introductory text that explains in one sentence what the documentation is about, and guides the reader to the appropriate part: Atomisator is a product that fetches RSS feeds and saves them in adatabase, with a filtering process.If you are a developer, you might want to look at the API description(api.txt)If you are a manager, you can read the features list and the FAQ(features.txt)If you are a designer, you can read the architecture andinfrastructure notes (arch.txt) By taking care of directing your readers in this way, you will probably produce better documentation. Know your readership before you start to write. Use a Simple Style Seth Godin is one of the best-selling writers on marketing topics. You might want to read Unleashing the Ideavirus, which is available for free on the Internet http://en.wikipedia.org/wiki/Unleashing_the_Ideavirus. Lately, he made an analysis on his blog to try to understand why his books sold so well. He made a list of all best sellers in the marketing area and compared the average number of words per sentences in each one of them. He realized that his books had the lowest number of words per sentence (thirteen words). This simple fact, Seth explained, proved that readers prefer short and simple sentences, rather than long and stylish ones. By keeping sentences short and simple, your writings will consume less brain power for their content to be extracted, processed, and then understood. Writing technical documentation aims to provide a software guide to readers. It is not a fiction story, and should be closer to your microwave notice than to the latest Stephen King novel. A few tips to keep in mind are: Use simple sentences; they should not be longer than two lines. Each paragraph should be composed of three or four sentences, at the most, that express one main idea. Let your text breathe. Don't repeat yourself too much: Avoid journalistic styles where ideas are repeated again and again to make sure they are understood. Don't use several tenses. Present tense is enough most of the time. Do not make jokes in the text if you are not a really fine writer. Being funny in a technical book is really hard, and few writers master it. If you really want to distill some humor, keep it in code examples and you will be fine. You are not writing fiction, so keep the style as simple as possible.
Read more
  • 0
  • 0
  • 8137

article-image-securing-your-trixbox-server
Packt
12 Oct 2009
6 min read
Save for later

Securing Your trixbox Server

Packt
12 Oct 2009
6 min read
Start with a good firewall Never have your trixbox system exposed completely on the open Internet; always make sure it is behind a good firewall. While many people think that because trixbox is running on Linux, it is totally secure, Linux, like anything else, has its share of vulnerabilities, and if things are not configured properly, is fairly simple for hackers to get into. There are really good open-source firewalls available, such as pfSense, Viata, and M0n0Wall. Any access to system services, such as HTTP or SSH, should only be done via a VPN or using a pseudo-VPN such as Hamachi. The best designed security starts with being exposed to the outside world as little as possible. If we have remote extensions that cannot use VPNs, then we will be forced to leave SIP ports open, and the next step will be to secure those as well. Stopping unneeded services Since trixbox CE is basically a stock installation of CentOS Linux, very little hardening has been done to the system to secure it. This lack of security is intentional as the first level of defence should always be a good firewall. Since there will be people who still insist on putting the system in a data center with no firewall, some care will need to be taken to ensure that the system is as secure as possible. The first step is to disable any services that are running that could be potential security vulnerabilities. We can see the list of services that are used with the chkconfig –list command. [trixbox1.localdomain rules]# chkconfig --listanacron 0:off 1:off 2:on 3:on 4:on 5:on 6:offasterisk 0:off 1:off 2:off 3:off 4:off 5:off 6:offavahi-daemon 0:off 1:off 2:off 3:off 4:off 5:off 6:offavahi-dnsconfd 0:off 1:off 2:off 3:off 4:off 5:off 6:offbgpd 0:off 1:off 2:off 3:off 4:off 5:off 6:offcapi 0:off 1:off 2:off 3:off 4:off 5:off 6:offcrond 0:off 1:off 2:on 3:on 4:on 5:on 6:offdc_client 0:off 1:off 2:off 3:off 4:off 5:off 6:offdc_server 0:off 1:off 2:off 3:off 4:off 5:off 6:offdhcpd 0:off 1:off 2:off 3:off 4:off 5:off 6:offdhcrelay 0:off 1:off 2:off 3:off 4:off 5:off 6:offez-ipupdate 0:off 1:off 2:off 3:off 4:off 5:off 6:offhaldaemon 0:off 1:off 2:off 3:on 4:on 5:on 6:offhttpd 0:off 1:off 2:off 3:on 4:on 5:on 6:offip6tables 0:off 1:off 2:off 3:off 4:off 5:off 6:offiptables 0:off 1:off 2:off 3:off 4:off 5:off 6:offisdn 0:off 1:off 2:off 3:off 4:off 5:off 6:offkudzu 0:off 1:off 2:off 3:on 4:on 5:on 6:offlm_sensors 0:off 1:off 2:on 3:on 4:on 5:on 6:offlvm2-monitor 0:off 1:on 2:on 3:on 4:on 5:on 6:offmDNSResponder 0:off 1:off 2:off 3:on 4:on 5:on 6:offmcstrans 0:off 1:off 2:off 3:off 4:off 5:off 6:offmdmonitor 0:off 1:off 2:on 3:on 4:on 5:on 6:offmdmpd 0:off 1:off 2:off 3:off 4:off 5:off 6:offmemcached 0:off 1:off 2:on 3:on 4:on 5:on 6:offmessagebus 0:off 1:off 2:off 3:on 4:on 5:on 6:offmultipathd 0:off 1:off 2:off 3:off 4:off 5:off 6:offmysqld 0:off 1:off 2:off 3:on 4:on 5:on 6:offnamed 0:off 1:off 2:off 3:off 4:off 5:off 6:offnetconsole 0:off 1:off 2:off 3:off 4:off 5:off 6:offnetfs 0:off 1:off 2:off 3:on 4:on 5:on 6:offnetplugd 0:off 1:off 2:off 3:off 4:off 5:off 6:offnetwork 0:off 1:off 2:on 3:on 4:on 5:on 6:offnfs 0:off 1:off 2:off 3:off 4:off 5:off 6:offnfslock 0:off 1:off 2:off 3:on 4:on 5:on 6:offntpd 0:off 1:off 2:off 3:on 4:on 5:on 6:offospf6d 0:off 1:off 2:off 3:off 4:off 5:off 6:offospfd 0:off 1:off 2:off 3:off 4:off 5:off 6:offportmap 0:off 1:off 2:off 3:on 4:on 5:on 6:offpostfix 0:off 1:off 2:on 3:on 4:on 5:on 6:offrdisc 0:off 1:off 2:off 3:off 4:off 5:off 6:offrestorecond 0:off 1:off 2:on 3:on 4:on 5:on 6:offripd 0:off 1:off 2:off 3:off 4:off 5:off 6:offripngd 0:off 1:off 2:off 3:off 4:off 5:off 6:offrpcgssd 0:off 1:off 2:off 3:on 4:on 5:on 6:offrpcidmapd 0:off 1:off 2:off 3:on 4:on 5:on 6:offrpcsvcgssd 0:off 1:off 2:off 3:off 4:off 5:off 6:offsaslauthd 0:off 1:off 2:off 3:off 4:off 5:off 6:offsnmpd 0:off 1:off 2:off 3:off 4:off 5:off 6:offsnmptrapd 0:off 1:off 2:off 3:off 4:off 5:off 6:offsshd 0:off 1:off 2:on 3:on 4:on 5:on 6:offsyslog 0:off 1:off 2:on 3:on 4:on 5:on 6:offvsftpd 0:off 1:off 2:off 3:off 4:off 5:off 6:offxinetd 0:off 1:off 2:off 3:on 4:on 5:on 6:offzaptel 0:off 1:off 2:on 3:on 4:on 5:on 6:offzebra 0:off 1:off 2:off 3:off 4:off 5:off 6:off The highlighted lines are services that are started automatically on system startup. The following list of services is required by trixbox CE and should not be disabled: Anacron crond haldaemon httpd kudzu lm_sensors lvm2-monitor mDNSResponder mdmonitor memcached messagebus mysqld network ntpd postfix sshd syslog xinetd zaptel To disable a service, we use the command chkconfig <servicename> off. We can now turn off some of the services that are not needed: chkconfig ircd offchkconfig netfs offchkconfig nfslock offchkconfig openibd offchkconfig portmap offchkconfig restorecond offchkconfig rpcgssd offchkconfig rpcidmapd offchkconfig vsftpd off We can also stop the services immediately without having to reboot: service ircd stopservice netfs stopservice nfslock stopservice openibd stopservice portmap stopservice restorecond stopservice rpcgssd stopservice rpcidmapd stopservice vsftpd stop Securing SSH A very large misconception is that by using SSH to access your system, you are safe from outside attacks. The security of SSH access is only as good as the security you have used to secure SSH access. Far too often, we see systems that have been hacked because their root password is very simple to guess (things like password or trixbox are not safe passwords). Any dictionary word is not safe at all, and substituting numbers for letters is very poor practice as well. So, as long as SSH is exposed to the outside, it is vulnerable. The best thing to do, if you absolutely have to have SSH running on the open Internet, is to change the port number used to access SSH. This section will detail the best methods of securing your SSH connections. Create a remote login account First off, we should create a user on the system and only allow SSH connections from it. The username should be something that only you know and is not easily guessed. Here, we will create a user called trixuser and assign a password to it. The password should be something with letters, numbers, symbols, and not based on a dictionary word. Also, try to string it into a sentence making sure to use the letters, numbers, and symbols. Spaces in passwords work well too, and are hard to add in scripts that might try to break into your server. A nice and simple tool for creating hard-to-guess passwords can be found at http://www.pctools.com/guides/password/. [trixbox1.localdomain init.d]# useradd trixuser[trixbox1.localdomain init.d]# passwd trixuser Now, ensure that the new account works by using SSH to log in to the trixbox CE server with this new account. If it does not let you in, make sure the password is correct or try to reset it. If it works, continue on. Only allowing one account access to the system over SSH is a great way to lock out most brute force attacks. To do this, we need to edit the file in /etc/ssh/sshd_config and add the following to the file. AllowUsers trixuser The PermitRootLogin setting can be edited so that root can't log in over SSH. Remove the # from in front of the setting and change the yes to no. PermitRootLogin no
Read more
  • 0
  • 0
  • 4058
article-image-social-bookmarking-blogger-part-2
Packt
12 Oct 2009
6 min read
Save for later

Social Bookmarking in Blogger: Part 2

Packt
12 Oct 2009
6 min read
Adding buttons gives the site a more homemade feel, but it is time consuming to hunt down the links to the different services on the social networking sites. Wouldn't it be great if there was a third-party service out there that did the gathering for you? AddThis (http://www.addthis.com) offers a multi-bookmark widget popular with many bloggers. Offering Multiple Bookmarks with One Button Using a widget like the one offered by AddThis frees you to spend your time blogging. You can choose to show all the main bookmark networks or pick and choose from an extensive list. We'll configure the widget and then install it on our blog. Time for Action!—Offering Multiple Bookmarks with AddThis Register at the AddThis (http://www.addthis.com) site. Georgia has already created an account for Fruit for All. The AddThis Social Widget Builder screen has multiple options to customize the widget code. Choose the Bookmarking widget option from the Which kind of widget? drop-down box. Select the style of bookmark button you want to use. We will choose the second one. The on a Blog option should be selected for Where? Choose Blogger for the Blogging Platform and then click Get Your Free Button>> for the code. Next, AddThis will provide you with the code. Copy the code from the site or type the code below in place of the button links, above the <p class='post-footer-line post-footer-line-2'> tag in the template code: <!-- AddThis Bookmark Post Dropdown BEGIN --> <div> <script type='text/javascript'>addthis_url='<data:post.url/>'; addthis_title='<data:post.title/>'; addthis_pub='fruitforall';</script> <script src='http://s7.addthis.com/js/addthis_widget.php?v=12' type='text/javascript'></script> </div> <!-- AddThis Bookmark Post Dropdown END --> Save the template changes and view the blog. Try hovering the cursor over the Bookmark button to see whether the list of bookmarks appears. The button looks great. We need to test an icon to see how AddThis submits posts. Click the Del.icio.us icon to bring up the submission window. The URL, description (title), and tags were auto populated for us. Taking a note of the recommended tags will help us label future posts, and will guide us in adding more labels to the current post. What Just Happened? The AddThis button replaced our group of social bookmark buttons. When the visitor hovers their cursor over the button, a list of social bookmark icons appear. The visitor also has the option to choose from social bookmarks not listed in the main group. A new window opens with a submission form for the service we selected. After the form is filled out, AddThis collects statistical data for us and displays it graphically on our AddThis account page. The icons displayed on the button can be changed on the AddThis site. You can't predict which bookmarks your visitors use. Using a multiple bookmark aggregator such as AddThis keeps your posts free of bookmark clutter while giving visitors more bookmarking choices. There are other options as well. ShareThis (http://www.sharethis.com) has recently released the latest version of its multiple bookmark service, which includes tracking. It is available at http://sharethis.com/publisher/. Adding Dynamic Counters to Bookmark Links Showing counters on social bookmark icons is becoming popular. Dynamic counters are offered by bookmark services Reddit, Del.icio.us, Ma.gnolia, and Digg. Bookmark services are adding their own counters every day. Readers can quickly see if a post has already been submitted to a service and can vote to increase or decrease the popularity of the post while still at the blog. We will add the popular del.icio.us dynamic bookmark and examine the features it offers. We will then explore and then explore using Feedburner Flare (http://www.feedburner.com) to show multiple counters easily. Time for Action!—Adding Dynamic Links with Counters to Posts Navigate to the Edit HTML screen on the blog, and click the Expand Widget Templates checkbox. Type the following block of code directly above the <p class='post-footer-line post-footer-line-2'> tag in the template code, deleting any existing social bookmark code we added before: <script type="text/javascript">if (typeof window.Delicious == "undefined") window.Delicious = {}; Delicious.BLOGBADGE_DEFAULT_CLASS = 'delicious- blogbadge-line';</script> <script src="http://images.del.icio.us/static/js/ blogbadge.js"></script> Save the template, and view the blog to see the changes. An example of how it should look now is shown in the following screenshot: Are there any differences between the information captured using this bookmark and others? Let's test the bookmark and find it out. Click on bookmark this on the del.icio.us button and review the results: The bookmark does not display the actual post title and post URL. We will need to customize it to display that information when the reader submits the post. What Just Happened? We inserted a ready made counter bookmark script from the del.icio.us site into our template code. The first JavaScript code snippet will check to see if a link to del.icio.us already exists. If it does not, a special default CSS class is set to control the appearance of the badge. The code is shown for reference below: <script type="text/javascript">if (typeof window.Delicious == "undefined") window.Delicious = {}; Delicious.BLOGBADGE_DEFAULT_CLASS = 'delicious-blogbadge-line';</script> Calling the code controlling the badge counter is done with the final script tag. It links to an external JavaScript file stored at the del.icio.us site. <script src="http://images.del.icio.us/static/js/blogbadge.js"> </script> The script counts how many times readers have recommended the blog site to del.icio.us using their own script counter. The number shown will increase each time the site is bookmarked by someone on del.icio.us.
Read more
  • 0
  • 0
  • 2397

article-image-customizing-and-extending-aspnet-mvc-framework
Packt
12 Oct 2009
5 min read
Save for later

Customizing and Extending the ASP.NET MVC Framework

Packt
12 Oct 2009
5 min read
(For more resources on .NET, see here.) Creating a control When building applications, you probably also build controls. Controls are re-usable components that contain functionality that can be re-used in different locations. In ASP.NET Webforms, a control is much like an ASP.NET web page. You can add existing web server controls and markup to a custom control and define properties and methods for it. When, for example, a button on the control is clicked, the page is posted back to the server that performs the actions required by the control. The ASP.NET MVC framework does not support ViewState and postbacks, and therefore, cannot handle events that occur in the control. In ASP.NET MVC, controls are mainly re-usable portions of a view, called partial views, which can be used to display static HTML and generated content, based on ViewData received from a controller. In this topic, we will create a control to display employee details. We will start by creating a new ASP.NET MVC application using File | New | Project... in Visual Studio, and selecting ASP.NET MVC Application under Visual C# - Web. First of all, we will create a new Employee class inside the Models folder. The code for this Employee class is: public class Employee{ public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string Department { get; set; }} On the home page of our web application, we will list all of our employees. In order to do this, modify the Index action method of the HomeController to pass a list of employees to the view in the ViewData dictionary. Here's an example that creates a list of two employees and passes it to the view: public ActionResult Index(){ ViewData["Title"] = "Home Page"; ViewData["Message"] = "Our employees welcome you to our site!"; List<Employee> employees = new List<Employee> { new Employee{ FirstName = "Maarten", LastName = "Balliauw", Email = "maarten@maartenballiauw.be", Department = "Development" }, new Employee{ FirstName = "John", LastName = "Kimble", Email = "john@example.com", Department = "Development" } }; return View(employees);} The corresponding view, Index.aspx in the Views | Home folder of our ASP.NET MVC application, should be modified to accept a List<Employee> as a model. To do this, edit the code behind the Index.aspx.cs file and modify its contents as follows: using System.Collections.Generic;using System.Web.Mvc;using ControlExample.Models;namespace ControlExample.Views.Home{ public partial class Index : ViewPage<List<Employee>> { }} In the Index.aspx view, we can now use this list of employees. Because we will display details of more than one employee somewhere else in our ASP.NET MVC web application, let's make this a partial view. Right-click the Views | Shared folder, click on Add | New Item... and select the MVC View User Control item template under Visual C# | Web | MVC. Name the partial view, DisplayEmployee.ascx. The ASP.NET MVC framework provides the flexibility to use a strong-typed version of the ViewUserControl class, just as the ViewPage class does. The key difference between ViewUserControl and ViewUserControl<T>is that with the latter, the type of view data is explicitly passed in, whereas the non-generic version will contain only a dictionary of objects. Because the DisplayEmployee.aspx partial view will be used to render items of the type Employee, we can modify the DisplayEmployee. ascx code behind the file DisplayEmployee.ascx.cs and make it strong-typed: using ControlExample.Models;namespace ControlExample.Views.Shared{ public partial class DisplayEmployee : System.Web.Mvc.ViewUserControl<Employee> { }} In the view markup of our partial view, the model can now be easily referenced. Just as with a regular ViewPage, the ViewUserControl will have a ViewData property containing a Model property of the type Employee. Add the following code to DisplayEmployee.ascx: <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="DisplayEmployee.ascx.cs" Inheits="ControlExample.Views.Shared.DisplayEmployee" %><%=Html.Encode(Model.LastName)%>, <%=Html.Encode(Model.FirstName)%><br/><em><%=Html.Encode(Model.Department)%></em> The control can now be used on any view or control in the application. In the Views | Home | Index.aspx view, use the Model property (which is a List<Employee>) and render the control that we have just created for each employee: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Index.aspx.cs"Inherits="ControlExample.Views.Home.Index" %><asp:Content ID="indexContent" ContentPlaceHolderID="MainContent"runat="server"> <h2><%= Html.Encode(ViewData["Message"]) %></h2> <p>Here are our employees:</p> <ul> <% foreach (var employee inModel) { %> <li> <% Html.RenderPartial("DisplayEmployee", employee); %> </li> <% } %> </ul></asp:Content> In case the control's ViewData type is equal to the view page's ViewData type, another method of rendering can also be used. This method is similar to ASP.NET Webforms controls, and allows you to specify a control as a tag. Optionally, a ViewDataKey can be specified. The control will then fetch its data from the ViewData dictionary entry having this key. <uc1:EmployeeDetails ID="EmployeeDetails1" runat="server" ViewDataKey="...." /> For example, if the ViewData contains a key emp that is filled with an Employee instance, the user control could be rendered using the following markup: <uc1:EmployeeDetails ID="EmployeeDetails1" runat="server" ViewDataKey="emp" /> After running the ASP.NET MVC web application, the result will appear as shown in the following screenshot:
Read more
  • 0
  • 0
  • 6993
Modal Close icon
Modal Close icon