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

7018 Articles
article-image-all-new-september-open-source-books-packt
Packt
28 Sep 2010
1 min read
Save for later

All New September Open Source Books from Packt

Packt
28 Sep 2010
1 min read
  Moodle 2.0 First Look Discover what's new in Moodle 2.0, how the new features work, and how it will impact you. Click for more information MySQL for Python Integrate the flexibility of Python and the power of MySQL to boost the productivity of your Python applications. Click for more information Implementing SugarCRM 5.x A complete guide to implementing SugarCRM including needs assessment, installing and using the software, training users, integrating with existing systems, and more. Click for more information WordPress Top Plugins Find and install the best plugins for generating and sharing content, building communities and generating revenue. Click for more information Building job sites with Joomla! A practical stepwise tutorial to build your professional website using Joomla! Click for more information WordPress 3.0 jQuery Enhance your WordPress website with the captivating effects of jQuery. Click for more information Alfresco 3 Web Content Management Create an infrastructure to manage all your web content, and deploy it to various external production systems. Click for more information  
Read more
  • 0
  • 0
  • 1179

article-image-drupal-site-configuration-performance-maintenance-logging-and-errors-and-reports
Packt
28 Sep 2010
9 min read
Save for later

Drupal Site Configuration: Performance, Maintenance, Logging and Errors and Reports

Packt
28 Sep 2010
9 min read
  Drupal 7 A comprehensive beginner's guide to installing, configuring, and building a professional Drupal 7 website Set up, configure, and deploy a Drupal 7 website Easily add exciting and powerful features Design and implement your website's look and feel Promote, manage, and maintain your live website In-depth coverage of Drupal's new core features, including image handling and fields Extended media coverage Completely new coverage on Views Improved and updated coverage on themes and theming Over 150 online quiz questions and exercises included Revised and updated for Drupal 7 based on comments from thousands of readers Read more about this book (For more resources on Drupal, see here.) Performance Every once in a while, someone makes a site that becomes wildly popular. Having many people visiting all at once can put some serious strain on the server's resources and cause all sorts of problems as the congestion builds. If you are unsure about what resources are available on your site, check with the hosting service and find out what they provide in the way of disk space, monthly transfer, and transfer speed. Many hosting services will boast unlimited bandwidth, but won't talk about connection speed. In other words, they don't meter how much water you use because they only let you switch the hosepipe on half way. It's important to know the limitations of the hardware and network resources, but don't fall into the trap of believing this is the most important thing to know. Ensuring that there are facilities in place to handle a large amount of traffic will go some way in ensuring that your site scales well. It's a time-honored tradition in the corporate world to throw extra resources at computing problems—buying the latest, fastest servers to help speed up slow applications, upgrading network hardware to allow data to travel more freely, and so on. Invariably though, poorly designed software, or software that is poorly tuned for performance always finds a way to utilize all the resources one can throw at it and still want more. More often than not, it is better to look at why software is chewing up resources and see what can be done to either stop it or at least alleviate the problem, so that the software utilizes its resources wisely. Drupal already has several strategies in place to help you, the site administrator, decide how and when to use resource-intensive modules and how to maximize the site's efficiency. Caching This section provides several options to improve the performance of your site, and as nothing in this world is really free, you need to understand that, by and large, obtaining a performance boost comes at the expense of something else—namely, how up-to-date content is. The following screenshot shows the performance page: The first option, CLEAR CACHE, is useful while making modifications to a site because it helps to ensure that changes are definitely displayed and not held up while the site cache is still in operation. Having the ability to clear the cache in order to view precisely how pages are being built is useful, but comes at a price. Remember that if you have a large site with lots of content, then Drupal will have to do a lot of work to rebuild its cache, and it is possible that users may notice a slowdown during this time. It is important to only enable caching on a live site, and not on the development machine, because changes to a page show up only when the cache expires—causing confusion if you are expecting something else during testing. As you know, Drupal uses PHP to build web pages that are returned to a user's browser. Most of the time, these pages are unchanged between requests, and Drupal ends up repeating the work of building the same page before sending it off to the other users who requested it. It makes sense to tell Drupal that if it has created a web page once, it should store a copy of this page and serve that copy instead of going through the trouble of recreating it. The process of storing copies of web pages in order to reduce the amount of effort required to repeatedly create a page is known as caching. The trade-off when using page caching is that any changes to a page are only shown to the users once that cached version has expired and been replaced. This makes caching a suitable method for boosting performance whenever content is not updated very often or when it is not important to have new content presented immediately. You will need to decide how long you think it is suitable to go before any updates made to a page must be shown—the longer you leave a page cached, the less work Drupal has to do, but the longer it will take for new content to show on the site. If your site is a daily blog, then by all means set the cache for up to a day at a time. If your site is a super busy, breaking news portal, then clearly you would opt for a cache time in minutes. Drupal also has the ability to cache the content of blocks, which can be a real performance boost for authenticated users (since page caching is only available for anonymous users). Blocks are constructed independently from the page as a whole, and often require expensive database requests or other operations in order to provide the information they contain. Enabling block caching means that blocks no longer have to query the database (or whatever else it is they are doing) each time a page refreshes. Rather, they simply serve up the cached version and save on all that work. Again, make sure you carefully weigh up the benefits between having fresh content and having high performance. Bandwidth optimization BANDWIDTH OPTIMIZATION, shown at the bottom of the page in the previous screenshot, deals with how to best transfer data from your server across the Internet to the users' browsers. The way in which data is transferred plays a big role in optimizing performance. In general, the most important things to remember are: Keep files small Keep the number of files down As shown, Drupal can aggregate and compress disparate CSS and JavaScript files in order to reduce the size and number of requests made to a server. Obviously, this has a huge number of benefits, especially if you are charged for bandwidth usage. Again, don't aggregate files during development. Turn this feature on only once the site has gone live, otherwise you are in for some serious frustration when changes to themes or scripts don't show up or behave as expected. Maintenance I should make the following point very clear: All major development or changes to a site should be performed on the development machine and thoroughly tested before being implemented or ported to the live site. There will be times, however, when you simply have to make some changes directly to the live site—even if it is only to implement upgrades that have already been tested out on the development server. If this is the case, then rather than allow users to browse a site under maintenance, visit the Maintenance mode page in the Development section, and select Put site into maintenance mode, provide a Maintenance mode message to display if the default one is not suitable, and get on with your work. Be very careful when working in maintenance mode because once you have logged out you are effectively locked out too. This is because, by default, only one user (that is the administrative user) can do anything on the site while it is offline. If you log off and try logging in again, you are no longer the administrative user; you are instead anonymous and are shown only the offline message: This is not very helpful if you do happen to be the site administrator; so Drupal allows the login page to be accessed as normal. Navigate to http://localhost/ drupal/user, and you will be able to log in as the administrator and use the site without hindrance. Make sure you know the administrator's password before going into maintenance mode. Everyone else is locked out until the site is no longer under maintenance. Logging and errors Go to Logging and errors in the DEVELOPMENT section of the Configuration overlay. This page provides a few options used to control how errors are displayed and logged: Error messages to display allows you to decide whether to write errors to the screen or not. While you are busy building the site, it's useful to view All messages in order to determine what has gone wrong and when. However, once it is time to go live you should change this to None for security reasons. Doing so prevents Drupal from displaying information to malicious users who might be able to use it in an attack on your site. The final setting, Database log entries to keep, at least to begin with, is sensible. You may wish to increase or decrease the number of records stored on the system depending on how much work you have to do in order to maintain the site properly. Remember that Drupal can properly maintain the site's event logs only if the cron jobs are being run regularly. Having only one setting to make is not that exciting, but once the site is live and messages are no longer visible through the pages, you can check the logs in the Reports section. Doing this on a regular basis is a good strategy to ensure that the site continues to run smoothly. Error messages, warnings, and so on are effectively windows into the operations of the site, and are indispensable tools.
Read more
  • 0
  • 0
  • 1957

article-image-checking-openstreetmap-data-problems
Packt
27 Sep 2010
7 min read
Save for later

Checking OpenStreetMap Data for Problems

Packt
27 Sep 2010
7 min read
  OpenStreetMap Be your own cartographer Collect data for the area you want to map with this OpenStreetMap book and eBook Create your own custom maps to print or use online following our proven tutorials Collaborate with other OpenStreetMap contributors to improve the map data Learn how OpenStreetMap works and why it's different to other sources of geographical information with this professional guide Read more about this book (For more resources on OpenStreetMap, see here.) It's important to remember that there are few fixed ideas of what is "wrong" data in OpenStreetMap. It should certainly be an accurate representation of the real world, but that's not something an automatic data-checking tool can detect. There may be typographical errors in tags that prevent them from being recognized, but there are also undocumented tags that may accurately describe a feature, yet be unknown to anyone except the mapper who used them. The latter is fine, but the former is a problem. It's tempting to use the two map renderings on openstreetmap.org as a debugging tool, but this can be misleading. Not every possible feature is rendered, and many problems with the data, such as duplicate nodes or unjoined ways, won't be obvious from a rendered map. If a feature you've mapped doesn't render when a similarly tagged one does, there's an issue, but a feature appearing in the map doesn't mean it's free of problems, and a feature that doesn't appear isn't necessarily wrong. Ultimately, you will have to use your own judgment to find out whether or not an issue reported by one of these tools is really an error in the data. You can always contact other members of the OpenStreetMap community. This is only a selection of the more widely used quality assurance tools used by mappers. For a more complete list, refer to http://wiki.openstreetmap.org/wiki/Quality_Assurance. Inspecting data with openstreetmap.org's data overlay and browser The openstreetmap.org website has a range of tools you can use to inspect the data in the database, both current and past. Some of the tools aren't obvious from the front page of the site, but are easily found if you know where they are. The tools, which consist of the data map overlay and the data browser pages, allow you to see the details of any object in the OpenStreetMap database, including coordinates, tags, and editing history, without the need to launch an editor or read raw XML. As these tools work directly with the data in the OpenStreetMap database, they always show the most up-to-date information available. However, they simply provide raw information, and don't provide any guidance on whether the geometry or tagging of any feature could be problematic. The easiest way of inspecting data is to start with the data map overlay. Go to the map view and find Compton (or any other area you want to inspect). Open the layer chooser by clicking on the + sign at the top-right. Click the checkbox labeled Data, and a box will appear to the left of the map view. After a short delay, the data overlay will appear, and a list of objects will appear in the box. JavaScript speed and the OpenStreetMap data overlay The data overlay and the accompanying list of objects make heavy use of JavaScript in your browser, and depending on how many objects are currently in your map view, can use a lot of processing power and memory. Some older browsers may struggle to even show the data overlay. Mappers have reported that Firefox 3.5, Apple Safari, and Google Chrome all work well with the data overlay, even with large numbers of objects. Once the data for the area you're inspecting has loaded, you'll see something like the following image: In the preceding image, on the left you can see the Object list, which gives a text description of every feature in the current map view, giving its primitive type and either its ID number or a name, if the feature has one. On the right is the map with the data overlay, which highlights every feature in the current area, whether they're rendered on the map or not. This last point is worth repeating: Not every type of feature gets rendered on the two map renderings used on openstreetmap.org, and those that do can take some time to appear if the load on the rendering engines is high. Any feature in the database will always appear in the data overlay. Inspecting a single feature To inspect an individual feature, either click on its entry in the object list, or on its highlight in the map view. Both the object list and the overlay will change to reflect this. Occasionally, an area feature may get drawn on top of other features, preventing you from selecting the ones underneath, but you'll still be able to select them from the list. Let's select The Street and inspect its data. Either click on its name in the object list, or on the way in the map view, and the object list should change to show the tags applied to the feature, and you should see something like the following in the object list: This gives a list of the tags attached to the feature. If you click on Show History, a list of the edits made to the current feature is added to the list. To get more information, click on the Details link next to the feature's name, and you'll be taken to the data browser page for that object, as follows: Here you see far more details about the feature we're inspecting. Apart from the object ID and its name, you can find the time when the object was last edited and by whom, and in which changeset. There are clickable links to any related objects and a map showing the feature's location. At the bottom of the page are links to the raw XML of the feature, the history page of the feature, and a link to launch Potlatch—the online editor—for the area surrounding the feature. Checking a feature's editing history The OpenStreetMap database keeps every version of every feature created, so you can inspect previous versions and see when and how a feature has changed. To look at a feature's history, click on the link at the bottom of its data browser page. For the Watts Gallery in Compton, you should see something like the following: You can see each version of the object listed in full, including which mapper created that version in which changeset, and what the tags for that version were. There's currently no way of showing any previous version or the changes between versions on the map, but third-party tools such as OSM Mapper provide some of these features. Inspecting changesets Along with looking at individual features, you can see how the map gets changed by looking at changesets. Since version 0.6 of the OpenStreetMap API went live in April 2009, every change to the map has to be part of a changeset. A changeset is a list of related edits made to OpenStreetMap data, with its own set of tags. What goes into a changeset is entirely up to the mapper creating it. You can view the list of recent changesets by clicking on the History tab at the top of the map view. This will show a list of the 20 most recent changesets whose bounding box intersects your current map view. Note that this doesn't guarantee that any changesets listed include any edits in your current view, and any changesets covering a large area will be marked with (big) in the list.
Read more
  • 0
  • 0
  • 3161

article-image-creating-your-own-functions-mysql-python
Packt
27 Sep 2010
6 min read
Save for later

Creating Your Own Functions in MySQL for Python

Packt
27 Sep 2010
6 min read
  MySQL for Python Integrate the flexibility of Python and the power of MySQL to boost the productivity of your Python applications Implement the outstanding features of Python's MySQL library to their full potential See how to make MySQL take the processing burden from your programs Learn how to employ Python with MySQL to power your websites and desktop applications Apply your knowledge of MySQL and Python to real-world problems instead of hypothetical scenarios A manual packed with step-by-step exercises to integrate your Python applications with the MySQL database server Read more about this book (For more resources on Phython see here.) Hello() To create a function, we necessarily have to go back to the CREATE statement. As in a Python function definition, MySQL expects us to declare the name of the function as well as any arguments it requires. Unlike Python, MySQL also wants the type of data that will be received by the function. The beginning of a basic MySQL function definition looks like this: CREATE FUNCTION hello(s CHAR(20)) MySQL then expects to know what kind of data to return. Again, we use the MySQL data type definitions for this. RETURNS CHAR(50) This just tells MySQL that the function will return a character string of 50 characters or less. If the function will always perform the same task, it is best for the sake of performance to include the keyword DETERMINISTIC next. If the behavior of the function varies, use the keyword NON-DETERMINISTIC. If no keyword is set for the characteristic of the function, MySQL defaults to NON-DETERMINISTIC. You can learn more about the characteristic keywords used in function definitions at: http://dev.mysql.com/doc/refman/5.5/en/create-procedure.html Finally comes the meat of the function definition. Here we can set variables and perform any calculations that we want. For our basic definition, we will simply return a concatenated string: RETURN CONCAT('Hello, ', s, '!'); The function obviously concatenates the word 'Hello' with whatever argument is passed to it and appends an exclamation point at the end. To call it we use SELECT as with the other functions: mysql> SELECT hello('world') as Greeting; Capitalise() A function to capitalize every initial letter in a string follows the same pattern. The main point of the function is to walk through the string, character by character, and use UPPER() on every character that does not follow a letter. DELIMITER Obviously, we need a way to pass the entire function to MySQL without having any of the lines evaluated until we call it. To do this, we use the keyword DELIMITER. DELIMITER allows users to tell MySQL to evaluate lines that end in the character(s) we set. So the process for complex function definitions becomes: Change the delimiter. Pass the function with the usual semicolons to indicate the end of the line. Change the delimiter back to a semicolon. Call the function. The DELIMITER keyword allows us to specify more than one character as the line delimiter. So in order to ensure we don't need to worry about our code inadvertently conflicting with a line delimiter, let's make the delimiter @@: DELIMITER @@ The function definition From here, we are free to define a function to our specification. The definition line will read as follows: CREATE FUNCTION `Capitalise`(instring VARCHAR(1000)) The function will return a character string of similar length and variability: RETURNS VARCHAR(1000) When MySQL functions extend beyond the simplest calculations, such as hello(), MySQL requires us to specify the beginning and ending of the function. We do that with the keywords BEGIN and END. So let's begin the function: BEGIN Next, we need to declare our variables and their types using the keyword DECLARE: DECLARE i INT DEFAULT 1;DECLARE achar, imark CHAR(1);DECLARE outstring VARCHAR(1000) DEFAULT LOWER(instring); The DEFAULT keyword allows us to specify what should happen if outstring should fail for some reason. Next, we define a WHILE loop: WHILE i <= CHAR_LENGTH(instring) DO The WHILE loop obviously begins with a conditional statement based on the character length of instring. The resulting action begins with the keyword DO. From here, we set a series of variables and express what should happen where a character follows one of the following: blank space & '' _ ? ; : ! , - / ( . The operational part of the function looks like this: SET achar = SUBSTRING(instring, i, 1); SET imark = CASE WHEN i = 1 THEN ' ' ELSE SUBSTRING(instring, i - 1, 1) END CASE; IF imark IN (' ', '&', '''', '_', '?', ';', ':', '!', ',', '-', '/', '(', '.') THEN SET outstring = INSERT(outstring, i, 1, UPPER(achar)); END IF; SET i = i + 1; Much of this code is self-explanatory. It is worth noting, however, that the apodosis of any conditional in MySQL must end with the keyword END. In the case of IF, we use END IF. In the second SET statement, the keyword CASE is an evaluative keyword that functions similar to the try...except structure in Python. If the WHEN condition is met, the empty THEN apodosis is executed. Otherwise, the ELSE exception applies and the SUBSTRING function is run. The CASE structure ends with END CASE. MySQL will equally recognize the use of END instead. The subsequent IF clause evaluates whether imark, defined as the character before achar, is one of the declared characters. If it is, then that character in instring is replaced with its uppercase equivalent in outstring. After the IF clause is finished, the loop is incremented by one. After the entire string is processed, we then end the WHILE loop with: END WHILE; After the function's operations are completed, we return the value of outstring and indicate the end of the function: RETURN outstring;END@@ Finally, we must not forget to return the delimiter to a semicolon: DELIMITER ; It is worth noting that, instead of defining a function in a MySQL session we can define it in a separate file and load it on the fly with the SOURCE command. If we save the function to a file called capfirst.sql in a directory temp, we can source it relatively: We can also use: SOURCE /home/skipper/temp/capfirst.sql;
Read more
  • 0
  • 0
  • 9802

article-image-exception-handling-mysql-python
Packt
27 Sep 2010
7 min read
Save for later

Exception Handling in MySQL for Python

Packt
27 Sep 2010
7 min read
Why errors and warnings are good for you The value of rigorous error checking is exemplified in any of the several catastrophes arising from poor software engineering. Examples abound, but a few are particularly illustrative of what happens when bad data and design go unchallenged. On 4 June 1996, the first test flight of the Ariane 5 rocket self-destructed 37 seconds after its launch. The navigation code from Ariane 4 was reused in Ariane 5. The faster processing speed on the newer rocket caused an operand error. The conversion of a 64-bit floating-point value resulted in a larger-than-expected and unsupported 16-bit signed integer. The result was an overflow that scrambled the flight's computer, causing too much thrust to be passed by the rocket itself, resulting in the crash of US$370 million worth of technology. Widely considered to be one of the most expensive computer bugs in history, the crash arose due to mistakes in design and in subsequent error checking. On 15 January 1990, the American telecommunications company AT&T installed a new system on the switches that controlled their long-distance service. A bug in the software caused the computers to crash every time they received a message from one of their neighboring switches. The message in question just happened to be the same one that the switches send out when they recover from a system crash. The result: Within a short time, 114 switches across New York City were rebooting every six seconds, leaving around 60,000 people without long distance service for nine hours. The system ultimately had to be fixed by reinstalling the old software. On the Internet, a lack of proper error-checking still makes it possible for a malformed ping request to crash a server anywhere in the world. The Computer Emergency Response Team (CERT) Advisory on this bug, CA-1996-26, was released in 1996, but the bug persists. The original denial-of-service attack has thus evolved into the distributed denial-of-service attack employing botnets of zombie machines worldwide. More than any other part of a computing system, errors cost significantly more to fix later than if they were resolved earlier in the development process. It is specifically for this reason that Python outputs error messages to the screen, unless such errors are explicitly handled otherwise. A basic dynamic of computing is that the computer does not let anyone know what is happening inside itself. A simple illustration of this dynamic is as follows: x = 2 if x == 2: x = x + x Knowing Python and reading the code, we understand that the value of x is now 4. But the computer has provided us no indication of the value of x. What's more, it will not tell us anything unless we explicitly tell it to do so. Generally speaking, there are two ways you can ask Python to tell you what it's thinking: By outputting values to the screen By writing them to a file Here, a simple print statement would tell us the value of x. Output displayed on the screen or saved to a file are the most common ways for programs to report their status to users. However, the similar effect is done by indicator lights and other non-verbal forms of communication. The type of output is necessarily dependent on the hardware being used. By default, Python outputs all errors and warnings to the screen. As MySQL for Python is interpreted by Python, errors passed by MySQLdb are no different. This naturally gives the debugging programmer information for ironing out the performance of the program—whether determining why a program is not executing as planned or how to make it execute faster or more reliably. However, it also means that any information needed for tracing the error, along with parts of the code, is passed to the user, whoever they may be. This is great for debugging, but makes for terrible security. That is why the Zen of Python reads: Errors should never pass silently Unless explicitly silenced One needs the error messages to know why the program fails, but it is a security hazard to pass raw error messages to the user. If one wants the user to handle an error message, it should be sanitized of information that may compromise the security of the system. Handling exceptions correctly takes a lot of code. At the risk of sounding like a hypocrite, it should be noted that the exigencies of a printed book do not allow for the reproduction of constant, rigorous error-handling in the code examples such as this article espouses. Therefore, while I state this principle, the programming examples do not always illustrate it as they should. If they did, the book would be significantly thicker and heavier (and probably cost more too!). Further, the more complicated an application, the more robust the error-handling should be. Ultimately, every kind of error is covered by one of the several types that can be thrown by MySQL for Python. Each one of them allows for customized error messages to be passed to the user. With a bit of further coding, one can check the authentication level of the user and pass error messages according to their level of authorization. This can be done through a flag system or by using modules from the Python library. If the former is used, one must ensure that knowledge of the flag(s) used is guarded from unauthorized users. Alternatively, one can employ both systems by checking the authentication level of users or programs that pass a particular flag to the program. Errors versus warnings: There's a big difference As with Python in general, the main difference between errors and warnings is that warnings do not cause a program to terminate. Errors do. Warnings provide notice of something we should note; errors indicate the reason the program cannot continue. If not handled appropriately, warnings therefore pass process information to the user without interrupting the execution of the program. This lack of detectability makes warnings more dangerous to the security of an application, and the system in general, than errors. Consequently, the error-handling process of an application must account for both errors and warnings. While Python handles warnings and exceptions differently by default, especially with regard to program execution, both are written to stderr. Therefore, one handles them the same way that one handles standard errors. Additionally, one can set warnings to be silenced altogether or to carry the same gravity as an error. This level of functionality was introduced in Python 2.1. The two main errors in MySQLdb Python generally supports several kinds of errors, and MySQL for Python is no different. The obvious difference between the two is that MySQLdb's errors deal exclusively with the database connection. Where MySQLdb passes warnings that are not MySQL-specific, all exceptions are related to MySQL. The MySQL-specific exceptions are then classified as either warnings or errors. There is only one kind of warning, but MySQLdb allows two categories of errors—DatabaseError and InterfaceError. Of the former, there are six types that we will discuss here. DatabaseError When there is a problem with the MySQL database itself, a DatabaseError is thrown. This is an intermediate catch-all category of exceptions that deal with everything from how the data is processed (for example, errors arising from division by zero), to problems in the SQL syntax, to internal problems within MySQL itself. Essentially, if a connection is made and a problem arises, the DatabaseError will catch it. Several types of exceptions are contained by the DatabaseError type. We look at each of these in the section Handling exceptions passed from MySQL. InterfaceError When the database connection fails for some reason, MySQLdb will raise an InterfaceError. This may be caused from problems in the interface anywhere in the connection process.
Read more
  • 0
  • 0
  • 12260

article-image-creating-custom-wcm-workflow-group-using-alfresco-3
Packt
27 Sep 2010
13 min read
Save for later

Creating a Custom WCM Workflow for a Group using Alfresco 3

Packt
27 Sep 2010
13 min read
(For more resources on Alfresco 3, see here.) You can define and deploy your own task-oriented workflows in the Alfresco repository. However, you need to follow a particular format to define your workflow and a particular process to deploy it in Alfresco. Workflows can be deployed manually (which requires a restart of the server) and dynamically (without starting the server). For now we will deploy the workflow manually. These customizations are typically deployed via the alfresco/extension folder and require the Alfresco server to be restarted to take effect. In the later examples, we will deploy using the dynamic approach. As an example, we will configure one workflow. The use case scenario is as follows. There is a section of Blogs and News on the Cignex website, which needs to be updated monthly. The blog has to be published regularly. In order to publish, one needs to follow some process that can be defined in a workflow. The blog has to be reviewed by three different groups. Each group has different roles. Groups approve the blog one at a time and in order. When the blog is submitted, it will go to the first group. All the users belonging to that group will receive a notification via a task in the My Pooled Tasks dashlet. Any one of the users can take ownership and approve or reject the task. If rejected, it will go to the initiator. On approval it will go to next group and the process will continue for all three groups. Once the process is complete, a notification will be sent to the initiator. Also the blog would be submitted to the Staging box. For this, create Jennifer Bruce, Kristie Dawid, LeRoy Fuess, Michael Alison, and Jessica Tucker as users. Create three groups: Technical Reviewer, Editorial, and Publisher. Add Jennifer Bruce and Kristie Dawid to Technical Reviewer, add LeRoy Fuess to Editorial, and add Michael Alison and Jessica Tucker to Publisher. Invite Technical Reviewer, Editorial, and Publisher as Reviewer on the Cignex web project. The custom workflow process is shown in the following diagram: Defining the workflow process For any workflow to be deployed you should have the following files: Task Model: The Task Model provides a description for each of the tasks in the workflow. Each task description consists of Name, Title, Properties, Mandatory Aspects, and Association. Process Definition: The Process Definition describes the states (steps) and transitions (choices) of a workflow. Resource Bundle (optional): A workflow Resource Bundle provides all the human-readable messages displayed in the user interface for managing the workflow. Messages include task titles, task property names, task choices, and so on. web-client-config-custom.xml: Web Client configuration specifies the presentation of Tasks and properties to the user in the Alfresco Explorer. custom-model-context.xml: The custom model Spring Context file instructs Spring on how to bootstrap or load the Task Model definition file, Process Definition file, and Resource Bundle. web-client-config-wcm.xml: Web Client configuration specifies the availability of workflow to the web project in the Alfresco Explorer. Follow these steps to create a custom workflow. Step 1: Create a Task Model For each task in the Process Definition (as defined by <task> elements), it is possible to associate a task description. The description specifies information that may be attached to a task, that is properties (name and data type) associations (name and type of associated object), and mandatory aspects. A user may view and edit this information in the Task dialog within the Alfresco Explorer. The Task Model is expressed as a Content Model, as supported by the Data Dictionary. To create a Task Model, create a new Content Model file for Process Definition with the .xml extension. Define a Content Model name Create a Type for each task Define Properties Define and add Aspects to a Type Define a Content Model name Create a new Content Model for the Process Definition. Define the namespace of the model. XML namespaces provide a method for avoiding element name conflicts. If you want to use any other model's task, aspect, or association, then you can use it by importing their namespace. Reusability of Task Model is possible. <?xml version="1.0" encoding="UTF-8"?> <model name="bookwcmwf:workflowmodel" > <imports> <import uri="http://www.alfresco.org/model/wcmworkflow/1.0" prefix="wcmwf" /> <import uri="http://www.alfresco.org/model/bpm/1.0" prefix="bpm"> </imports> <namespaces> <namespace uri="http://book.com" prefix="bookwcmwf" /> </namespaces></model> Create a Type for each task For each task we have to define a Content Type. The Type can also be extended as follows: <types> <type name="bookwcmwf:submitReviewTask"> <parent>wcmwf:startTask</parent> </type></types> Define Properties Within each Type, describe the Properties and Associations (information) required for that task. Properties can also be inherited from other task definitions. Using the previous example all the properties of wcmwf:startTask will be added to this Type. <type name="bookwcmwf:submitReviewTask"> <parent>wcmwf:startTask</parent> <properties> <property name="wcmwf:submitReviewType"> <title>Serial or Parallel Review</title> <type>d:text</type> </property> </properties> <associations> <association name="wcmwf:webproject"> <source> <mandatory>false</mandatory> <many>false</many> </source> <target> <class>wca:webfolder</class> <mandatory>true</mandatory> <many>false</many> </target> </association> </associations></type> Define Aspect You can also introduce custom properties by defining an Aspect. An Aspect can be applied to any Content Type. Once applied, the properties are added to that Content Type. You cannot define a dependency on other Aspects. They cannot be extended. <type name="bookwcmwf:verifyBrokenLinksTask"> <parent>wcmwf:workflowTask</parent> <mandatory-aspects> <aspect>bookwcmwf:reviewInfo</aspect> <aspect>bpm:assignee</aspect> </mandatory-aspects></type> <aspects> <aspect name="bookwcmwf:reviewInfo"> <properties> <property name=" bookwcmwf:reviewerCnt"> <title>Reviewer Count</title> <type>d:int</type> <mandatory>true</mandatory> </property> </properties> </aspect></aspects> The following are the advantages of having custom Aspect over custom content: Flexibility: You will have more flexibility. Having a custom Aspect will give you the flexibility to add an additional set of properties to the documents in specific spaces. Efficiency: Since these properties are applied selectively to certain documents only in certain spaces, you will use limited storage in a relational database for these properties. The following are the disadvantages of having custom Aspect over custom content: High Maintenance: If the custom Aspect (additional properties) is added to documents based on business rules, you need to define it at every space, wherever required. Dependency: You cannot define the dependency with other Aspects. For example, if you need the effectivity aspect to always be associated with the custom aspect, you need to make sure you attach both the Aspects to the documents. Now that we are familiar with the code, let's develop a complete model file to deploy our case study in action. For any customization of files you have to develop the files in the extension folder of <install-alfresco>. Create a file book-serial-group-workflow-wcmModel.xml in the specified location <install-alfresco>/tomcat/shared/classes/alfresco/extension. Copy the downloaded content into the file. For reference, go to http://wiki.alfresco.com/wiki/Data_Dictionary_Guide#Content_Types. Step 2: Create the Process Definition A Process Definition represents a formal specification of a business process and is based on a directed graph. The graph is composed of nodes and transitions. Every node in the graph is of a specific Type. The Type of the node defines the runtime behavior. A Process Definition has exactly one Start-state and End-state. The following table describes some of the key terms used in a Process Definition: Key term Description Swimlane Swimlane is used to define a role for a user. Transition Transitions have a source node and a destination node. The source node is represented by the property from and the destination node is represented by the property to. It is used to connect nodes. A Transition can optionally have a name. The name is represented in the UI with a button. Task Tasks are associated with a Swimlane. These tasks are defined in the Workflow model files. On the basis of these tasks, the Properties are displayed. Actions Actions are pieces of Java code that are executed upon events in the process execution. These actions are performed on the basis of these tasks, as defined in the Process Definition. Events The jBPM engine will fire Events during the graph execution. Events specify moments in the execution of the process. An Event can be task-create, nodeenter, task-end, process-end, and so on. When the jBPM engine fires an event, the list of Actions is executed. Scripts Script is executed within Action. Some of the variables that can be available in Script are node, task, execution context, and so on. Nodes Each Node has a specific type. The Node Type determines what will happen when an execution arrives in the Node at runtime. The following table summarizes the Node Types available in jBPM out of the box. Node types Description Task Node A Task Node represents one or more tasks that have to be performed by users. Start-state There can be only one Start-state in the Process Definition, which logs the start of the workflow. decision The distinction between multiple paths. When the decision between multiples path has to be taken, a decision node is used. fork A fork splits one path of execution into multiple concurrent paths of execution. join Joins multiple paths into single path. A join will end every token that enters the join. node The node serves the situation where you want to write your own code in a node. End-state There can be only one End-state in the Process Definition, which logs the end of the workflow. There are two ways of building the Process Definition. One is by hand, that is create a jPDL XML document. The second option is by designer, that is use a tool to generate the jPDL XML document. To create a Process Definition, create a new Process Definition file with the extension .xml. Define a Process Definition name The Process Definition name is important. <?xml version="1.0" encoding="UTF-8"?> <process-definition name="bookwcmwf:bookworkflow"> In the previous code we have used bookwcmwf:bookworkflow where bookwcmwf is the namespace of the workflow model file defined earlier, which we are going to use in this Process Definition, and bookworkflow can be any name. Define a Swimlane Swimlanes are used to declare workflow "roles". Tasks are associated with a Swimlane. Here initiator is the user who is starting the workflow. Likewise, we have some other roles also defined. For example, bpm_assignee (one user to whom the workflow is assigned), bpm_assignees (one or more user), bpm_groupAssignee (single group), and bpm_groupAssignees (one or more groups). <swimlane name="initiator"/><swimlane name="approver"> <assignment class="org.alfresco.repo.workflow.jbpm.AlfrescoAssignment"> <pooledactors>#{bpm_groupAssignee}</pooledactors> </assignment></swimlane><swimlane name="assignee"> <assignment class="org.alfresco.repo.workflow.jbpm.AlfrescoAssignment"> <actor>#{bpm_assignee}</actor> </assignment></swimlane> Associate a task We have already defined task in the Content Model files. On the basis of these tasks the properties are displayed. Next step is to add these tasks to the workflow process. To start with, add a task to the start node. The Start Task is assigned to the initiator of the workflow. It's used to collect the information (that is the workflow parameters) required for the workflow to proceed. <start-state name="start"> <task name="bookwcmwf:submitReviewTask" swimlane="initiator"/> <transition name="" to="initialise"/></start-state><swimlane name="assignee"> <assignment class="org.alfresco.repo.workflow.jbpm.AlfrescoAssignment"> <actor>#{bpm_assignee}</actor> </assignment></swimlane> <task-node name="initialise "> <task name="bookwcmwf:verifyBrokenLinksTask" swimlane="assignee" /> <transition name="abort" to="end"> <action class="org.alfresco.repo.workflow.jbpm.AlfrescoJavaScript"> <script> var mail = actions.create("mail"); mail.parameters.to = initiator.properties["cm:email"]; mail.parameters.subject = "Adhoc Task " + bpm_workflowDescription; mail.parameters.from = bpm_assignee.properties["cm:email"]; mail.parameters.text = "It's done"; mail.execute(bpm_package); </script> </action> </task-node> <end-state name="end"/> During runtime, all the properties of the task bookwcmwf:submitReviewTask are visible to the user who is initiating a workflow. Once the properties are filled, the initiator assigns a task to another user or group. In this case, it is assigned to user. Now the task appears in dashlets of assigned user. The Assignee fills the properties of the task bookwcmwf:verifyBrokenLinksTask and clicks on the abort button. The abort transition would call Alfresco JavaScript that sends an e-mail. And an end-state event will log the end of the workflow. We are now ready to create a Process Definition file and use the workflow model we developed earlier for our case study. Create a file book-serial-group-processdefinition.xml in the specified location <install-alfresco>/tomcat/shared/classes/alfresco/extension. Copy the downloaded content into the file. For reference go to http://wiki.alfresco.com/wiki/WorkflowAdministration. Step 3: Create the workflow Resource Bundles For localized workflow interaction it is necessary to provide Resource Bundles containing UI labels for each piece of text that is exposed to the user. With the appropriate Resource Bundles, a single workflow instance may spawn tasks where the user interface for each task is rendered in a different language, based on the locale of the user. Specific structure has to be followed in order to define labels for UI in Resource Bundle. <model_prefix>_<model_name>.[title|description]<model_prefix>_<model_name>.<model_element>.<element_prefix>_ <element_name>.[title|description] Add all the properties that relate to this Process Definition and model. bookwcmwf_bookworkflow.workflow.title=Book Workflow bookwcmwf_bookworkflow.node.verifybrokenlinks.transition.abort.title=Abort Submission bookwcmwf_workflowmodel.type.bookwcmwf_reviewTask.description=Review Documents to approve or reject them Create a file book-serial-group-messages.properties in the specified location, <install-alfresco>/tomcat/shared/classes/alfresco/extension. Copy the downloaded content into the file.
Read more
  • 0
  • 0
  • 2784
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-understanding-jquery-and-wordpress-together
Packt
27 Sep 2010
11 min read
Save for later

Understanding jQuery and WordPress Together

Packt
27 Sep 2010
11 min read
  WordPress 3.0 jQuery Enhance your WordPress website with the captivating effects of jQuery. Enhance the usability and increase visual interest in your WordPress 3.0 site with easy-to-implement jQuery techniques Create advanced animations, use the UI plugin to your advantage within WordPress, and create custom jQuery plugins for your site Turn your jQuery plugins into WordPress plugins and share with the world Implement all of the above jQuery enhancements without ever having to make a WordPress content editor switch over into HTML view   Read more about this book (For more resources on WordPress and jQuery, see here.) Two ways to "plugin" jQuery into a WordPress site You're aware that WordPress is an impressive publishing platform. Its core strength lies in its near perfect separation of content, display, and functionality. Likewise, jQuery is an impressive JavaScript library with a lot of effort spent on making it work across platforms, be very flexible and extensible, and yet, elegantly degradable (if a user doesn't have JavaScript enabled for some reason). You're aware that WordPress themes control the look and feel of your site and that WordPress plugins can help your site do more, but we're going to take a look at exactly how those two components work within the WordPress system and how to use jQuery from either a theme or a WordPress plugin. In doing so, you'll be better able to take advantage of them when developing your jQuery enhancements. Speaking of jQuery enhancements, jQuery scripts can be turned into their own type of plugins, not to be confused with WordPress plugins. This makes the work you do in jQuery easily portable to different projects and uses. Between these three components, themes, WordPress plugins, and jQuery plugins, you'll find that just about anything you can dream of creating is at your fingertips. Even better, you'll realize that most of the work is already done. All three of these component types have extensive libraries of already developed third-party creations. Most are free! If they aren't free, you'll be prepared to determine if they're worth their price. By understanding the basics of editing themes and creating your own WordPress and jQuery plugins, you'll be ready to traverse the world of third-party creations and find the best solutions for your projects. You'll also be able to determine if it's better or faster to work with another developer's themes, plugins, or jQuery plugins, versus creating your own from scratch. WordPress themes overview A WordPress theme is, according to the WordPress codex, a collection of files that work together to produce a graphical interface with an underlying unifying design for a weblog. Themes comprise a collection of template files and web collateral such as images, CSS stylesheets, and JavaScript. Themes are what allow you to modify the way your WordPress site looks, without having to know much about how WordPress works, much less change how it works. There are plenty of sites that host free themes and or sell premium WordPress themes. A quick Google search for "wordpress themes" will give you an idea of the enormity of options available. However, when first looking for or researching themes, a good place to start is always WordPress' free theme gallery where you can easily review and demo different themes and styles: http://wordpress.org/extend/themes/. The next screenshot shows the main page of the WordPress theme's directory: (Move the mouse over the image to enlarge.) Once you've selected a theme to use or work with, you'll activate the theme by navigating to Administration | Appearance | Themes in the left-hand side panel of your WordPress installation's administration panel. The next screenshot displays the Manage Themes panel: That's the minimum you need to know about themes as a WordPress user. The basics of a WordPress theme The WordPress theme essentially contains the HTML and CSS that wrap and style your WordPress content. Thus, it's usually the first place you'll start when incorporating jQuery into a site. Most of the time, this is a good approach. Understanding a bit more about how themes work can only make your jQuery development go a little smoother. Let's take a look at how themes are structured and best practices for editing them. Want to know more about WordPress theme design? This title focuses on what you most need to know to work with jQuery in WordPress. If you're interested in WordPress theme development I highly recommend April Hodge Silver and Hasin Hayer's WordPress 2.7 Complete. Along with covering the complete core competencies for managing a WordPress site, it has an overview on editing and creating standard themes for WordPress. If you want to really dig deep into theme design, my title WordPress 2.8 Theme Design will walk you through creating a working HTML and CSS design mockup and coding it up from scratch. Understanding the template's hierarchy We've discussed that a WordPress theme comprises many file types including template pages. Template pages have a structure or hierarchy to them. That means, if one template type is not present, then the WordPress system will call up the next level template type. This allows developers to create themes that are fantastically detailed, which take full advantage of all of the hierarchy's available template page types, to make the setup unbelievably simple. It's possible to have a fully functioning WordPress theme that consists of no more than an index.php file! To really leverage a theme for jQuery enhancement (not to mention help you with general WordPress troubleshooting), it's good to start with an understanding of the theme's hierarchy. In addition to these template files, themes of course also include image files, stylesheets, and even custom template pages, and PHP code files. Essentially, you can have 14 different default page templates in your WordPress theme, not including your style.css sheet or includes such as header.php, sidebar.php, and searchform.php. You can have more template pages than that if you take advantage of WordPress' capability for individual custom page, category, and tag templates. If you open up the default theme's directory that we've been working with, you'll see most of these template files as well as an image directory, style.css and the js directory with the custom-jquery.js file. The following screenshot shows you the main files in WordPress 3.0's new default theme, Twenty Ten: The next list contains the general template hierarchy rules. The absolute simplest theme you can have must contain an index.php page. If no other specific template pages exist, then index.php is the default. You can then begin expanding your theme by adding the following pages: archive.php trumps index.php when a category, tag, date, or author page is viewed. home.php trumps index.php when the home page is viewed. single.php trumps index.php when an individual post is viewed. search.php trumps index.php when the results from a search are viewed. 404.php trumps index.php when the URI address finds no existing content. page.php trumps index.php when looking at a static page. A custom template page, such as: page_about.php, when selected through the page's Administration panel, trumps page.php, which trumps index.php when that particular page is viewed. category.php trumps archive.php, which then trumps index.php when a category is viewed. A custom category-ID page, such as: category-12.php trumps category.php. This then trumps archive.php, which trumps index.php. tag.php trumps archive.php. This in turn trumps index.php when a tag page is viewed. A custom tag-tagname page, such as: tag-reviews.php trumps tag.php. This trumps archive.php, which trumps index.php. author.php trumps archive.php. This in turn trumps index.php, when an author page is viewed. date.php trumps archive.php. This trumps index.php when a date page is viewed. You can learn more about the WordPress theme template hierarchy here:http://codex.wordpress.org/Template_Hierarchy. A whole new theme If you wanted to create a new theme or if you'll be modifying a theme considerably, you'll want to create a directory with a file structure similar to the hierarchy explained previously. Again, because it's hierarchal, you don't have to create every single page suggested, higher up pages will assume the role unless you decide otherwise. As I've mentioned, it is possible to have a working theme with nothing but an index.php file. I'll be modifying the default theme, yet would like the original default theme available for reference. I'll make a copy of the default theme's directory and rename it to: twentyten-wp-jq. WordPress depends on the theme directories namespace. Meaning, each theme requires a uniquely named folder! Otherwise, you'll copy over another theme. The next screenshot shows this directory's creation: I'll then open up the style.css file and modify the information at the beginning of the CSS file: /* Theme Name: Twenty Ten - <b>edited for Chapter 3 of WordPress & jQuery</b> Theme URI: http://wordpress.org/ Description: The 2010 default theme for WordPress. Author: the WordPress team <b>& Tessa Silver</b> Version: 1.0 Tags: black, blue, white, two-columns, fixed-width, custom-header, custom-background, threaded-comments, sticky-post, translation-ready, microformats, rtl-language-support, editor-style */ ... My "new" theme will then show up in the administration panel's Manage Themes page. You can take a new screenshot to update your new or modified theme. If there is no screenshot, the frame will display a grey box. As the look of the theme is going to change a little, I've removed the screenshot.png file from the directory for now, as you can see in the next screenshot: The Loop We know how useful it is when jQuery "loops" through selected elements in a wrapper for you. WordPress does a little looping of its own; in fact, it's important enough to be named "The Loop". The Loop is an essential part of your WordPress theme. It displays your posts in chronological order and lets you define custom display properties with various WordPress template tags wrapped in HTML markup. The Loop in WordPress is a while loop and therefore starts with the PHP code: while (have_posts()): followed by the template tag the_post(). All the markup and additional template tags are then applied to each post that gets looped through for display. The Loop is then ended with the PHP endwhile statement. Every template page view can have its own loop so that you can modify and change the look and layout of each type of post sort. Every template page is essentially, just sorting your posts in different ways. For example, different category or tag template pages sort and refine your posts down to meet specific criteria. Those sorted posts can appear different from posts on your main page, or in your archive lists, and so on. The next example is a very simple loop taken from WordPress 2.9.2's default Kubrick theme: ... <?php while (have_posts()) : the_post(); ?> <div <?php post_class() ?> id="post-<?php the_ID(); ?>"> <h2> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"> <?php the_title(); ?> </a> </h2> <small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --> </small> <div class="entry"> <?php the_content('Read the rest of this entry &raquo;'); ?> </div> <p class="postmetadata"> <?php the_tags('Tags: ', ', ', '<br />'); ?> Posted in <?php the_category(', ') ?> | <?php edit_post_link('Edit', '', ' | '); ?> <?php comments_popup_link('No Comments &#187;', '1 Comment &#187;', '% Comments &#187;'); ?> </p> </div> <?php endwhile; ?> ... The loop is tucked into a large if/else statement that most importantly checks if there are posts to sort. If there are no matching posts to display, a "Sorry" message is displayed, and the searchform.php file is included with the get_search_form() include tag. The new WordPress 3.0 Twenty Ten theme has its loop separated out into its own template page called loop.php, and it has quite a few more if/else statements within it so that the same loop code can handle many different situations, instead of writing individual loops for different template pages. On the whole, the same basic template tags as well as conditional and include tags are used in the new theme as they were before in the previous default theme. There are now just a few new template and include tags that help you streamline your theme. Let's take a closer look at some of these template tags, include and conditional tags, and the API hooks available to us in a WordPress theme.
Read more
  • 0
  • 0
  • 2352

article-image-basics-wordpress-and-jquery-plugin
Packt
27 Sep 2010
10 min read
Save for later

The Basics of WordPress and jQuery Plugin

Packt
27 Sep 2010
10 min read
  WordPress 3.0 jQuery Enhance your WordPress website with the captivating effects of jQuery. Enhance the usability and increase visual interest in your WordPress 3.0 site with easy-to-implement jQuery techniques Create advanced animations, use the UI plugin to your advantage within WordPress, and create custom jQuery plugins for your site Turn your jQuery plugins into WordPress plugins and share with the world Implement all of the above jQuery enhancements without ever having to make a WordPress content editor switch over into HTML view   Read more about this book (For more resources on WordPress and jQuery, see here.) WordPress plugins overview So themes change the look of WordPress without affecting its functionality. But what if you want to change or add functionality? WordPress plugins allow easy modification, customization, and enhancement to a WordPress site. Instead of having to dig in to the main files and change the core programming of WordPress, you can add functionality by installing and activating WordPress plugins. The WordPress development team took great care to make it easy to create plugins using access points and methods provided by the WordPress' Plugin API (Application Program Interface). The best place to search for plugins is: http://wordpress.org/extend/plugins/. The following is a screenshot of the WordPress plugin directory's main page: (Move the mouse over the image to enlarge.) Once you have a plugin, it's a simple matter of decompressing the file (usually just unzipping it) and reading the included readme.txt file for installation and activation instructions. For most WordPress plugins, this is simply a matter of uploading the file or directory to your WordPress installation's wp-content/plugins directory and then navigating to the Administration | Plugins | Installed panel to activate it. The next screenshot shows the Plugins admin panel with the activation screen for the default Askimet, Hello Dolly, and new WordPress Importer plugins: So how does a WordPress plugin differ from a jQuery plugin? In theory and intent, not that much, but in practice, there are quite a few differences. Let's take a look at jQuery plugins. jQuery plugins overview jQuery has the ability to allow you to take the scripts that you've created and encapsulate them into the jQuery function object. This allows your jQuery code to do a couple of key things. First, it becomes more easily ported over to different situations and uses. Second, your plugin works as a function that can be integrated into larger scripts as part of the jQuery statement chain. The best place to browse for jQuery plugins is the jQuery plugins page (http://plugins.jquery.com/), as seen in the next screenshot: In addition to having jQuery already bundled, WordPress has quite a few jQuery plugins already bundled with it as well. WordPress comes bundled with Color, Thickbox as well as Form and most of the jQuery UI plugins. Each of these plugins can be enabled with the wp_enqueue_script either in the theme's header.php file or function.php file, in WordPress. In this article, we'll shortly learn how to enable a jQuery plugin directly in a WordPress plugin. Of course, you can also download jQuery plugins and include them manually into your WordPress theme or plugins. You'd do this for plugins that aren't bundled with WordPress, or if you need to amend the plugins in anyway. Yes, you've noticed there's no easy jQuery plugin activation panel in WordPress. This is where understanding your chosen theme and WordPress plugins will come in handy! You'll soon find you have quite a few options to choose from when leveraging jQuery. Now that we have an overview of what WordPress themes, plugins, and jQuery plugins are, let's learn how to take better advantage of them. The basics of a WordPress plugin The goal here is to show you the structure of a simple WordPress plugin and the basics of how to construct one. Understanding this, you can begin to write your own basic plugins and feel more confident looking through other people's plugins when assessing what kind of features they provide to your WordPress site and if you need to tweak anything for your jQuery enhancements. Even as simply and basically as we're going to work, you'll see how truly powerful WordPress plugins can be. Want to become a WordPress plugin rockstar? You can start off with, yet again, WordPress 2.7 Complete by April Hodge Silver and Hasin Hayder. There's a chapter on plugins that walks you through creating very useful simple plugins, as well as a more complex plugin that writes to the WordPress database. Beyond that, you'll want to check out WordPress Plugin Development: Beginner's Guide by Vladimir Prelovac. Don't let the title fool you, Vladimir will have you generating feature rich and dynamic WordPress plugins using WordPress' coding standards all explained with clear, step-by-step code. Working with plugins does require some experience with PHP. I'll keep this explanation fairly straightforward for non-PHP developers, and those of you with PHP experience should be able to see how to expand on this example to your advantage in WordPress. Just as with themes, WordPress plugins require a little structure to get started with them. There's no defined hierarchy for plugin files, but you do need, at the very least, a PHP file with a special comment up top so that WordPress can display it within the Plugin Management page. While there are some single-file plugins out there, such as the Hello Dolly plugin, which comes with your WordPress installation, you never know when you first start developing, the ways in which a plugin may grow. To be safe, I like to organize my plugins into a uniquely named folder. Again, like with themes, WordPress relies on the plugin directory's namespace, so uniqueness is of key importance! In the wp-content/plugins directory you can place a unique folder and inside that, create a .php file, and at the beginning of the file, inside the <?php ?> tags, include the following header information. Only the bold information is absolutely required. The rest of the information is optional and populates the Manage Plugins page in the Administration panel. <?php /* Plugin Name: your WordPress Plugin Name goes here Plugin URI: http://yoururl.com/plugin-info Description: Explanation of what it does Author: Your Name Version: 1.0 Author URI: http://yoururl.com */ //plugin code will go here ?> Make sure that you don't have any spaces before your <?php tag or after your ?> tag. If you do, WordPress will display some errors because the system will get some errors about page headers already being sent. Once you have your .php file set up in its own directory, inside your plugin directory, you can add a basic PHP function. You can then decide how you want to evoke that function, using an action hook or a filter hook. For example: <?php /* Plugin Name: your WordPress Plugin Name goes here Plugin URI: http://yoururl.com/plugin-info Description: Explanation of what it does Author: Your Name Version: 1.0 Author URI: http://yoururl.com */ function myPluginFunction(){ //function code will go here } add_filter('the_title', 'myPluginFunction'); //or you could: /*add_action('wp_head', 'myPluginFunction');*/ ?> If you didn't have wp_head or wp_footer in your theme, many plugins can't function, and you limit yourself to the plugins you can write. In my plugins, I mostly use wp_header and the init action hooks. Luckily, most filter hooks will work in your plugins as WordPress will run through them in The Loop. For the most part, you'll get the most work done in your plugin using the_title and the_content filter hooks. Each of these filter's hooks will execute your function when WordPress loops through those template tags in the loop. Want to know what filter and action hooks are available? The list is exhaustive. In fact, it's so immense that the WordPress codex doesn't seem to have them all documented! For the most complete listing available of all action and filter hooks, including newer hooks available in version 2.9.x, you'll want to check out Adam Brown's WordPress Hooks Database: http://adambrown.info/p/wp_hooks. Overwhelmed by the database? Of course, checking out Vladimir's WordPress Plugin Development: Beginner's Guide will get you started with an arsenal of action and filter hooks as well. You now understand the basics of a WordPress plugin! Let's do something with it. Project: Writing a WordPress plugin to display author bios As we've discussed, plugins can help expand WordPress and give it new functionality. However, we've seen that adding jQuery scripts directly to the theme and editing its template pages here and there will do the trick in most cases. But let's imagine a more complicated scenario using our modified default theme and the hypothetical client. While we tweaked the default theme, I figured that this client might want to have her site's focus be more journalism oriented, and thus, she'd want some attention drawn to the author of each post upfront. I was right, she does. However, there's a catch. She doesn't just want their WordPress nickname displayed; she'd prefer their full first and last name be displayed as well, as it's more professional. She'd also like their quick biography displayed with a link to their own URL and yet, not have that information "get in the way" of the article itself, or lost down at the bottom of the post. And here's the really fun part; she wants this change affected not just on this site, but across her network of genre-specific news sites, over 20 of them at last count (dang, I forgot she had so many sites! Good thing she's hypothetical). For this specific WordPress site, it's easy enough to go in and comment out the custom function we dealt with earlier: add in the_author tag and display it twice, passing each tag some parameters to display the first and last name. I can also add a tag to display the author's biography snippet from the user panel and URL (if they've filled out that information). Also, it's certainly easy enough to add a little jQuery script to make that bio div show up on a rollover of the author's name. However, having to take all that work and then re-copy it into 20 different sites, many of which are not using the default theme, and most of which have not had jQuery included into their theme, does sound like an unnecessary amount of work (to boot, the client has mentioned that she's deciding on some new themes for some of the sites, but she doesn't know which sites will get what new themes yet). It is an unnecessary amount of work. Instead of amending this theme and then poking through, pasting, testing, and tweaking in 20 other themes, we'll spend that time creating a WordPress plugin. It will then be easy to deploy it across all the client's sites, and it shouldn't matter what theme each site is using. Let's get started!
Read more
  • 0
  • 0
  • 4295

article-image-disaster-recovery-mysql-python
Packt
25 Sep 2010
10 min read
Save for later

Disaster Recovery in MySQL for Python

Packt
25 Sep 2010
10 min read
  MySQL for Python Integrate the flexibility of Python and the power of MySQL to boost the productivity of your Python applications Implement the outstanding features of Python's MySQL library to their full potential See how to make MySQL take the processing burden from your programs Learn how to employ Python with MySQL to power your websites and desktop applications Apply your knowledge of MySQL and Python to real-world problems instead of hypothetical scenarios A manual packed with step-by-step exercises to integrate your Python applications with the MySQL database server Read more about this book (For more resources on Phython, see here.) The purpose of the archiving methods covered in this article is to allow you, as the developer, to back up databases that you use for your work without having to rely on the database administrator. As noted later in the article, there are more sophisticated methods for backups than we cover here, but they involve system-administrative tasks that are beyond the remit of any development post and are thus beyond the scope of this article. Every database needs a backup plan When archiving a database, one of the critical questions that must be answered is how to take a snapshot backup of the database without having users change the data in the process. If data changes in the midst of the backup, it results in an inconsistent backup and compromises the integrity of the archive. There are two strategic determinants for backing up a database system: Offline backups Live backups Which you use depends on the dynamics of the system in question and the import of the data being stored. In this article, we will look at each in turn and the way to implement them. Offline backups Offline backups are done by shutting down the server so the records can be archived without the fear of them being changed by the user. It also helps to ensure the server shut down gracefully and that errors were avoided. The problem with using this method on most production systems is that it necessitates a temporary loss of access to the service. For most service providers, such a consequence is anathema to the business model. The value of this method is that one can be certain that the database has not changed at all while the backup is run. Further, in many cases, the backup is performed faster because the processor is not simultaneously serving data. For this reason, offline backups are usually performed in controlled environments or in situations where disruption is not critical to the user. These include internal databases, where administrators can inform all users about the disruption ahead of time, and small business websites that do not receive a lot of traffic. Offline backups also have the benefit that the backup is usually held in a single file. This can then be used to copy a database across hosts with relative ease. Shutting down a server obviously requires system administrator-like authority. So creating an offline backup relies on the system administrator shutting down the server. If your responsibilities include database administration, you will also have sufficient permission to shut down the server. Live backups Live backups occur while the server continues to accept queries from users, while it's still online. It functions by locking down the tables so no new data may be written to them. Users usually do not lose access to the data and the integrity of the archive, for a particular point in time is assured. Live backups are used by large, data-intensive sites such as Nokia's Ovi services and Google's web services. However, because they do not always require administrator access of the server itself, these tend to suit the backup needs of a development project. Choosing a backup method After having determined whether a database can be stopped for the backup, a developer can choose from three methods of archiving: Copying the data files (including administrative files such as logs and tablespaces) Exporting delimited text files Backing up with command-line programs Which you choose depends on what permissions you have on the server and how you are accessing the data. MySQL also allows for two other forms of backup: using the binary log and by setting up replication (using the master and slave servers). To be sure, these are the best ways to back up a MySQL database. But, both of these are administrative tasks and require system-administrator authority; they are not typically available to a developer. However, you can read more about them in the MySQL documentation. Use of the binary log for incremental backups is documented at: http://dev.mysql.com/doc/refman/5.5/en/point-in-time-recovery.html Setting up replication is further dealt with at: http://dev.mysql.com/doc/refman/5.5/en/replication-solutions-backups.html Copying the table files The most direct way to back up database files is to copy from where MySQL stores the database itself. This will naturally vary based on platform. If you are unsure about which directory holds the MySQL database files, you can query MySQL itself to check: mysql> SHOW VARIABLES LIKE 'datadir'; Alternatively, the following shell command sequence will give you the same information: $ mysqladmin variables | grep datadir| datadir | /var/lib/mysql/ | Note that the location of administrative files, such as binary logs and InnoDB tablespaces are customizable and may not be in the data directory. If you do not have direct access to the MySQL server, you can also write a simple Python program to get the information: #!/usr/bin/env pythonimport MySQLdbmydb = MySQLdb.connect('<hostname>', '<user>', '<password>')cursor = mydb.cursor()runit = cursor.execute("SHOW VARIABLES LIKE 'datadir'")results = cursor.fetchall()print "%s: %s" %(cursor.fetchone()) Slight alteration of this program will also allow you to query several servers automatically. Simply change the login details and adapt the output to clarify which data is associated with which results. Locking and flushing If you are backing up an offline MyISAM system, you can copy any of the files once the server has been stopped. Before backing up a live system, however, you must lock the tables and flush the log files in order to get a consistent backup at a specific point. These tasks are handled by the LOCK TABLES and FLUSH commands respectively. When you use MySQL and its ancillary programs (such as mysqldump) to perform a backup, these tasks are performed automatically. When copying files directly, you must ensure both are done. How you apply them depends on whether you are backing up an entire database or a single table. LOCK TABLES The LOCK TABLES command secures a specified table in a designated way. Tables can be referenced with aliases using AS and can be locked for reading or writing. For our purposes, we need only a read lock to create a backup. The syntax looks like this: LOCK TABLES <tablename> READ; This command requires two privileges: LOCK TABLES and SELECT. It must be noted that LOCK TABLES does not lock all tables in a database but only one. This is useful for performing smaller backups that will not interrupt services or put too severe a strain on the server. However, unless you automate the process, manually locking and unlocking tables as you back up data can be ridiculously inefficient. FLUSH The FLUSH command is used to reset MySQL's caches. By re-initiating the cache at the point of backup, we get a clear point of demarcation for the database backup both in the database itself and in the logs. The basic syntax is straightforward, as follows: FLUSH <the object to be reset>; Use of FLUSH presupposes the RELOAD privilege for all relevant databases. What we reload depends on the process we are performing. For the purpose of backing up, we will always be flushing tables: FLUSH TABLES; How we "flush" the tables will depend on whether we have already used the LOCK TABLES command to lock the table. If we have already locked a given table, we can call FLUSH for that specific table: FLUSH TABLES <tablename>; However, if we want to copy an entire database, we can bypass the LOCK TABLES command by incorporating the same call into FLUSH: FLUSH TABLES WITH READ LOCK; This use of FLUSH applies across the database, and all tables will be subject to the read lock. If the account accessing the database does not have sufficient privileges for all databases, an error will be thrown. Unlocking the tables Once you have copied the files for a backup, you need to remove the read lock you imposed earlier. This is done by releasing all locks for the current session: UNLOCK TABLES; Restoring the data Restoring copies of the actual storage files is as simple as copying them back into place. This is best done when MySQL has stopped, lest you risk corruption. Similarly, if you have a separate MySQL server and want to transfer a database, you simply need to copy the directory structure from the one server to another. On restarting, MySQL will see the new database and treat it as if it had been created natively. When restoring the original data files, it is critical to ensure the permissions on the files and directories are appropriate and match those of the other MySQL databases. Delimited backups within MySQL MySQL allows for exporting of data from the MySQL command line. To do so, we simply direct the output from a SELECT statement to an output file. Using SELECT INTO OUTFILE to export data Using sakila, we can save the data from film to a file called film.data as follows: SELECT * INTO OUTFILE 'film.data' FROM film; This results in the data being written in a tab-delimited format. The file will be written to the directory in which MySQL stores the sakila data. Therefore, the account under which the SELECT statement is executed must have the FILE privilege for writing the file as well as login access on the server to view it or retrieve it. The OUTFILE option on SELECT can be used to write to any place on the server that MySQL has write permission to use. One simply needs to prepend that directory location to the file name. For example, to write the same file to the /tmp directory on a Unix system, use: SELECT * INTO OUTFILE '/tmp/film.data' FROM film; Windows simply requires adjustment of the directory structure accordingly. Using LOAD DATA INFILE to import data If you have an output file or similar tab-delimited file and want to load it into MySQL, use the LOAD DATA INFILE command. The basic syntax is: LOAD DATA INFILE '<filename>' INTO TABLE <tablename>; For example, to import the film.data file from the /tmp directory into another table called film2, we would issue this command: LOAD DATA INFILE '/tmp/film.data' INTO TABLE film2; Note that LOAD DATA INFILE presupposes the creation of the table into which the data is being loaded. In the preceding example, if film2 had not been created, we would receive an error. If you are trying to mirror a table, remember to use the SHOW CREATE TABLE query to save yourself time in formulating the CREATE statement. This discussion only touches on how to use LOAD DATA INFILE for inputting data created with the OUTFILE option of SELECT. But, the command handles text files with just about any set of delimiters. To read more on how to use it for other file formats, see the MySQL documentation at: http://dev.mysql.com/doc/refman/5.5/en/load-data.html
Read more
  • 0
  • 0
  • 6243

article-image-oracle-bpm-suite-11gr1-creating-bpm-application
Packt
25 Sep 2010
7 min read
Save for later

Oracle BPM Suite 11gR1: Creating a BPM Application

Packt
25 Sep 2010
7 min read
Getting Started with Oracle BPM Suite 11gR1 – A Hands-On Tutorial Learn from the experts – teach yourself Oracle BPM Suite 11g with an accelerated and hands-on learning path brought to you by Oracle BPM Suite Product Management team members Offers an accelerated learning path for the much-anticipated Oracle BPM Suite 11g release Set the stage for your BPM learning experience with a discussion into the evolution of BPM, and a comprehensive overview of the Oracle BPM Suite 11g Product Architecture Discover BPMN 2.0 modeling, simulation, and implementation Understand how Oracle uses standards like Services Component Architecture (SCA) to simplify the process of application development Describes how Oracle has unified services and events into one platform Built around an iterative tutorial, using a real-life scenario to illustrate all the key features Full of illustrations, diagrams, and tips for developing SOA applications faster, with clear step-by-step instructions and practical examples Written by Oracle BPM Suite Product Management team members   Read more about this book (For more resources on Oracle, see here.) The BPM Application consists of a set of related business processes and associated shared artifacts such as Process Participants and Organization models, User Interfaces, Services, and Data. The process-related artifacts such as Services and Data are stored in the Business Catalog. The Business Catalog facilitates collaboration between the various stakeholders involved in the development of the business process. It provides a mechanism for Process Developer (IT) to provide building blocks that can in turn be used by the process analyst in implementing the business process. Start BPM Studio using Start | Programs | Oracle Fusion Middleware 11.1.1.3 | Oracle JDeveloper 11.1.1.3. BPM Studio supports two roles or modes of process development. The BPM Role is recommended for Process Analysts and provides a business perspective with focus on business process modeling. The Default Role is recommended for Process Developers for refinement of business process models and generation of implementation artifacts to complete the BPM Application for deployment and execution. Tutorial: Creating SalesQuote project and modeling RequestQuote process This is the beginning of the BPM 11gR1 hands-on tutorial. Start by creating the BPM Application and then design the Sales Quote business process. Open BPM Studio by selecting the BPM Process Analyst role when you start JDeveloper or if JDeveloper is already open, select Preferences from the Tools menu and in the Roles section, select BPM Process Analyst. Go to File | New to launch the Application wizard. In the New Gallery window, select Applications in the Categories panel. Select BPM Application in the Items panel. Specify the Application Name —SalesQuoteLab; the folder name should also be set to SalesQuoteLab. Click on the Next button. Enter QuoteProcessLab for the Project Name. Click on the Finish button. Go to the View | BPM Project Navigator. The BPM Project Navigator opens up the QuoteProcessLab – BPM Project that you just created. A single BPM Project can contain multiple related business processes. Notice that the BPM Project contains several folders. Each folder is used to store a specific type of BPM artifact. The Processes folder stores BPMN business process models; the Activity Guide folder is used to store the process milestones; the Organization folder stores Organization model artifacts such as Roles and Organization Units; the Business Catalog folder stores Services and Data; the Simulation folder stores simulation models to capture what-if scenarios for the business process and the Resources folder holds XSLT data transformation artifacts. To create a new business process model, you need to right-click on Processes and select New | Process. This launches the Create BPMN Process wizard. Select From Pattern option and select the Manual Process pattern. Recall that the Sales Quote Process is instantiated when Enter Quote task gets assigned to the Sales Representative role. The Asynchronous Service and the Synchronous Service patterns are used to expose the BPMN process as a Service Provider. Click on the Next button. Specify the name for the Process—RequestQuoteLab. Click on the Finish button. This creates a RequestQuoteLab process with a Start Event (thin circle) and End Event (thicker circle) of type None with a User Task in between. The User Task represents a human step that is managed by the BPM run-time engine—workflow component. The Start Event of type None signifies that there is no external event triggering the process. The first activity after the Start Event creates the process instance. In addition, a default swim lane—Role, gets created. In BPM Studio, the swim lanes in the BPMN process point to logical roles. A logical role represents a process participant (user or group) and needs to be mapped to physical roles (LDAP users/groups) before the process is deployed. Right-click on the User Task step, select Properties, and specify the name Enter Quote Details for the step. Click on the OK button. The next step is to rename the default created role to SalesRep. Navigate to QuoteProcessLab—BPM Project node and select the Organization node underneath it. Right-click on the Organization node and select Open. This opens up the Organization pane. Highlight the default role named Role and use the pencil icon to edit it to be SalesRep. Click on the + sign to add the following roles—Approvers, BusinessPractices, and Contracts. The following screenshot shows the list of roles that you just created: Close the Organization window. Go back to the RequestQuoteLab—process model. The participant for the Enter Quote Details—User Task is now set to the SalesRep role. Ignore the yellow triangular symbol with the exclamation for now. It indicates that certain configuration information is missing for the activity. Right-click on the process diagram just below the SalesRep-Lane. Choose the Add Role option. Choose Business Practices from the list of options available. Click on the OK button. Open the View | Component Palette. Drag and drop a User Task from the Interactive Tasks section of the BPMN Component Palette. Note: The Interactive Tasks refers to a step that is managed by the workflow engine. The Assignees (Participants) represent the business users who need to carry out the Interactive Task. The associated Task (work to be performed) is shown in the inbox of the assignees (similar to Email Inbox) when the Interactive Task is triggered. The User Task is the simplest type of Interactive Task where the assignee of the task is set to a single role. The actual work is performed only when the Assignee executes on his Task. The Task is presented to the Assignee through a browser based worklist application. In BPM Studio, the Assignee is automatically set to the role associated with the swim lane into which the Interactive Task is dropped. Place this new User Task after the existing Enter Quote Details—User Task by hovering on the center of the connector until it turns blue and name it Business Practices Review. The connection lines are automatically created. Drag the new Business Practices Review—User Task to the Business Practices lane. The performer or assignee for the Business Practices Review—User Task is automatically set to Business Practices—role. Create two more lanes for Approvers and Contracts. Drag and drop three User Tasks on to the process diagram, one following the other, and name them Approve Deal, Approve Terms, and Finalize Contracts respectively. Pin the Approve Deal step to the Approvers Lane. Pin the other two User Tasks—Approve Terms and Finalize Contracts steps to the Contracts Lane. Finally add a Service Task right after the Finalize Contracts step from the BPM Component Palette and name it Save Quote. The modified diagram should look like the following:
Read more
  • 0
  • 0
  • 8746
article-image-building-complete-board-based-puzzle-game-microsoft-xna-40
Packt
25 Sep 2010
14 min read
Save for later

Building a Complete Board-based Puzzle Game with Microsoft XNA 4.0

Packt
25 Sep 2010
14 min read
  XNA 4.0 Game Development by Example: Beginner's Guide Create your own exciting games with Microsoft XNA 4.0 Dive headfirst into game creation with XNA Four different styles of games comprising a puzzler, a space shooter, a multi-axis shoot 'em up, and a jump-and-run platformer Games that gradually increase in complexity to cover a wide variety of game development techniques Focuses entirely on developing games with the free version of XNA Packed with many suggestions for expanding your finished game that will make you think critically, technically, and creatively Fresh writing filled with many fun examples that introduce you to game programming concepts and implementation with XNA 4.0 A practical beginner's guide with a fast-paced but friendly and engaging approach towards game development Read more about this book (For more resources on XNA 4.0, see here.) It was just another day at the bottom of the ocean until an explosion in one of the storage bays cracked the protective dome around Deep Sea Research Lab Alpha. Now the entire place is flooding, and the emergency pump system is a chaotic jumble of loose parts. Designing a puzzle game The Puzzler has always been a popular game genre. From old standbys like Tetris to modern crazes like Bejeweled, puzzle games are attractive to players because they do not require a long-term time investment or a steep learning curve. The game mechanic is the heart of any good puzzle game. This mechanic is usually very simple, with perhaps a few twists to keep the players on their toes. In Flood Control, the player will be faced with a board containing 80 pieces of pipe. Some will be straight pipes and some will be curved. The objective of the game is to rotate the pipes to form a continuous line to pump water from the left side of the board to the right side of the board. Completing a section of pipe drains water out of the base and scores points for the player, but destroys the pipes used. New pipes will fall into place for the player to begin another row. Time for action - set up the Flood Control project Open Visual Studio Express Edition (If it is already open, select Close Solution from the File menu so you are starting with an empty slate). In the Visual Studio window, open the File menu and select New Project... Under Project Type, make sure XNA Game Studio 4.0 is selected. Under Templates, select Windows Game (4.0). Name the project Flood Control. Click on OK. Right-click on Flood ControlContent (Content) in the Solution Explorer window and select Add | New Folder. Name the folder Textures. Add another folder under Flood ControlContent (Content) and name the folder Fonts. Download the 0669_02_GRAPHICPACK.zip file from the book's code download link and extract the files to a temporary folder. Back in Visual Studio, right-click on Textures in the Content project and click on Add | Existing Item. Browse to the folder where you extracted the 0669_02_GRAPHICPACK files and highlight all of them. Click on Add to add them to your project. What just happened? You have now set up a workspace for building Flood Control, and created a couple of folders for organizing game content. You have also imported the sample graphics for the Flood Control game into the project. Introducing the Content Pipeline The Flood ControlContent (Content) project inside Solution Explorer is a special kind of project called a Content Project. Items in your game's content project are converted into .XNB resource files by Content Importers and Content Processors. If you right-click on one of the image files you just added to the Flood Control project and select Properties, you will see that for both the Importer and Processor, the Content Pipeline will use Texture - XNA Framework. This means that the Importer will take the file in its native format (.PNG in this case) and convert it to a format that the Processor recognizes as an image. The Processor then converts the image into an .XNB file which is a compressed binary format that XNA's content manager can read directly into a Texture2D object. There are Content Importer/Processor pairs for several different types of content—images, audio, video, fonts, 3D models, and shader language effects files. All of these content types get converted to .XNB files which can be used at runtime. In order to see how to use the Content Pipeline at runtime, let's go ahead and write the code to read these textures into memory when the game starts: Time for action - reading textures into memory Double-click on Game1.cs in Solution Explorer to open it or bring it to the front if it is already open. In the Class Declarations area of Game1 (right below SpriteBatch spriteBatch;), add: Texture2D playingPieces;Texture2D backgroundScreen;Texture2D titleScreen; Add code to load each of the Texture2D objects at the end of LoadContent(): playingPieces = Content.Load<Texture2D>(@"TexturesTile_Sheet");backgroundScreen = Content.Load<Texture2D>(@"TexturesBackground");titleScreen = Content.Load<Texture2D>(@"TexturesTitleScreen"); What just happened? In order to load the textures from disk, you need an in-memory object to hold them. These are declared as instances of the Texture2D class. A default XNA project sets up the Content instance of the ContentManager class for you automatically. The Content object's Load() method is used to read .XNB files from disk and into the Texture2D instances declared earlier. One thing to note here is that the Load() method requires a type identifier, specified in angled brackets (< >), before the parameter list. Known in C# as a "Generic", many classes and methods support this kind of type specification to allow code to operate on a variety of data types. We will make more extensive use of Generics later when we need to store lists of objects in memory. The Load() method is used not only for textures, but also for all other kinds of content (sounds, 3D models, fonts, etc.) as well. It is important to let the Load() method know what kind of data you are reading so that it knows what kind of object to return. Sprites and sprite sheets As far as XNA and the SpriteBatch class are concerned, a sprite is a 2D bitmapped image that can be drawn either with or without transparency information to the screen. Sprites vs. TexturesXNA defines a "sprite" as a 2D bitmap that is drawn directly to the screen. While these bitmaps are stored in Texture2D objects, the term "texture" is used when a 2D image is mapped onto a 3D object, providing a visual representation of the surface of the object. In practice, all XNA graphics are actually performed in 3D, with 2D sprites being rendered via special configurations of the XNA rendering engine. The simple form of the SpriteBatch.Draw() call when drawing squares only needs three parameters: a Texture2D to draw, a Rectangle indicating where to draw it, and a Color to specify the tint to overlay onto the sprite. Other overloads of the Draw() method, however, also allow you to specify a Rectangle representing the source area within the Texture2D to copy from. If no source Rectangle is specified, the entire Texture2D is copied and resized to fit the destination Rectangle. OverloadsWhen multiple versions of the same method are declared with either different parameters lists or different return values, each different declaration is called an "overload" of the method. Overloads allow methods to work with different types of data (for example, when setting a position you could accept two separate X and Y coordinates or a Vector2 value), or leave out parameters that can then be assigned default values. By specifying a source Rectangle, however, individual pieces can be pulled from a large image. A bitmap with multiple sprites on it that will be drawn this way is called a "sprite sheet". The Tile_Sheet.png file for the Flood Control project is a sprite sheet containing 13 different sprites that will be used to represent the pieces of pipe used in the game. Each image is 40 pixels wide and 40 pixels high, with a one pixel border between each sprite and also around the entire image. When we call SpriteBatch.Draw() we can limit what gets drawn from our texture to one of these 40 by 40 squares, allowing a single texture to hold all of the playing piece images that we need for the game: The Tile_Sheet.png file was created with alpha-based transparency. When it is drawn to the screen, the alpha level of each pixel will be used to merge that pixel with any color that already occupies that location on the screen. Using this fact, you can create sprites that don't look like they are rectangular. Internally, you will still be drawing rectangles, but visually the image can be of any shape. What we really need now to be able to work with the playing pieces is a way to reference an individual piece, knowing not only what to draw to the screen, but what ends of the pipe connect to adjacent squares on the game board. Alpha blendingEach pixel in a sprite can be fully opaque, fully transparent, or partially transparent. Fully opaque pixels are drawn directly, while fully transparent pixels are not drawn at all, leaving whatever has already been drawn to that pixel on the screen unchanged. In 32-bit color mode, each channel of a color (Red, Green, Blue, and Alpha) are represented by 8 bits, meaning that there are 256 different degrees of transparency between fully opaque (255) and fully transparent (0). Partially transparent pixels are combined with the current pixel color at that location to create a mixed color as if the pixels below were being seen through the new color. Classes used in Flood Control While it would certainly be possible to simply pile all of the game code into the Game1 class, the result would be difficult to read and manage later on. Instead, we need to consider how to logically divide the game into classes that can manage themselves and help to organize our code. A good rule of thumb is that a class should represent a single thing or type of thing. If you can say "This object is made up of these other objects" or "This object contains these objects", consider creating classes to represent those relationships. The Flood Control game contains a game board made up of 80 pipes. We can abstract these pipes as a class called GamePiece, and provide it with the code it needs to handle rotation and provide the code that will display the piece with a Rectangle that can be used to pull the sprite off the sprite sheet. The game board itself can be represented by a GameBoard class, which will handle managing individual GamePiece objects and be responsible for determining which pieces should be filled with water and which ones should be empty. The GamePiece class The GamePiece class represents an individual pipe on the game board. One GamePiece has no knowledge of any other game pieces (that is the responsibility of the GameBoard class), but it will need to be able to provide information about the pipe to objects that use the GamePiece class. Our class has the following requirements: Identify the sides of each piece that contain pipe connectors Differentiate between game pieces that are filled with water and that are empty Allow game pieces to be updated Automatically handle rotation by changing the piece type to the appropriate new piece type Given one side of a piece, provide the other sides of the piece in order to facilitate determining where water can flow through the game board Provide a Rectangle that will be used when the piece is drawn, to locate the graphic for the piece on the sprite sheet Identifying a GamePiece While the sprite sheet contains thirteen different images, only twelve of them are actual game pieces (the last one is an empty square). Of the twelve remaining pieces, only six of them are unique pieces. The other six are the water-filled versions of the first six images. Each of the game pieces can be identified by which sides of the square contain a connecting pipe. This results in two straight pieces and four pieces with 90 degree bends in them. A second value can be tracked to determine if the piece is filled with water or not instead of treating filled pieces as separate types of pieces. Time for action - build a GamePiece class - declarations Switch back to your Visual C# window if you have your image editor open. Right-click on Flood Control in Solution Explorer and select Add | Class... Name the class GamePiece.cs and click on Add. At the top of the GamePiece.cs file, add the following to the using directives already in the class: using Microsoft.Xna.Framework.Graphics;using Microsoft.Xna.Framework; In the class declarations section, add the following: public static string[] PieceTypes = { "Left,Right", "Top,Bottom", "Left,Top", "Top,Right", "Right,Bottom", "Bottom,Left", "Empty"};public const int PieceHeight = 40;public const int PieceWidth = 40;public const int MaxPlayablePieceIndex = 5;public const int EmptyPieceIndex = 6;private const int textureOffsetX = 1;private const int textureOffsetY = 1;private const int texturePaddingX = 1;private const int texturePaddingY = 1;private string pieceType = "";private string pieceSuffix = ""; Add two properties to retrieve information about the piece: public string PieceType{ get { return pieceType; }}public string Suffix{ get { return pieceSuffix; }} What just happened? You have created a new code file called GamePiece.cs and included the using statements necessary to access the pieces of the XNA Framework that the class will use. Using DirectivesAdding the XNA Framework using directives at the top of the class file allows you to access classes like Rectangle and Vector2 without specifying their full assembly names. Without these statements, you would need Microsoft.Xna.Framework.Rectangle in your code every time you reference the type, instead of simply typing Rectangle. In the declarations area, you have added an array called PieceTypes that gives a name to each of the different types of game pieces that will be added to the game board. There are two straight pieces, four angled pieces, and an empty tile with a background image on it, but no pipe. The array is declared as static because all instances of the GamePiece class will share the same array. A static member can be updated at execution time, but all members of the class will see the same changes. Then, you have declared two integer constants that specify the height and width of an individual playing piece in pixels, along with two variables that specify the array index of the last piece that can be placed on the board (MaxPlayablePieceIndex) and of the fake "Empty" piece. Next are four integers that describe the layout of the texture file you are using. There is a one pixel offset from the left and top edge of the texture (the one pixel border) and a single pixel of padding between each sprite on the sprite sheet. Constants vs. Numeric literalsWhy create constants for things like PieceWidth and PieceHeight and have to type them out when you could simply use the number 40 in their place? If you need to go back and resize your pieces later, you only need to change the size in one place instead of hoping that you find each place in the code where you entered 40 and change them all to something else. Even if you do not change the number in the game you are working on, you may reuse the code for something else later and having easily changeable parameters will make the job much easier. There are only two pieces of information that each instance of GamePiece will track about itself—the type of the piece and any suffix associated with the piece. The instance members pieceType and pieceSuffix store these values. We will use the suffix to determine if the pipe that the piece represents is empty or filled with water. However, these members are declared as private in order to prevent code outside the class from directly altering the values. To allow them to be read but not written to, we create a pair of properties (pieceType and pieceSuffix) that contain get blocks but no set blocks. This makes these values accessible in a read-only mode to code outside the GamePiece class.
Read more
  • 0
  • 0
  • 4709

article-image-installing-and-configuring-jobs-and-managing-sections-categories-and-articles-using-jo
Packt
25 Sep 2010
4 min read
Save for later

Installing and Configuring Jobs! and Managing Sections, Categories, and Articles using Joomla!

Packt
25 Sep 2010
4 min read
  Building job sites with Joomla! A practical stepwise tutorial to build your professional website using Joomla!  Build your own monster.com using Joomla!  Take your job site to the next level using commercial Jobs! Extension  Administrate and publish your Joomla! job site easily using the Joomla! 1.5 administrator panel and Jobs! Pro control panel interface  Boost your job site ranking in search engines using Joomla! SEO Read more about this book (For more resources on Joomla!, see here.) Joomla! is a popular content management system, so it is mainly used for managing content. You can manage content from the Joomla! backend administrator panel. To go to this area, type in your web browser, the address of the server directory where the administrator folder is located. For example, if you have installed Joomla! in the joomla directory of local server, then the address is:http://localhost/ joomla/administrator. You will see the Joomla! Administration Login screen in your browser window. Log into the administrator panel as Super Administrator. By default, the username is admin. Then provide the password that you have created while you were configuring. Before adding an article as content, you must create a section and category for it. You can organize your content by using sections and categories because Joomla! uses a three-tier organization level for articles—Section | Category | Article. Any section contains one or more categories, and each category may have articles assigned to it. One article can only be in one category and section. You can easily add new sections, edit existing sections, publish or unpublish any section, and copy or delete sections from the Section Manager window. To manage sections, click on Contents | Section Manager (as shown in the following screenshot): The process of managing categories is quite similar to managing sections. You just need to click on Contents | Category Manager to go to Category Manager window and then manage your categories. After creating section and category, to add a new article from admin panel, click on Contents | Article Manager (as shown in the following screenshot): To add a new article, click on the New button in the Article Manager window and write your article with a title in Article: [New] window WYSISWYG editor area. You must also define the section and category for this article—which you have created earlier—and save this content. If you want to edit an article, select the article, click on Edit, and then make any changes in the article in Article: [Edit] window. Article Manager enables you to publish or unpublish an article. You can send an article to trash, copy an article, move an article, and so on. Just select an article and then click on the corresponding buttons. Managing extensions Components, modules, plugins, templates, and languages are collectively known as extensions. Each of these extensions is used for specific functions: Components: It is the largest and the most complex of the extension types. When a Joomla! web page is being loaded, a component is called to render the main page body. For example, the component com_banners displays a banner in a web page. Components are divided into two parts—for the administrator and for the frontend website. Modules: It is used for page rendering and doesn't need to be linked to anything. It can contain only static HTML, image, or text. For example, mod_mainmenu and mod_banners. Plugins: These were previously known as mambots. Using a plugin allows a developer to change the way their code behaves depending upon which plugins are installed to react to an event. Templates: It is basically the design of your Joomla! website. With a template, you can change the look and the feel of your website. Templates have certain fields in which components and modules are shown. You can easily create and customize any template file. Languages: Languages can be packaged in two ways—either as a core package or as an extension package—and allow both the Joomla! core as well as third-party components and modules to be localized or internationalized. To know more about extensions, go to the Joomla! documentation page: http://docs.joomla.org/Joomla!_Extensions_Defined. You can easily manage extensions by using the Extensions menu. For example, to install or uninstall any extension, click on the menu Extension | Install/Uninstall; to manage modules, click on the Module Manager; to manage plugins, click on the Plugin Manager; to manage templates, click on the Template Manager; and to manage language, click on the Language Manager.
Read more
  • 0
  • 0
  • 1314

article-image-installing-and-configuring-joomla-15
Packt
25 Sep 2010
7 min read
Save for later

Installing and Configuring Joomla! 1.5

Packt
25 Sep 2010
7 min read
  Building job sites with Joomla! A practical stepwise tutorial to build your professional website using Joomla!  Build your own monster.com using Joomla!  Take your job site to the next level using commercial Jobs! Extension  Administrate and publish your Joomla! job site easily using the Joomla! 1.5 administrator panel and Jobs! Pro control panel interface  Boost your job site ranking in search engines using Joomla! SEO Introduction You may have various approaches for building a jobsite, with job search and registration facilities for users and providing several services to your clients such as job posting, online application process, resume search, and so on. Joomla! is one of the best approaches and an affordable solution for building your jobsite, even if you are a novice to Joomla!. This is because Joomla! is a free, open source Content Management System (CMS) , which provides one of the most powerful web application development frameworks available today. These are all reasons for building a jobsite with Joomla!: It has a friendly interface for all types of users—designers, developers, authors, and administrators. This CMS is growing rapidly and improving since its release. Joomla! is designed to be easy to install and set up even if you're not an advanced user. Another advantage is that you need less time and effort to build a jobsite with Joomla!. You need to use a Joomla! jobsite extension to build your jobsite and you can use the commercial extension Jobs! because it's fully equipped to operate a jobsite, featuring tools to manage jobs, resumes, applications, and subscriptions. If you are looking for a jobsite such as Monster, Career Builder, a niche jobs listing such as Tech Crunch, or just posting job ads on your company site, Jobs! is an ideal solution. To know more about this extension, visit its official website http://www.instantphp.com/ Jobs! has two variations—Jobs! Pro and Jobs! Basic . The Jobs! Pro provides some additional features and facilities, which are not available in Jobs! Basic. You can use any one of them, depending upon your needs and budget. But if you need full control over your jobsite and more customization facilities, then Jobs! Pro is recommended. You can install Jobs! component and its modules easily, like any other Joomla! extension. You need to spend only a few minutes to install and configure Joomla! 1.5 and Jobs! Pro 1.3 or Jobs! Basic 1.0. It is a stepwise setup process. But first you must ensure that your system meets all the requirements that are recommended by developers. Prerequisites for installation of Joomla! 1.5 and Jobs! Joomla! is written in PHP and mainly uses MySQL database to store and manipulate information. Before installing Joomla! 1.5 and Jobs! extension, we need a server environment, that includes the following:     Software/Application Minimum Requirement Recommended Version Website PHP 5 5.2 http//php.net MySQL 4.1 or above 5 http://dev.mysql.com/downloads/mysql/5.0.html Apache 1.3 or above   http://httpd.apache.org IIS 6 7 http://www.iis.net/ mod_mysql mod_xml mod_zlib       You must ensure that you have the MySQL, XML, and zlib functionality enabled within your PHP installation. This is controlled within the php.ini file. Setting up a local server environment In order to run Joomla! properly, we need a server environment with pre-installed PHP and MySQL. In this case, you can use a virtual server or can choose other hosting options. But if you want to try out Joomla! on your own computer before using a remote server, we can set up a local server environment. To set up a server environment, we can use XAMPP solution. It comes equipped with Apache HTTP server, PHP, and MySQL. Installing these components individually is quite difficult and needs more time and effort. To install XAMPP, download the latest version of XAMPP 1.7.x from the Apache friends website: http://www.apachefriends.org/en/xampp.html. Windows operating system users can install XAMPP for Windows in two different variations—self-extracting RAR archive and ZIP archive. If you want to use self-extracting RAR archive, first download the .exe file and then follow these steps: Run the installer file, choose a directory, and click on the Install button. After extracting XAMPP, the setup script setup_xampp.bat will start automatically. After the installation is done, click on Start All Programs | Apache Friends | XAMPP | XAMPP Control Pane|. Start Apache and MySQL by clicking on the Start buttons beside each item. If prompted by Windows Firewall, click on the Unblock button.For more information on installing XAMPP on Windows or troubleshooting, go to the Windows FAQs page: http://www.apachefriends.org/en/faqxampp- windows.html. If you are using Linux platform, download the compressed .tar.gz file and follow these steps for installation: Go to a Linux shell and log in as the system administrator root: su Extract the downloaded archive file to /opt: tar xvfz xampp-linux-1.7.3a.tar.gz -C /opt XAMPP is now installed in the /opt/lampp directory. To start XAMPP, call the command: /opt/lampp/lampp start You should now see something similar to the following on your screen: Starting XAMPP 1.7.3a... LAMPP: Starting Apache... LAMPP: Starting MySQL... LAMPP started.   For more information on installing XAMPP on Linux or troubleshooting, go to the Linux FAQs page: http://www.apachefriends.org/en/faq-xampp-linux.html. If you want to use XAMPP in MAC operating system , download the .dmg file and follow these steps: Open the DMG-Image. Drag and drop the XAMPP folder into your Applications folder. XAMPP is now installed in the /Applications/XAMPP directory. To start XAMPP open XAMPP Control and start Apache and MySQL. After installation of XAMPP in a system, to test your installation, type the following URL in the browser: http://localhost/. You will see the XAMPP start page. Uploading installation packages and files to server Now, we need to copy or transfer Joomla! installation package files to server. Before copying the installation package, we must download Joomla_1.5.15-Stable-Full_ Package.zip from the webpage http://www.joomla.org/download.html, and then extract and unzip it. You can use WinZip or WinRAR to unzip these files. After unzipping the files, you have to copy files on your server root folder (for Apache, it is htdocs folder). If you are not using the XAMPP or local server environment, you need the File Transfer Protocol (FTP) software to transfer files to your server root folder, such as htdocs or wwwroot. The popular FTP software is FileZilla, which is absolutely free and available for different platforms, including Windows, Linux, and Mac OS. You can get it from the website http://filezilla-project.org/. Creating database and user Before installing and configuring Joomla! and Jobs! extension, we also need to create a database and a database user. You can easily add a new database and any user by using phpMyAdmin in XAMPP server environment. To add a database, by using phpMyAdmin, you must follow the following steps: Type the address http://localhost/phpmyadmin in the web browser. The front page of phpMyAdmin will be displayed. Type a name for the database you want to create. For example, my_db in the Create new Database field and then click on the Create button to create the database. To be connected with the database, we need a user account. You can add a user account by clicking on the Privileges tab of phpMyAdmin. You will see all users' information. Click on Add a new User link of Privileges window. After clicking on the link, a new window will appear. Provide the required information in the Login Information section of this window and then click on the Go button. We have now completed the preparation stage of installing Joomla!.
Read more
  • 0
  • 0
  • 3597
article-image-fine-tuning-sql-server-database-dynamics-nav
Packt
24 Sep 2010
5 min read
Save for later

Fine-tuning the SQL Server database for Dynamics NAV

Packt
24 Sep 2010
5 min read
  Microsoft Dynamics NAV Administration A quick guide to install, configure, deploy, and administer Dynamics NAV with ease Install, configure, deploy and administer Dynamics NAV with ease Install Dynamics NAV Classic Client (Dynamics NAV C/SIDE), Dynamics NAV Role Tailored Client (RTC), and Dynamics NAV Classic Database Server on your computer to manage enterprise data Connect Dynamics NAV clients to the Database Server in the earlier versions and also the latest Dynamics NAV 2009 version A step-by-step guide filled with examples to help you to accomplish administrative tasks such as securing and maintaining databases using Dynamics NAV   Read more about this book (For more resources on Microsoft see here.) SIFT In the Classic database server option, SIFT (Sum Index Flow Technology) is used to make the calculation of balances, sums, and so on. In any other database, this is normally done through calculations and could be a time-consuming process if there are thousands of records in the table. The SIFT data is stored in indexes, which are also called secondary keys in the Classic database server option. The balances based on the "secondary keys" are stored in separate indexes in the database. The programmer can define which fields need calculation by defining the SumIndexFields for the keys, as represented in the following screenshot. Therefore, the retrieval time for things such as account balances and such others is minimal, making the application extremely fast: What gives a boost to SIFT is the ability to filter on the underlying values that make up SIFT balances. This technology is also known as the flow filter technology, which complements the basic SIFT technology in a significant way. When SIFT was initially implemented on the Microsoft SQL Server database option for Dynamics NAV, it was done by storing these SIFT columns in summarized tables called SIFT tables that were continuously updated through SQL triggers. Thus, the procedure was expensive and took a toll on the performance when a table containing SIFT indexes was updated. From the Dynamics NAV 5.0 Service Pack 1 version, Microsoft decided to use indexed views in SQL Server instead of SIFT tables. Dynamics NAV creates one SQL indexed view per key, regardless of how many sum indexed fields there are in that key. Having too many SIFT indexes can adversely affect the performance of the application. Having too many fields in the SIFT indexes is also not advisable. The MaintainSIFTIndex property of the index in the base table could be used to optimally design the SIFT indexes. If there is the possibility of the base table not growing so rapidly, it is recommended to keep the MaintainSIFTIndex property to No. For more information about SQL indexed views, we can refer to the Microsoft SQL library. Using indexes/keys in Dynamics NAV Maintaining indexes for Microsoft Dynamics NAV has also been seen as a big performance issue. This is one of the major reasons for performance issues in the Dynamics NAV Classic database. The Microsoft SQL Server is clever enough to sort the data without any index, if the dataset being sorted is not huge. To access these properties of the keys, go to Object Designer, highlight the table in which the key needs to be modified, click on Design to open the list of fields in the table, and go to View | Keys. A window similar to the following screenshot opens, showing the list of keys: To open the properties of a particular key, highlight the key and then click on View| Properties, as shown in the following screenshot: These indexes or keys could be used optimally by using the following properties of the keys: Enabled: This is a property to enable or disable an individual key. A lot of times, developers create a one-off key to be used in a particular report or another piece of customization. This one-off key can be disabled or enabled based on the utilization or frequency of the use of customization. SumIndexFields: This property is used to define the SumIndexFields (whose sum needs to be maintained in the SQL indexed views). A maximum of 20 SumIndexedFields can be selected. KeyGroups: This is a method of combining the various keys together so that they could be enabled or disabled together. For example, in the following screenshot we see that the, Key Group property is defined as Consol, which is one of the key groups in the database. Keys can be combined together based on the nature of the use of keys or a particular application area. To enable or disable a key group, go to File | Database | Information. Click on the Key Group button in the bottom of the Database Information form to open a list of key groups defined in the database. MaintainSQLIndex: Microsoft SQL Server is clever enough to sort the data without an index, though to have the SQL Server sort faster, an index of the fields to be sorted can be created. Any writes to the table will be slower, as the number of indexes in a table grows, as those indexes will have to be updated along with each write transaction. MaintainSIFTIndex:We need to set this property to No if the data to be maintained in the SIFT base tables is less. Clustered: This is where we define whether or not the index is clustered. Clustered indexes are used to specify the sorting of data as it pertains to the storage in the table. In Dynamics NAV and also in a SQL Server database, a primary key is a clustered index by default. SQLIndex: We can specify here the actual list of fields that need to be a part of the SQL index. Investigating the performance of the database There are a few key performance troubleshooting techniques that are effective in identifying the bottlenecks in the performance of the database.
Read more
  • 0
  • 0
  • 5850

Packt
24 Sep 2010
6 min read
Save for later

Generating Content in WordPress Top Plugins—A Sequel

Packt
24 Sep 2010
6 min read
  WordPress Top Plugins Find and install the best plugins for generating and sharing content, building communities and generating revenue Learn WordPress plugin basics for both Macs and PCs Focuses exclusively on 100% free and open plugins Screenshots for each plugin Organized by complexity to install and manage Search Terms for automatic installation of plugins Instructions on configuring and setting up the more complex plugins Read more about this book (For more resources on WordPress see here.) CForms II By Oliver Seidel (http://deliciousdays.com) Why it's awesome: Super easy to create engaging and secure forms Why it was picked: Popularity and ease of use Manual Install URL: http://deliciousdays.com Automatic Install search term: CFORMS Geek level: Webmaster Configuration location: Top Navigation | cforms II Used in: Posts, widgets, pages WordPress lacks any methods for creating a form (beyond the comment form) to collect visitor questions, contact info, or any other type of communication data. CForms makes creating custom forms as easy as pointing and clicking. Forms can be embedded throughout your blog, including widgets, posts, and pages. CForms administration CForms is a very powerful and somewhat complex plugin, so let's take a moment to get familiar with the Administration section. Form Action is the somewhat hard-to-find Admin Actions. You will use this expandable menu to save your changes, delete, create, and back up your forms. Form Selection is how you switch between your different forms. Form Name is where you will define your form's name. This name will be used when you want to insert this form into a blog post, page, or widget. Fields are the individual inputs your form will contain. Kind of Field allows you to define a field as either a single line of text, multi-lined text, multiple-choice, captchas, file uploader, and a lot more. Add New Field will insert a new field into your form. Modifying the default form Once inside the CForms Administration, located at Settings | CForms II, you will see your "default form". This default form is the basic information needed to create a "Contact Us" form on your blog, including the field's name, e-mail, website, and message. Click the Field Sort Order icon, and drag it to reorder the field to any other position. Use the Default Value icon to specify what the field's default value should be, as well as mouse over values and error messages. Use the Delete this Field icon to remove a field from your form. Adding your form to a page, post, or widget CForms can be inserted into pages, posts, and widgets. However, the widget version is awfully wide and will most likely not look right in your sidebar. At the time of writing, there is no apparent way to modify this. Once inside the page or post editor, you will find a new icon added to your "Descriptions" toolbar. Once you click the CForms icon, you will need to select which form you would like to include. The drop-down box will contain all of the forms you currently have active. If you would rather use the coding method to insert your form, use the WP tag <!--cforms name="My Form Name"--> or the PHP tag <?php insert_cform("my form name"); ?>. Advanced CForms customizations While CForms might not be the easier form/mailer plugin available, it is hands down the most flexible. Make sure to delve into the additional options towards the bottom of the Form Manager. File upload settings If you will be using the File Upload field, you will need to provide some additional server information for it to work properly. Specifically, you will need to define where your file should be uploaded to, the maximum file sizes, and what type of files are allowed to be uploaded. Messages, text, and button label Customize your buttons, error messages, and text non-fictions for a given form. Core Form Admin / e-mail options Inside the Core Form Admin, you will be able to turn on and off the ability to track submissions in the RSS feed, set redirection rules, set start and end dates when a form will be shown. Admin e-mail message options Configure the e-mail message that will be sent to the administrator, once a user submits a form—including setting which e-mail address to send to, the header and footer html, and the from e-mail address. Auto confirmation Automatically send your visitor a confirmation e-mail, once they submit a form by clicking the Activate Auto confirmation link. Through this option, you will be able to configure the subject and message to send, the moment a form is submitted. Multi-part / multi-page forms Create multiple page forms by activating the Multi-part form option. Once activated, the Multi-part forms panel will allow you to define what step the current form in your process is, along with the ability to add back and next buttons. Tell-A-Friend form support The Tell-A-Friend field must be activated before you can leverage it. Once activated, you will have a new field type called "tell-a-friend". This "field" is actually multiple fields that are required to tell a friend about a given web page. WP comment feature You can actually replace WordPress' comment system with CForms. This might be helpful if you would like to customize the fields that a user can submit on a comment, or if you want the user to be able to send the author an e-mail opposed to a public comment. Third-party read-notification support CForm offers integration with notification services readnotify.com and didtheyreadit.com to notify you if a user reads your e-mail. These services might cause your e-mails to be triggered as spam. MapPress—Google maps By Chris Richardson (http://wphostreviews.com) Why it's awesome: Easily hack together some neat mashups on Google's dime Why it was picked: Popularity, ease of setup Manual Install URL: http://wordpress.org/extend/plugins/mappress-google-maps-for-wordpress/ Automatic Install search term: Mappress Geek level: Newbie Configuration location: Settings | MapPress Used in: Posts, pages MapPress makes it easy to insert custom Google Maps into your blog. Once installed, you will have the option to add multiple locations by address or lat/long. You will need a Google Maps API-key, which can be obtained from http://bit.ly/gmap-api. Google requires users who customize maps to have an API key. This allows them to track usage and ensure that people are not using Google Maps outside the 'Terms and Conditions'. If you do not have a need for customizing the content on the map, then you could always bypass installing this plugin and use the embed code directly from Google Maps. Adding a map to a post or page You will now have a new panel titled MapPress during the editing or creation of a post/page. The MapPress panel is where you define the size of your map, and the specific points of interest.
Read more
  • 0
  • 0
  • 1220
Modal Close icon
Modal Close icon