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-adding-random-background-image-your-joomla-template
Packt
02 Jul 2010
2 min read
Save for later

Adding a Random Background Image to your Joomla! Template

Packt
02 Jul 2010
2 min read
(Read more interesting articles on Joomla! 1.5 here.) Adding a random background image to your Joomla! template In distinguishing your Joomla! template from others, there are a number of extensions for Joomla! to help you, including one that allows you to display a random image as your template's background image for the <body> element. Getting ready You need to install the extension called Random Background. You can find the file's download link on the Joomla! website at http://extensions.Joomla.org/extensions/style-a-design/templating/6054. Once you have saved the extension files somewhere on your computer, log in to your website's Joomla! administration panel (if Joomla! is installed at example.com, the administration panel is typically accessible at example.com/administrator), and select the Install/Uninstall option from the Extensions option in the primary navigation: You will then be presented with a form, from where you can upload the extension's .zip file. Select the file from your computer, and then click on the Upload file & install button: Once complete, you should receive a confirmation message: Setting relevant permissions for installing the module If you have problems installing the module, you may receive an error message like the following one: The error is most likely because two directories on your server do not have sufficient permissions: /tmp /modules Use Joomla!'s FTP layer to manage the necessary file permissions for you. You can edit Joomla!'s configuration file, which is called configuration.php, in the root of your Joomla! website. Simply add these variables into the file if they don't exist already: var $ftp_host = ''; // your FTP host, e.g. ftp.example.com or just example.com, depending on your hostvar $ftp_port = ''; // usually 21var $ftp_user = ''; // your FTP usernamevar $ftp_pass = ''; // your FTP passwordvar $ftp_root = ''; // usually / or the directory of your Joomla! installvar $ftp_enable = '1'; // 1 = enabled
Read more
  • 0
  • 0
  • 5344

article-image-jasperreports-36-creating-simple-one-page-toc-your-report
Packt
30 Jun 2010
3 min read
Save for later

JasperReports 3.6: Creating a Simple, One-page TOC for Your Report

Packt
30 Jun 2010
3 min read
(For more resources on JasperReports, see here.) Getting ready Refer to the installPostgreSQL.txt file included in the source code download (chap5) to install and run PostgreSQL, which should be up and running before you proceed. The source code also includes a file named copySampleDataIntoPGS.txt, which helps you create a database named jasperdb6 and copy sample data for this recipe into the database. How to do it... Open the SimpleTOCReport.jrxml file from the Task2 folder of the source code. The Designer tab of iReport shows a report containing data in Title, Column Header, Customer Group Header 1, Product Group Header 1, Detail 1, and Product Group Footer 1 sections, as shown in the following screenshot: Switch to the Preview tab and you will see invoices for each customer grouped by product names. Switch back to the Designer tab. Right-click on the Variables node in the Report Inspector window on the left side of your report. From the pop-up menu that appears, select the Add Variable option. A new variable named variable1 will be added at the end of the variables list. While variable1 is selected, find the Name property in the Properties window below the Palette of components and change its value to FirstRecordOfANewGroup. Now the name of the variable1 variable will change to FirstRecordOfANewGroup. Select the Variable Class property and change its value to java.lang.Integer. Select the Calculation property and change its value to Count. Select the Reset type property and change its value to Group. Select the Reset group property and change its value to Customer. Select the Variable Expression property and click the button beside it. A Variable Expression window with no default expression will open, as shown in the next screenshot: Select Variables in the first column of the lower-half of the Variable Expression window. Then double-click the FirstRecordOfANewGroup variable in the second column. A new expression $V{FirstRecordOfANewGroup} will appear in the Variable Expression window, as shown in the next screenshot. Press the OK button. Right-click on the Variables node in the Report Inspector window. A pop-up menu will appear. Select the Add Variable option. A new variable named variable1 will be added at the end of the variables list. While variable1 is selected, find the Name property in the Properties window below the Palette of components and change its value to TOC. Now the name of the variable1 variable will change to TOC. Select the Variable Class property and change its value to java.lang.String.
Read more
  • 0
  • 0
  • 3651

article-image-microsoft-office-live-small-business-creating-and-customizing-your-webpage
Packt
30 Jun 2010
11 min read
Save for later

Microsoft Office Live Small Business: Creating and Customizing Your Webpage

Packt
30 Jun 2010
11 min read
Come to think of it, the starter website that Office Live Small Business built for you already has the first three pages in this list. And for good reason, even the professional designers at Microsoft, who built the starter website, think that pages along these lines are pretty much essential for most small-business websites. So, here's the plan: You'll begin by customizing the layout of the homepage. Once you're happy with the layout, you'll save it as a template that you can use to build new web pages. You'll then use this template to re-create the About Us and Contact Us pages. Why? Because you want all the pages on your website to look similar. The only way to do that reliably is to use the same template for all of them. Web pages need content. As I don't know much about your business, I can't provide you with readymade content for your web pages. But I'll give you tips on where to find good copy and pictures. I'll also give a few pointers on how to write good copy, if necessary. Using your new credentials as a copy writer, you'll write a copy for the two web pages that you've already built. You'll then add a new page, the Privacy Policy page, to your website. It goes without saying that you'll write a copy for that as well. Finally, you'll learn how to delete a web page by getting rid of the Site Map page. By the time you're done with this article, you'll have a fully functional four-page mini-website—content and all. You'll build on this foundation by improving the content of these pages and adding supplementary pages that describe your products, services, or whatever it is that you sell or hype. Editing the home page The Page Editor is the tool for editing web pages in Office Live Small Business.let's recap its features by opening the Home page. Time for action – opening the Home page in Page Editor Sign in to your Office Live Small Business account, if you haven't done so already, and go to Page Manager. Click the Edit link under the Options column for the Home page. The page opens in Office Live Small Business Page Editor, as shown in the next screenshot: From now on, I won't repeat these instructions; when I want you to open a page for editing, I'll simply say, Open such-and-such page in the Page Editor. What just happened? You opened the Home page in the Page Editor. Just like the Site Designer, the Page Editor too, has a Microsoft Office 2007-style ribbon at the top. The first two groups on the ribbon, Font and Paragraph, display familiar text editing commands. You can use these commands to format the text on the page just as you would on a word processor. If you want to underline a chunk of text, for example, select the text with your mouse and click the U button in the Font group on the ribbon, as shown: To undo something you've just changed, press CTRL+Z. If you want to right-justify a paragraph of text, place the cursor anywhere in the paragraph and click the Align Right button in the Paragraph group, as shown: See? Just like a word processor, as I said. The next group on the ribbon; Insert, displays commands that allow you to insert objects such as images, tables, and hyperlinks on the web page. Place the cursor anywhere in a zone—one of the regions on the page that's enclosed by red dotted lines, and click the Horizontal line button in the Insert group. it is a zone is an editable area on the page. All content on a page must reside within a zone. The Horizontal line button is shown in the next screenshot: A horizontal line appears just below the cursor. CTRL+Z works not only with text, but also with any other object that you insert on a page. The last group on the ribbon, Advanced, displays commands for manipulating some of the page's properties. Click on the Page Properties button, for example, and the Page properties dialog pops up. It's quite convenient to be able to access the Page properties dialog from the Page Editor, as you just did, and also from the Page Manager. You'll see that Office Live Small Business duplicates many such links to make your life easier. Some buttons, such as the Layout button in the Advanced group, have a little downward-pointing arrow at the bottom. Clicking them will open a drop-down selection menu. Go ahead, try it! Some other buttons, such as the Navigation button in the Advanced group, pop up dialog boxes where you can set properties. The rest, such as the Horizontal line button, work on the web page's text as you just saw. Don't worry if you don't understand what every command does at this stage; you'll go over them as you work along. Have a go hero – experiment with Page Editor commands Have a go at Page Editor's commands. It wouldn't harm to click a few of them and get an idea of Page Editor's features and capabilities. Add a table. Change the color of the text. Make the font bigger. Do whatever you please. And don't hesitate to experiment for fear of destroying the page. You can undo any change by pressing CTRL+Z. How many changes can you undo? I haven't really counted, so I can't give you an exact figure such as 23 or 127. But just as on a word processor, you can undo a series of changes with successive CTRL+Zs. I've noticed, however, that on some pages, CTRL+Z works only once for no apparent reason. In any case, you can effectively cancel all unsaved changes to a web page by not saving the page.How? Read on. Just as in Site Designer, you can preview your website after modifying a page in Page Editor. Click the View button at the top of the ribbon. A dialog pops up enquiring whether you wish to save the changes. If you do, you'd click OK. But because you were just playing around with the page, you can click Cancel this time. As you'd expect, you'd click the Save button, right next to the View button, if you wanted to save your changes. Close the preview window if it's still open, and return to Page Editor. Choosing a page layout Presently, the Home page is laid out with three content zones: Zone 1 at the top, spanning the entire width of the page, and Zone 2 and Zone 3 below it, side-by-side. This is not the only layout available; Page Editor has several more. Some have three zones, others have two, and the rest only have a single zone. You can change the layout of a page at any time; even after you've built the page. Let's change the layout of the Home page. Time for action – changing the Layout Open the Home page in Page Editor. Click the Layout button in the Advanced group of the ribbon. A menu drops down to reveal the available layouts as shown: Notice that each option has a little thumbnail schematic of the layout that it represents. The option that corresponds to the present layout of your Home page, Three, span top, is highlighted. Choose the Three, side by side option. The drop-down goes away and your Home page rearranges itself to conform to the new layout as shown: Notice that although the Page Editor has rearranged the zones, it has preserved the content inside each. But what if the layout I choose has fewer than three or more than three zones? Aha! That gets the Page Editor into a fix. While transferring the content of three zones to three new zones is quite straightforward, there's no logical way of transferring the content of three zones to two or four zones. So the Page Editor takes its best guess in rearranging the content. If you don't like it, you can always cut some content from one zone and paste it into another. Save the page and preview the website. Close the preview window and return to the Page Editor. What just happened? You learnt how to change the layout of a page in Page Editor. So what's the big deal? Well, it's a good idea to use the same layout on most of the pages on your website, if not all. A common layout makes life easier for you as well as the people who visit your site—you can build your site faster, and visitors can find things on your pages in predictable places. Therefore, choosing a single good layout for your website often plays a prominent role in its success. But then, you might ask, how come the good folks at Microsoft applied a different layout to every page on the starter site? The answer is that a single layout makes sense for small websites, such as yours, but sites with thousands of pages are often arranged into several logical sections and it's not unreasonable for pages in different sections to have different layouts. The starter site simply shows you an assortment of layouts, to give you an idea of how they look. You'll use the Three, side by side layout you just chose. But you won't be adding content to each of the zones; you'll use the middle zone for content and the zones on either side for padding. Customizing the page layout That's better. Your page now has precisely the number of zones that you wanted it to have. But what if you don't like how wide a specific zone is? Fear not! You can change the width of any zone on your page quite easily. Time for action – customizing a layout Select the content in Zone 1 and delete it. Unless you've played with the page layout and somehow managed to change the original order of the zones, the zones should be numbered 1, 2, and 3 from left to right. That's what I assume in the instructions.If your arrangement is different, read the instructions accordingly. Select the content in Zone 3 and delete it. Just above the top corners of each zone, you'll see a pair of drag handles as shown: You can use them to adjust the width of the zone, just as you can use the drag handles on a word processor to adjust the width of the editable area of a document. Click on the right drag handle of Zone 1 and drag it towards the left. That should make Zone 1 narrower. Click the left drag handle of Zone 3 and drag it towards the right. That should make Zone 3 narrower. Then use the drag handles of Zone 2, the middle zone, to stretch it on both sides. The end result should look something like this: Select the content in Zone 2 and delete it. At this stage, the cursor should be positioned in Zone 2. If it isn't, click in Zone 2 to place the cursor in it. Type Page Header. Notice that the text appears in the font that you set to be the site font . The font also appears as selected in the font selector on the ribbon. Anything you type in any of the zones will inherit this font by default, unless you change it explicitly. In the following images , you'll see the text in Georgia because that's the font I set for my site. You'll see it in the font that you selected. Select the text and increase its font size to 5 (18 pt) using the font size selector on the ribbon. Place the cursor just after the text that you just typed and click on the Horizontal line button on the ribbon. A horizontal line appears below the header text. Your page should now look something like this: Save your work and preview the site. Close the preview window and return to the Page Editor. What just happened? You learnt how to customize the layout that you've chosen for your web pages. From now on, you'll use this customized layout for all of your web pages.
Read more
  • 0
  • 0
  • 1748

article-image-moodle-19-working-mind-maps
Packt
30 Jun 2010
7 min read
Save for later

Moodle 1.9: Working with Mind Maps

Packt
30 Jun 2010
7 min read
In this virtual classroom, we are going to enrich the use of vocabulary, because in the creation of these techniques we have to use keywords, which have to be used in a piece of writing. Mind maps are going to be designed according to the facilities that the different software provides us to exploit them. Pictures in mind maps—using Buzan's iMindMap V4 In this task, we are going to use the software of the inventor of mind maps: Buzan's iMindMap V4. We are going to work on the topic of robots and afterwards students are going to write an article about them. We are going to provide students with images of different robots, taking into account that a robot is not a silver rectangular human look-alike. They may have several shapes and can be used for different purposes. Read the next screenshot, which is taken from Buzan's iMindMap V4 software, about inserting images in a mind map: Getting ready Let's create a mind map related to robots with pictures. After creating the mind map, students are going to look at it and they are going to write an article about the topic. In this case, the mind map will be designed with images only so as to "trigger associations within the brain" of our students. You can download a free trial of this software from the following webpage: http://www.thinkbuzan.com/uk/. How to do it... After downloading the free trial (you may also buy the software), create a new file. Then follow these steps to create a mind map with images using the previously mentioned software: Choose a central image in order to write the name of the topic in the middle, as shown in the next screenshot: In Enter some text for your central idea,, enter Robots as shown in the previous screenshot and click on Create. Click on Draw and select Organic, and draw the lines of the mind map, as shown in the following screenshot: To add images to the mind map, click on Insert and select Floating image, as shown in the next screenshot: Click on View and select Image Library and search for images, as shown in the next screenshot: Another option is to look for an image in Microsoft Word and copy and paste the images in the mind map. Save the file. How it works... We are going to select the Weekly outline section where we want to insert the activity. Then we are going to create a link to a file. Later, we will ask students to upload a single file in order to carry out the writing activity. Follow these steps: Click on Add a resource and select Link to a file or website. Complete the Name block. Complete the Summary block. Click on Choose or upload a file. Click on Upload a file. Click on Browse and search for the file, then click on Open. Click on Upload this file and then select Choose. In the Target block, select New window. Click on Save and return to course. The mind map appears as shown in the following screenshot: There's more... We saw how to create a mind map related to robots previously; now we will see how to upload this mind map as an image in your course. Uploading the mind map as .png file If your students do not have this software and they cannot open this file, you may upload this mind map in the Moodle course as an image. These are the steps that you have to follow: Open the file and fit the mind map in the screen. Press the Prt Scr key. Paste (Ctrl + V) the image in Paint or Inkscape (or any similar software). Select the section of the mind map only, as shown in the next screenshot: Save the image as .png so that you can upload the image of the mind map in the Moodle course. Drawing pictures using pen sketch It is also possible to use a digital pen, also known as pen sketch, to draw elements for the mind map. For example, as we are dealing with robots in this mind map, you can draw a robot's face and add it to the mind map, as shown in the next screenshot: Creating a writing activity You may add the mind map as a recourse in the Moodle course or you may insert an image in it. In both cases, students can write an article about robots. If you upload the mind map in the Moodle course, you can do it in the Description block of Upload a single file and you do not have to split the activity in two. Adding data to pictures—creating a mind map using MindMeister In this recipe, we are going to work with MindMeister software, which is free and open source.We are going to create a mind map, inserting links to websites, which contain information as well as pictures. Why? Because if we include more information in the mind map, we are going to lead our students on how to write. Apart from that, they are going to read more before writing and we are also exercising reading comprehension in a way. However, they may also summarize information if we create a link to a website. So let's get ready! Getting ready We are going to enter http://www.mindmeister.com/ and then Sign up for free. There is one version which is free to use, or you may choose the other two that are commercial. After signing up, we are going to develop a mind map for our students to work with. There is a video which is a tutorial explaining in a very simple and easy way on how to design a mind map using this software. So it is worth watching. How to do it... We are going to enter the previously mentioned website and we are going to start working on this new mind map. In this case, I have chosen the topic "Special days around the world". Follow these steps: Click on My New Mind Map and write the name of the topic in the block in the middle. Click on Connect and draw arrows, adding as many New node blocks as you wish. Add a website giving information for each special occasion. Click on the Node, then click on Extras–Links | Links and complete the URL block, as shown in the next screenshot: Then click on the checkmark icon. Repeat the same process for each occasion. You can add icons or images to the nodes of the mind map. Click on Share Map at the bottom of the page, as shown in the next screenshot: Click on Publish and change the button to ON, as shown in the next screenshot: Select Allow edit for everybody (WikiMap), as shown in the previous screenshot. You can also embed the mind map. When you click on Embed map, the next screenshot will appear: Copy the Embed code and click on Close. Click on OK. How it works... After creating the mind map about special occasions around the world, we will either embed it or create a link to a website for our students to work on a writing activity. Here the proposal is to work through a Wiki because in Map Properties we have clicked on Allow edit for everybody (WikiMap) so that students can modify the mind map with their ideas. Select the Weekly outline section where you want to insert the activity and these are the steps you have to follow: Click on Add an activity and select Wiki. Complete the Name block. Complete the Summary block. You may either embed the mind map or create a link to a website, as shown in the next screenshot: Click on Save and return to course.
Read more
  • 0
  • 0
  • 3102

article-image-adding-custom-field-compiere-3
Packt
30 Jun 2010
3 min read
Save for later

Adding a Custom Field in Compiere 3

Packt
30 Jun 2010
3 min read
(For more resources on Compiere 3, see here.) The user menu is your default tree, and is accessed through the System Administrator role. You can find the Menu item in the screen tree: The above screenshot illustrates a typical window set-up, which is done as follows: Create a new menu item by clicking on the New button. Enter a name and a description. Define its action type: A menu item's action type can be a Window, Form,Process, Report, Task, or Workflow. Link an AD item to the menu, which is illustrated above, where window Sales Order is linked to the Sales Order menu item. Move the menu item in context of the main menu tree for users understanding and access. It is recommended that you define your own windows, or copy from the existing dictionary, for customizations. Because dictionary (system) defined items may be overwritten during the process of migrating to a new version, it is better to copy a window and customize it in the copied window (or create new). This applies to Java code as well: never change the original source as it may be overwritten during migration. Adding a new field to a window and database In this section we are going to illustrate how the System Administrator would go about adding a new field to the database. As an illustration, we are going to add a probability reference field that can be used to measure a predefined set of outcomes on an order to the Sales Order window. .Find the context by Zooming to the Table from the Window. Open and find the Sales Order window in the Window, Tab, and Field menu item when logged in as System Administrator: Zoom from the window into the underlying Table and Column window.Order records are maintained in the database in the C_Order table: Next we refer the Column tab, and create a new column in the table(see the field naming conventions below). The new column must be as a System Element defined and hence we need to create a System Element prior to using it as a Column in the Table: Once the System Element has been defined, we set up the Column as follows: Create a new Reference key as follows: Because this is a custom list, we choose a validation type of List Validation, and a value format of L, indicating that any letters are allowed. For a full list of these conventions, refer to the help documentation in the system by pressing F1. We then define the Reference key's list validation options as follows: The finalized column (and thus the ultimate window field) set-up is thus shown as follows:
Read more
  • 0
  • 0
  • 1642

article-image-microsoft-office-live-small-business-extending-personal-website
Packt
30 Jun 2010
7 min read
Save for later

Microsoft Office Live Small Business: Extending the Personal Website

Packt
30 Jun 2010
7 min read
Re-creating the About Us page Okay, your Home page is now all set. Let's move on to the About Us page. Yes, I know:Office Live Small Business has already created an About Us page for your starter website. The trouble is, it doesn't use the same template as your Home page. Now that's a big no-no. Remember, we agreed that all web pages on your site will use your template. So, we'll have to find a way to apply your template to the About Us page. Unfortunately, none exists. Once you create a web page, it's married to its template; in the present version of Office Live Small Business, at least. Your only option is to create it again using a new template. Go to Page Manager. Click the New Page link or icon on the toolbar. The Create web page dialog pops up as shown. The first step in creating a web page is to choose a template for it. The Create web page dialog lists Standard Templates, which come bundled with Office Live Small Business, and Custom Templates, which you build yourself. Notice that the template that you built on earlier, Base Template, appears as a custom template in the selection box on the left. Select Base Template and click Next. The dialog asks you to Choose page properties. Enter About Us as the Page title. This title appears in the title bar of the browser when you view it. The title About Us is appropriate when referring to companies, groups, organizations, or businesses that involve several people. If you're a magician, for example, and your website touts your services for children's birthday parties, then you may want to change the title to About Me, or About Steve, the Magician (assuming you're Steve, of course). It sounds a little less pretentious. For my website, I'm going to change the title to About the Author, which is more appropriate for a website that's dedicated to a book. Type aboutus in the web address text box. The web address of the page will now be aboutus.aspx. It's a good idea to match a page's title and its web address. Because my page title is About the Author, I'll enter abouttheauthor in this text box. If your page title is About Steve the Magician, you should enter aboutstevethemagician here. Select the Overwrite existing page checkbox. You're creating a new About Us page. But a page by that name already exists. By selecting this checkbox, you're telling Office Live Small Business to go ahead and overwrite it. Select the Show this page in the navigation bar checkbox. Notice that Office Live Small Business automatically enters About Us (or About Steve the Magician, or whatever you entered as the page's title) in the Navigation title text box. Click Finish. The Create web page dialog goes away and the About Us page you just created appears in the Page Editor as shown: Hey! How come this picture shows both About Us and About the Author? Elementary, my dear Watson! Because I didn't call my page aboutus.aspx. Had I done so, Office Live Small Business would have replaced the original aboutus.aspx with my new aboutus.aspx.Because I called it abouttheauthor.aspx, the original aboutus.aspx is still intact. If you're in the same boat as I am in, you'll have to delete the About Us page. I'll show you how to do that later in this article. Select the text Page Header in Zone 2, and overwrite it with About Us (or About Steve the Magician, or whatever). Save your work and preview the page. Close the preview window and return to Page Editor. What just happened? You replaced the About Us page that Office live Small Business automatically created for you with a new page that uses your custom page template. As we discussed earlier, it's a good idea to use a common template for all of the pages on your website. Hence this exercise. Have a go hero – write copy for your about us page The About Us page is for introducing your business to visitors. Do it concisely; nobody really has the time to read a five page profile. Here's the copy that I'm using for my website: About the Author: Rahul Pitre has been writing software of one sort or another for twenty-five years, the last dozen or so of which he has spent developing mostly websites and web applications. He runs Acxede, a software consulting and training firm in New York, where he oversees web application and content development for a variety of clients. He holds a Masters degree in Business Administration and Computer Information Systems. Okay, it's your turn. Here's a rule of thumb that'll serve you well as you write some copy for this page: Write about what people will want to know about you; not what you want to tell people about yourself. Don't know where to start? Here are some points you might want to consider: What you do. How long you've been in business. The area that you serve. I highly recommend including your area and ZIP code in the copy. People often Google for phrases like Magicians in NY 10701. If you mention your general area and ZIP code in your text, there's a better chance of people finding you through search engines. Are you an authorized dealer for some big company? Again, people often search for phrases such as authorized Sony service center NY 10701. Have you received awards or citations for excellence? Are you a member of the Better Business Bureau or the local merchants' association? If your services are professional in nature, do you have the necessary qualifications? Licenses? Registrations? Insurance requirements? If you prefer writing conversational text, write it in short paragraphs. Alternatively, you can use a combination of text and bullet points. But, keep it short. And for heaven's sake, don't write a mission statement. Remember to write the text in a plain text editor such as Notepad; not in a word processor. Re-creating the Contact Us page Now let us now create the Contact Us page again using your site's template. Time for action – re-creating the Contact Us page Go to Page Manager. Click the New Page link or icon on the toolbar. The Create web page dialog pops up. Select Base Template and click Next. The dialog asks you to Choose page properties. Enter Contact Us as the Page title. This title appears in the title bar of the browser when you view it. Type contactus in the web address textbox. Select the Overwrite existing page checkbox. Select the Show this page in the navigation bar checkbox. Click Finish. The Create web page dialog goes away and the Contact Us page you just created appears in the Page Editor. Select the text Page Header in Zone 2, and overwrite it with Contact Us. Save your work and preview the page. What just happened? You replaced the Contact Us page that Office live Small Business automatically created for you with a new page that uses your custom page template. The Contact Us page is kind of unique. You might have noticed that the page you just replaced had a form for visitors to contact you. Normally, you'd have to write a little program to process the information they provide. The program would extract the information from the form and e-mail it to you. Thankfully, Office Live Small Business has a built-in component that does the job admirably. All that you need to do is to set the e-mail address at which you wish to receive the e-mails. Because you re-created the page, that form is now gone. The reason why I'm deferring it for now is that you haven't worked your way through a few prerequisites yet. Creating the Privacy Policy page you have to create your website's footer , you created a link to your website's "as yet non existent" privacy policy as shown: Let's now create a page that states your privacy policy and activate the link to it in the footer.
Read more
  • 0
  • 0
  • 1573
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-overview-compiere-application-dictionary-and-its-components
Packt
30 Jun 2010
4 min read
Save for later

Overview of the Compiere Application Dictionary and its Components

Packt
30 Jun 2010
4 min read
(For more resources on Compiere 3, see here.) The Compiere Application Dictionary (AD) The Application Dictionary makes Compiere a truly unique and flexible business framework. Compiere was originally designed from the ground up on a model driven architecture (MDA), as defined by the Object Management Group (OMG). The system design conforms to an open standard in its layered architecture between business, application, and platform logic. MDA separates the business logic modeling, from technology modeling so as to ensure that both can evolve within their own domains, but still keeping within a framework of an open standard (and platform independent) that interconnects the two. The benefit in the Compiere environment is that through modeling, design, and build the actual deployment time is greatly reduced. The AD also ensures a seamless upgrade of the platform while having little impact on the environment-specific business objects and processes. The Application Dictionary of Compiere is meta data driven, meaning that contextual data defines the experience. This also means that the end user presentation layer and thus, the Graphical User Interface (GUI) platform have been defined in different technologies (i.e. Java Swing, HTML, and Ajax) and offers endless possibilities. The Application Dictionaries can be illustrated as shown in: To access the Application Dictionary you need to log in as a System Administrator and refer to the sub menu shown in: We will use the Java Swing (Compiere Standard Edition) user interface for illustration purposes in this section. Table and columns This refers to the fundamental building blocks of the system, and links Compiere data to the underlying Table and Column structures in the database. Illustrated below is the Period table in the AD that links to the underlying table name of C_Period, which you will find in the database: If the underlying database already contains the required fields, then by pressing the Create Columns from DB button and having the correct DB Table Name, Compiere will create the columns from the database in the AD. Within a table, a key column must be created for use as the table identifier: Illustrated the key column C_Period_ID. A column links to a System Element, as explained below, and is linked to the underlying table through the Synchronize Column button. In effect, synchronization creates or updates a column to the underlying database. System elements System elements are the common data elements and are used for central terminology references. These system elements link the underlying database columns to business-speak, for instance, in the screenshot in Image 5, C_Period_ID would be translated into the actual period. System elements are also used for setting up translations, as well as help comments on column fields. Validation rules Field validation rules that are defined in the context of a column field are dynamically verified based on the predefined rules or user context, at time of rendering the data. For instance, when a Business Partner field is displayed for selecting, the Business Partner account must be active and not be a Summary Account as shown in Image 6. Based on the example shown in Image 6, a dynamic validation will be set up for the C_BPartner_ID column field (the Business Partner table key identifier) on the Order table, shown in Image 7. Reference A Reference refers to database column field types that are either Data Types (i.e. an Amount, Integer, Date, Time, image, hyperlink, etc.) or a List validation (i.e. user pre-defined dropdowns) or Table validation (i.e. drop-downs for table key columns). An example of a Data Type column would be a period start date. The Column field StartDate in the Period table in the database is defined as reference Date An example of a list validation on a Period Control Action (the actions that you can perform on a period) set-up is as shown in Image 9. The list defined through a Search Key and a Name. The list defined through a Search Key and a Name. Search keys are saved in the database. Table Validations are data-defined based on existing referenced key columns and SQL selection. An example of a table reference would be a Document type based on a table validation SQL query. Herewith, a Document type (C_DocType) is defined, but it refers to the appropriate Tenant/client so as to ensure that only the document types for a Tenant are displayed, shown in Image 11.
Read more
  • 0
  • 0
  • 2694

article-image-creating-catalyst-application-catalyst-58
Packt
30 Jun 2010
7 min read
Save for later

Creating a Catalyst Application in Catalyst 5.8

Packt
30 Jun 2010
7 min read
Creating the application skeleton Catalyst comes with a script called catalyst.pl to make this task as simple as possible. catalyst.pl takes a single argument, the application's name, and creates an application with that specified name. The name can be any valid Perl module name such as MyApp or MyCompany::HR::Timesheets. Let's get started by creating MyApp, which is the example application for this article: $ catalyst.pl MyAppcreated "MyApp"created "MyApp/script"created "MyApp/lib"created "MyApp/root"created "MyApp/root/static"created "MyApp/root/static/images"created "MyApp/t"created "MyApp/lib/MyApp"created "MyApp/lib/MyApp/Model"created "MyApp/lib/MyApp/View"18 ]created "MyApp/lib/MyApp/Controller"created "MyApp/myapp.conf"created "MyApp/lib/MyApp.pm"created "MyApp/lib/MyApp/Controller/Root.pm"created "MyApp/README"created "MyApp/Changes"created "MyApp/t/01app.t"created "MyApp/t/02pod.t"created "MyApp/t/03podcoverage.t"created "MyApp/root/static/images/catalyst_logo.png"created "MyApp/root/static/images/btn_120x50_built.png"created "MyApp/root/static/images/btn_120x50_built_shadow.png"created "MyApp/root/static/images/btn_120x50_powered.png"created "MyApp/root/static/images/btn_120x50_powered_shadow.png"created "MyApp/root/static/images/btn_88x31_built.png"created "MyApp/root/static/images/btn_88x31_built_shadow.png"created "MyApp/root/static/images/btn_88x31_powered.png"created "MyApp/root/static/images/btn_88x31_powered_shadow.png"created "MyApp/root/favicon.ico"created "MyApp/Makefile.PL"created "MyApp/script/myapp_cgi.pl"created "MyApp/script/myapp_fastcgi.pl"created "MyApp/script/myapp_server.pl"created "MyApp/script/myapp_test.pl"created "MyApp/script/myapp_create.pl"Change to application directory, and run "perl Makefile.PL" to make sureyour installation is complete. At this point it is a good idea to check if the installation is complete by switching to the newly-created directory (cd MyApp) and running perl Makefile.PL. You should see something like the following: $ perl Makefile.PLinclude /Volumes/Home/Users/solar/Projects/CatalystBook/MyApp/inc/Module/Install.pminclude inc/Module/Install/Metadata.pminclude inc/Module/Install/Base.pmCannot determine perl version info from lib/MyApp.pminclude inc/Module/Install/Catalyst.pm*** Module::Install::Catalystinclude inc/Module/Install/Makefile.pmPlease run "make catalyst_par" to create the PAR package!*** Module::Install::Catalyst finished.include inc/Module/Install/Scripts.pminclude inc/Module/Install/AutoInstall.pminclude inc/Module/Install/Include.pminclude inc/Module/AutoInstall.pm*** Module::AutoInstall version 1.03*** Checking for Perl dependencies...[Core Features]- Test::More ...loaded. (0.94 >= 0.88)- Catalyst::Runtime ...loaded. (5.80021 >= 5.80021)- Catalyst::Plugin::ConfigLoader ...loaded. (0.23)- Catalyst::Plugin::Static::Simple ...loaded. (0.29)- Catalyst::Action::RenderView ...loaded. (0.14)- Moose ...loaded. (0.99)- namespace::autoclean ...loaded. (0.09)- Config::General ...loaded. (2.42)*** Module::AutoInstall configuration finished.include inc/Module/Install/WriteAll.pminclude inc/Module/Install/Win32.pminclude inc/Module/Install/Can.pminclude inc/Module/Install/Fetch.pmWriting Makefile for MyAppWriting META.yml Note that it mentions that all the required modules are available. If any modules are missing, you may have to install those modules using cpan.You can also alternatively install the missing modules by running make followed by make install. We will discuss what each of these files do but for now, let's just change to the newly-created MyApp directory (cd MyApp) and run the following command: $ perl script/myapp_server.pl This will start up the development web server. You should see some debugging information appear on the console, which is shown as follows: [debug] Debug messages enabled[debug] Loaded plugins:.--------------------------------------------.| Catalyst::Plugin::ConfigLoader 0.23| Catalyst::Plugin::Static::Simple 0.21 |'--------------------------------------------'[debug] Loaded dispatcher "Catalyst::Dispatcher" [debug] Loaded engine"Catalyst::Engine::HTTP"[debug] Found home "/home/jon/projects/book/chapter2/MyApp"[debug] Loaded Config "/home/jon/projects/book/chapter2/MyApp/myapp.conf"[debug] Loaded components:.-----------------------------+----------.| Class | Type +-------------------------------+----------+| MyApp::Controller::Root | instance |'----------------------------------+----------'[debug] Loaded Private actions:.----------------------+-------- --------+----.| Private | Class | Method |+-----------+------------+--------------+| /default | MyApp::Controller::Root | default || /end | MyApp::Controller::Root | end|/index | MyApp::Controller::Root | index'--------------+--------------+-------'[debug] Loaded Path actions:.----------------+--------------.| Path | Private|+-------------------+-------------------------+| / | /default|| / | /index|'----------------+--------------------------------'[info] MyApp powered by Catalyst 5.80004You can connect to your server at http://localhost:3000 This debugging information contains a summary of plugins, Models, Views, and Controllers that your application uses, in addition to showing a map of URLs to actions. As we haven't added anything to the application yet, this isn't particularly helpful, but it will become helpful as we add features. To see what your application looks like in a browser, simply browse to http://localhost:3000. You should see the standard Catalyst welcome page as follows: Let's put the application aside for a moment, and see the usage of all the files that were created. The list of files is as shown in the following screenshot: Before we modify MyApp, let's take a look at how a Catalyst application is structured on a disk. In the root directory of your application, there are some support files. If you're familiar with CPAN modules, you'll be at home with Catalyst. A Catalyst application is structured in exactly the same way (and can be uploaded to the CPAN unmodified, if desired). This article will refer to MyApp as your application's name, so if you use something else, be sure to substitute properly. Latest helper scripts Catalyst 5.8 is ported to Moose and the helper scripts for Catalyst were upgraded much later. Therefore, it is necessary for you to check if you have the latest helper scripts. We will discuss helper scripts later. For now, catalyst.pl is a helper script and if you're using an updated helper script, then the lib/MyApp.pm file (or lib/whateverappname.pm) will have the following line: use Moose; If you don't see this line in your application package in the lib directory, then you will have to update the helper scripts. You can do that by executing the following command: cpan Catalyst::Helper Files in the MyApp directory The MyApp directory contains the following files: Makefile.PL: This script generates a Makefile to build, test, and in stall your application. It can also contain a list of your application's CPAN dependencies and automatically install them. To run Makefile.PL and generate a Makefile, simply type perl Makefile.PL. After that, you can run make to build the application, make test to test the application (you can try this right now, as some sample tests have already been created), make install to install the application, and so on. For more details, see the Module::Install documentation. It's important that you don't delete this file. Catalyst looks for it to determine where the root of your application is. Changes: This is simply a free-form text file where you can document changes to your application. It's not required, but it can be helpful to end users or other developers working on your application, especially if you're writing an open source application. README: This is just a text file with information on your application. If you're not going to distribute your application, you don't need to keep it around. myapp.conf: This is your application's main confi guration file, which is loaded when you start your application. You can specify configuration directly inside your application, but this file makes it easier to tweak settings without worrying about breaking your code. myapp.conf is in Apache-style syntax, but if you rename the file to myapp.pl, you can write it in Perl (or myapp.yml for YML format; see the Config::Any manual for a complete list). The name of this file is based on your application's name. Everything is converted to lowercase, double colons are replaced with underscores, and the .conf extension is appended. Files in the lib directory The heart of your application lives in the lib directory. This directory contains a file called MyApp.pm. This file defines the namespace and inheritance that are necessary to make this a Catalyst application. It also contains the list of plugins to load application-specific configurations. These configurations can also be defined in the myapp.conf file mentioned previously. However, if the same configuration is mentioned in both the files, then the configuration mentioned here takes precedence. Inside the lib directory, there are three key directories, namely MyApp/Controller, MyApp/Model, and MyApp/View. Catalyst loads the Controllers, Models, and Views from these directories respectively.
Read more
  • 0
  • 0
  • 2753

article-image-customizing-search-module-and-search-component-using-joomla-15
Packt
30 Jun 2010
4 min read
Save for later

Customizing Search Module and Search Component using Joomla! 1.5

Packt
30 Jun 2010
4 min read
Introduction Although we've seen how to alter much of our Joomla! website, there's still much we can do to improve and polish our Joomla! template to perfection. Styling the search module Joomla! is a powerful content management system which is capable of supporting websites with hundreds and even thousands of pages. When websites become this large, it's often important to provide your website's visitors with a search feature as a means of locating the information on your website that they are looking for. One option that Joomla! provides for your visitors to search your website is the search module, which is a block displayed within your template. Getting ready Identify the class or id assigned to your Joomla! template's search form, which is assigned by a jdoc include statement within your template's index.php file. In the rhuk_milkyway template—the one that we've been working with—the search feature is assigned to the user4 block by default with this jdoc statement: <jdoc:include type="modules" name="user4" /> It appears to the top-right of the template: If we now look at the page's HTML source, the HTML generated by Joomla! for the search feature looks like this: <div id="search"> <form action="index.php" method="post"> <div class="search"> <input name="searchword" id="mod_search_searchword" maxlength="20" alt="Search" class="inputbox" type="text" size="20" value="search." onblur="if(this.value=='')this.value='search...';" onfocus="if(this.value=='search...') this.value='';" /> </div> <input type="hidden" name="task" value="search" /> <input type="hidden" name="option" value="com_search" /> <input type="hidden" name="Itemid" value=1 /> </form> This means that we can apply CSS to #search to style our template's search box. How to do it... Open your template's primary stylesheet file, which is usually called template.css, and is located in the templatesrhuk_milkywaycss directory of your Joomla! installation. The rhuk_milkyway template already defines the style for the form as follows: #search { float: right; width:320px; margin-top: -20px; margin-right: 30px; height: 40px; overflow: hidden; text-align:right; } By adding CSS to change the search field's state when a visitor focuses within it, you can help improve your Joomla! template by orientating visitors to their whereabouts on the page: #search input[type='text']:focus { border-color: #09C /* blue */ } Once you've uploaded the altered template.css file, you will now see a blue border surrounding the search field: How it works... By using the CSS pseudo-class :focus, the browser changes the attributes we define to make it clearer to our website's visitors that their input device (for example, keyboard) is focused on the search input field. Internet Explorer versions 7 and below do not support the :focus pseudo-class. You can provide support in Internet Explorer for this feature of CSS with the use of JavaScript; see http://james.padolsey.com/javascript/fixing-focus-in-internet-explorer/. See also Understanding Joomla! template positions Styling the search component Styling the search component Along with providing the search module, which is embedded within your Joomla! template depending on the module position it is assigned to, there is the Joomla! search component. Getting ready Firstly, you need to access the search component on your Joomla! website. You can do this by visiting http://example.com/index.php?option=com_search, assuming that your Joomla! installation is installed in the root directory of the example.com domain. With the rhuk_milkyway template as your currently enabled template, you should see that the search component looks like this: Open your template's primary CSS file; for our example, this is templatesrhuk_milkywaycsstemplate.css. It is also worth studying the source of the search component page; you'll find that the search form is contained within a &gt;form< element identified with an id of searchForm. How to do it... In your template's CSS file (template.css), begin by styling the overall form first: form#searchForm { background: #E5F1FD; border: 1px #0C3A6D solid; border-radius: 10px; padding: 10px } Some browsers do not yet support the border-radius property in CSS, so you may just see the search form with squared corners. This changes the look of the search form as follows: Next, you'll style the search query field, which is identifiable by the #search_searchword id: #searchForm #search_searchword { border: 2px #0C3A6D solid; color: #0C3A6D } This helps to distinguish the search field from the other fields in the form: Lastly, you'll add some padding to the table cells used to lay the search component form out to provide a little more space between inputs to prevent visitors accidentally clicking: #searchForm table td { padding: 5px } That's the search form styled!
Read more
  • 0
  • 0
  • 4783

article-image-setting-basic-document-workflow-compiere-3
Packt
30 Jun 2010
2 min read
Save for later

Setting Up a Basic Document Workflow in Compiere 3

Packt
30 Jun 2010
2 min read
(For more resources on Compiere 3, see here.) Compiere's workflow processes form an integral part of the system. In this section we are going to learn how to setup a basic approval workflow for a document within Compiere. The system definitions are as follows: A workflow is made up of a node and transitions. A node refers to a piece of work. A transition is the action to get to the next node, based on a logical condition. The workflow process is the active workflow and an activity for the processing of the active node (an activity also may have multiple parallel processes). A workflow also has an active State. A Workflow State refers to whether the workflow is running, not running, not started, completed, aborted, or terminated. Nodes also have Owners or Responsible persons. Illustrative workflow example We are going to set up a workflow between two roles, whereby the Gardenworld Purchasing role will capture a Purchase Order and the order will be approved by the Gardenworld User role. This type of approval requires a flag, and Compiere has a built in IsApproved database field that is used for this purpose. Compiere has standard document workflows and transitions that are predefined within its workflow processes. These nodes are DocStart, DocPrepare, DocComplete, and DocAuto (automatic approval). What this means is that workflow processes already manage the transitions of documents, with the System being the Owner of these workflow nodes.
Read more
  • 0
  • 0
  • 2229
article-image-networking-tcl-using-udp-sockets
Packt
29 Jun 2010
10 min read
Save for later

Networking in Tcl: Using UDP Sockets

Packt
29 Jun 2010
10 min read
(For more resources on Tcl, see here.) TCP support is built in to the core of the Tcl interpreter. To be able to use the UDP protocol, you have to use an external package. The default choice is usually the TclUDP extension, which is available from http://sourceforge.net/projects/tcludp/ (it also comes as a part of ActiveTcl bundle; if you don't have it, install it with teacup install udp). In contrast to TCP, which is a connection-oriented protocol, UDP is connection-less. This means that every data package (datagram) travels from one peer to another on its own, without a return acknowledgement or retransmission in the case of lost packets. What is more, one of the peers may send packages that are never received (for example if the second peer is not listening at the moment), and there is no feedback information that something is going wrong. This implies a difference in the design for handling the transmission, which will be illustrated in the following example. Creating a UDP-based client Lets consider a simple 'time server', where the server sends the current time to any client application that subscribes for such notifications, of course using UDP connectivity. The format of each datagram will be rather simple: it will contain only the current time expressed in seconds. First let's have a look on client code: package require udpset s [udp_open]fconfigure $s -buffering nonefconfigure $s -remote [list 127.0.0.1 9876]puts -nonewline $s "subscribe"proc readTime {channel} { puts "Time from server: [read $channel]"}fileevent $s readable [list readTime $s]vwait foreverclose $s As you have probably figured out, the first line loads the TclUDP extension. The next line creates a UDP socket, using the udp_open command, and stores its reference in the s variable. The UDP protocol uses ports in the same way as TCP. If we executed udp_open 1234, the port value 1234 would be specified, but if omitted, the operating system would assign a random port. Note that if you specify a port that is already being used by any other program, an error will be generated. Next, we set the buffering mode to none, meaning that the output buffer will be automatically flushed after every output operation. We will discuss buffering issues more deeply later in this example. The newly created UDP socket is not connected to anything, as the UDP is connection-less. Such a socket is able to receive packets as they arrive at any time from any source, without establishing a data connection of any type. To have datagrams be sent to a specific destination, you should use the fconfigure command with a new option (introduced by TclUDP) –remote, along with a two-item list containing the target address and port: fconfigure $s -remote [list 127.0.0.1 9876]. In this example the server will be executed on local host (so you are able to run it even if you are not part of a network). Note that you can call this command any time you wish, causing successive datagrams to be sent to different peers. Now it is time to send a message to the server – in this case simply a string containing 'subscribe'. If –nonewline is omitted, puts would generate 2 datagrams (the second one containing the newline character) – it is likely that the puts implementation will write data twice to the buffer (the message, and then the new line character), and as the buffering is set to none, it is flushed immediately after each write. The other solution would be to set buffering to full and call flush $s after each socket write. The handling of incoming data is implemented based on event programming. The line: fileevent $s readable [list readTime $s] defines that every time the socket has some data to read (is readable), the command readTime with $s as an argument is called. The command itself is simple – it prints to the screen every piece of data that comes from the socket, read with the read $s command. Implementing service using UDP The code for the server is a bit more complicated, due to a need to track subscribed clients: package require udpset clients [list]proc registerClient {s} { global clients lappend clients [fconfigure $s -peer]}proc sendTime {s} { global clients foreach peer $clients { puts "sending to $peer" fconfigure $s -remote $peer puts -nonewline $s [clock seconds] } after 1000 [list sendTime $s]}set server [udp_open 9876]fconfigure $server -buffering nonefileevent $server readable [list registerClient $server]sendTime $servervwait forever The list named clients will hold an entry for each subscribed client; each entry is also a list containing IP address and port, so it suits perfectly for the fconfigure $s –remote command. The server opens a UDP socket on port 9876. We would like to avoid the word 'listens' in this context, as this socket does not differ in any way from the one used by the client. By contrast, TCP requires a special server type socket, for listening purposes. On every incoming data even, the registerClient procedure is executed. The command appends to the client's list information about the originator of the data (usually referred to as a peer) that has just arrived. This information is retrieved with fconfigure $s –peer. Although it may seem that this data is defined for the socket (represented by $s), in reality it refers to the most recent datagram received by this socket.   Every one second the procedure sendTime is called. The purpose of this command is to send the current time to all subscribed clients, so it iterates over the clients list, and for each one it first configures the socket with the target address and port (fconfigure $s -remote $peer), and then sends a datagram containing the time in the form of the output from the clock seconds command.   The server code is simple, it runs forever and there is no way to unsubscribe from receiving the data, but it demonstrates how to work with UDP in Tcl. The following picture shows an example of the execution of the server (timeServer.tcl)and two clients (timeClient.tcl): The first client connects from the port 4508, and the second one (started a few seconds later) from 4509. The most important observation is that UDP sockets are handled identically on both the client and server, so the name 'server' is actually contractual. It is worth mentioning that TclUDP supports multicasting and broadcasting of UDP packets. For details of how to perform this, please consult the package's manual. Sending reliable messages The UDP protocol lacks reliability, which is one of its main differences compared to TCP. Applications using UDP must either accept the fact that some of the datagrams may be lost, or implement equivalent functionality on their own. The same is true of topics like the order of incoming packets and data integrity. The implementation of such logic could be as follows in the following example that follows — the sender calculates the MD5 checksum of the data, and sends both to the receiver. The receiver calculates the checksum again and compares it to the received one – and in the case of equality, sends acknowledgment (in this example, the checksum is sent back). The sender will repeatedly attempt to send the data until the confirmation is received, or the permitted number of attempts has been reached. The sender code is as follows: package require udppackage require md5set s [udp_open]fconfigure $s -buffering nonefconfigure $s -remote [list 127.0.0.1 9876]proc randomData {length} { set result "" for {set x 0} {$x<$length} {incr x} { set result "$result[expr { int(2 * rand()) }]" } return $result}proc sendPacket {chan contents {retryCount 3}} { variable ackArray if {$retryCount < 1} { puts "packet delivery failure" return } set md5 [md5::md5 -hex $contents] # if ack received, remove ack and do not send again if {[info exists ackArray($md5)]} { puts "packet successfully delivered" unset ackArray($md5) return } puts "sending packet, # of retries: $retryCount" puts "packet content: $md5$contents" puts -nonewline $chan "$md5$contents" flush $chan # handle retries incr retryCount -1 after 1000 sendPacket [list $chan $contents $retryCount]}proc recvAckPacket {chan} { variable ackArray set md5 [read $chan] puts "received ack: $md5" set ackArray($md5) 1 }sendPacket $s [randomData 48]after 5000 sendPacket $s [randomData 48]after 10000 sendPacket $s [randomData 48]fileevent $s readable [list recvAckPacket $s]vwait forever The main logic is located in the sendPacket procedure. The last parameter is the number of retries left to deliver the data. The procedure calculates the MD5 checksum of the data to be sent (stored in contents variable) and first checks if the appropriate acknowledgment has already been received – if the array ackArray contains the entry for the checksum (that is concurrently an acknowledgment), it is removed and the datagram is considered to have been delivered. If it is not, then the checksum along with the data is sent to the receiver, and a sendPacket is scheduled to be executed again after one second, every time with retries counter decreased. If the procedure is called when the counter is equal to zero, the delivery is considered to be negative. The acknowledgments are received by the procedure recvAckPacket, which simply stores it into ackArray, allowing sendPacket to find it and react appropriately. The helper procedure randomData allows the generation of a random string of zeroes and ones of a given length. Note that this example does not cover the topic of received packets order. The receiver code: package require udppackage require md5 set server [udp_open 9876]fconfigure $server -buffering nonefileevent $server readable [list recvPacket $server]proc recvPacket {chan} { variable readPackets set data [read $chan] puts "received: $data" set md5 [string range $data 0 31] set contents [string range $data 32 end] if {$md5 != [md5::md5 -hex $contents]} { #the data are malformed puts "malformed data" return } # send an ack anyway, because original # might not have been received by other peer fconfigure $chan -remote [fconfigure $chan -peer] #simulate the ack package lost over network if {10*rand() > 7} { puts -nonewline $chan $md5 flush $chan } # check if this packet is not a duplicate if {[info exists readPackets($md5)]} { return } set readPackets($md5) [clock seconds] # handle packet here...}proc periodicCleanup {} { variable readPackets set limit [clock scan "-300 seconds"] foreach {md5 clock} [array get readPackets] { if {$clock < $limit} { unset readPackets($md5) } } after 60000 periodicCleanup}vwait forever The receiver will send back the acknowledgement each time the correct datagram is received, that is when the checksums sent (first 32 chars) and calculated locally are equal. It also stores in the readPackets array the time of arrival of each packet, which allows us to detect duplicated data and processing it only once. To make the example more vivid, about 70% of data loss is simulated by randomly not sending confirmations. The receiver also implements some simple logic for periodic clean up of the received datagrams log, to prevent it from becoming too huge and memory consumptive. The result of running the example can be as depicted: In this example, the first datagram was delivered successfully on the first attempt, the second one's delivery failed despite 3 attempts, and the last one was delivered on the second try. Summary In this article we saw how to handle the UDP communication in Tcl, with TclUDP extension as the implementation. Further resources on this subject: Tcl: Handling Email [article] Extending Applications in Tcl [article] Managing Certificates from Tcl [article]
Read more
  • 0
  • 0
  • 9185

article-image-indexing-mysql-admin
Packt
29 Jun 2010
6 min read
Save for later

Indexing in MySQL Admin

Packt
29 Jun 2010
6 min read
Using prefix primary keys In this example we will add indexes to two tables that are almost identical. The only difference will be the definition of their primary keys. You will see the difference in space consumption for secondary indexes between a regular full column primary key and a prefix primary key. The sample table structure and data are designed to demonstrate the effect very evidently. In real-world scenarios the effect will most certainly be less severe. Getting ready... Connect to the database server with your administrative account. How to do it... Download the sample script for this article from the book's website and save it to your local disk. In the example below, we will assume it is stored in /tmp/idxsizeestimate_sample.sql. Create a new database and make it the default database:CREATE DATABASE pktests; USE pktests; Import the sample data from the downloaded file. When done, you will be presented with some statistics about the two tables loaded. Note that both tables have an Index Length of 0. SOURCE /tmp/idxsizeestimate_sample.sql; Now with the sample tables present, add an index to each of them: ALTER TABLE LongCharKey ADD INDEX IDX_PAY_10(Payload(10)); ALTER TABLE LongCharKey10 ADD INDEX IDX_PAY_10(Payload(10)); Display the data and index sizes of the tables now:SHOW TABLE STATUS LIKE 'LongCharKey%'; Add another index to each table to make the difference even more evident:ALTER TABLE LongCharKey ADD INDEX IDX2_PAY_10(Payload(10));ALTER TABLE LongCharKey10 ADD INDEX IDX2_PAY_10(Payload(10)); Display the data and index sizes of the tables again and compare with the previous values:SHOW TABLE STATUS LIKE 'LongCharKey%'; Name Rows Data Length Index Length Index/Data Ratio LongCharKey 50045 30392320 28868608 94.99% LongCharKey10 50045 29949952 3178496 10.61%   With the second index added, the difference in index length becomes even clearer.   How it works... Executing the downloaded script will set up two tables with the following structures: CREATE TABLE `LongCharKey` (`LongChar` char(255) NOT NULL,`Payload` char(255) DEFAULT NULL,PRIMARY KEY (`LongChar`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;CREATE TABLE `LongCharKey10` (`LongChar` char(255) NOT NULL,`Payload` char(255) DEFAULT NULL,PRIMARY KEY (`LongChar`(10))) ENGINE=InnoDB DEFAULT CHARSET=latin1; The two tables are almost identical, except for the primary key definition. They are pre-filled with 50,000 records of sample data. The tables are populated with exactly the same 50,000 records of pseudo-random data. The Payload column is filled with sequences of 255 random letters each. The LongChar column is filled with a sequential number in the first 10 characters and then filled up to use all remaining 245 character with the same sort of random data.SELECT LEFT(LongChar,20), LEFT(Payload, 20) from LongCharKey LIMIT 5; LEFT(LongChar,20) LEFT(Payload, 20) 0000000000KEAFAYVEJD RHSKMEJITOVBPOVAGOGM 0000000001WSSGKGMIJR VARLGOYEONSLEJVTVYRP 0000000002RMNCFBJSTL OVWGTTSHEQHJHTHMFEXV 0000000003SAQVOQSINQ AHDYUXTAEWRSHCLJYSMW 0000000004ALHYUDSRBH DPLPXJVERYHUOYGGUFOS While the LongKeyChar table simply marks the whole LongChar column as a primary key with its entire 255 characters length, the LongCharKey10 table limits the primary key to the first 10 characters of that column. This is perfectly fine for this table, because the test data was crafted to be unique in this range. Neither one of the two tables has any secondary indexes defined. Looking at some relevant table data shows they are equally big (some columns left out for brevity): SHOW TABLE STATUS LIKE 'LongCharKey%'; Name Rows Data Length Index Length LongCharKey 50045 30392320 0 LongCharKey10 50045 29949952 0 With each index added, the Index Length for the first table will increase significantly, while for the second one its growth is much slower. In case of the LongCharKey table, each secondary index record will carry around with it a complete copy of the LongChar column because it is the primary key without limitation. Assuming a single byte character encoding, this means every secondary index record is blown up in size by 255 bytes on top of the 10 bytes needed for the actual index entry. This means a whole kilobyte is spent just for the primary key reference for every 4 records! In contrast to that, the primary key definition of the LongCharKey10 table only includes the leading 10 characters of the LongChar column, making the secondary index entry 245 bytes shorter and thereby explaining the much slower growth upon adding further indexes. Choosing InnoDB primary key columns In the article introduction we promised to shed some light on how to choose your InnoDB primary key columns sensibly. Be advised that choosing good primary key columns is not an exact science—there are multiple aspects that influence this decision. Depending on your needs and preconditions you will want to prioritize them differently from one table to the next. Consider the following as general advice rather than hard rules that must be obeyed unconditionally. Getting ready In order to make reasonable decisions on primary key columns, it is important to have a very clear understanding of what the data looks like in the table at hand. If you already have existing data that is to be stored in an InnoDB table—for example in MyISAM format—it can be helpful to compare it with the criteria below. If you are planning a new schema, you might have to guess about some characteristics of the future data. As is often the case, the quality of your choices is directly proportional to how good those guesses are. This recipe is less strict step-by-step instructions that must be followed from top to bottom and should be considered a list of properties a good primary key should have, even though you might decide some of them do not apply to your actual environment. As a rule of thumb, however, a column that fulfills all or most of the attributes described below is most probably a sensible choice for a primary key. See the How it works... section for details on the individual items. How to do it... Identify unique attributes: This is an absolute (technical) requirement for primary keys in general. Any data attribute that is not strictly guaranteed to be free of duplicates cannot be used alone as a primary key. Identify immutable attributes: While not absolutely necessary, a good primary key is never changed once it has been assigned. For all intents and purposes, you should avoid columns that have even a small chance of being changed for existing records Use reasonably short keys: This is the "softest" criterion of all. In general, longer keys have negative impacts on overall database performance—the longer the worse. Also, consider a prefix primary key. See Using prefix primary keys earlier in this article for more information. Prefer single-column keys: Even though nothing prevents you from choosing a composite primary key (a combination of columns that together form the uniqueness), this can easily become a hassle to work with, especially when handling foreign keys. Consider the clustered index nature of the primary key: As InnoDB's primary key is also clustered, you should take this special nature into account as well. It can speed up read access a lot, if you often have to query for key ranges, because disk seek times will be minimized.
Read more
  • 0
  • 0
  • 2254

article-image-advanced-wordpress-themes
Packt
29 Jun 2010
14 min read
Save for later

Advanced WordPress Themes

Packt
29 Jun 2010
14 min read
(For more resources on Wordpress, see here.) Creating a basic WordPress theme is great. You learn about The Loop, find the appropriate template tags to display the information that you want, and then you write some HTML and CSS to tie it all together. However, there comes a time when you're ready to take your themes to the next level. That is what this article is all about. In this article, you'll learn how to provide your theme's users with options about what is displayed and how it is displayed. You'll also learn about localizing your theme for an international audience and showing users information based on their current role. Finally, this article covers the essentials for packaging and distributing your theme via the WordPress.org theme repository. You'll need to follow a few simple steps to make sure that your theme is accepted and that it provides users with the best possible experience. Adding a theme options page As a theme developer, you have to make a lot of choices when you create a theme. What text should be displayed in certain locations? Will that text always be appropriate? How many posts should you display in a featured item carousel? How many levels should the nested navigation menu have? Part of being a good developer is knowing when to make these decisions for your theme's users, and when to give the users a choice. Many WordPress users are not comfortable with editing PHP files, so you need to provide some other way for users to make these choices. The best way, in the context of a WordPress theme, is to provide the users with a theme options panel. Getting started You need to have created a WordPress theme containing at least a style.css file and an index.php file. How to do it... First, you need to decide what choice you want to give your users. In this recipe, we're going to assume that you want users to be able to change the color of the name of their site, which is located in the site header. Next, you have to create the options page that lets users make their choice and save it. Open your theme's directory and create a new directory inside it called admin. Inside the admin directory, create a file called options.php. Open the options.php file, and insert the following code: <?php$settings = $this->get_settings();?><div class="wrap"> <h2><?php _e('My Theme Options' ); ?></h2> <?php if('1'==$_GET['updated']) { ?> <div id="my-theme-options-updated" class="updated fade"><p><?php _e('Settings saved!' ); ?></p></div> <?php } ?> <form method="post"> <table class="form-table"> <tbody> <tr> <th scope="row"><label for="custom-theme-header-color"> <?php _e('Header Color'); ?></label></th> <td> #<input type="text" class="regular-text" name="custom-theme-header-color" id="custom-theme-header-color" value="<?php echo esc_attr( $settings[ 'header-color' ] ); ?>" /> </td> </tr> </tbody> </table> <p class="submit"> <?php wp_nonce_field( 'custom-theme-save-options' ); ?> <input type="submit" class="button-primary" name="custom-theme-save-options" id="custom-theme-save-options" value="<?php _e( 'Save' ); ?>" /> </p> </form></div> This file contains all of the code necessary for the theme options page. The next thing that you need to do is to hook the admin page into the WordPress administrative menu. Open or create your theme's functions.php file and insert the following code: if (!class_exists('My_Theme')) { class My_Theme { var $settings = null; function My_Theme() { add_action('admin_init', array(&$this, 'save_settings')); add_action('admin_menu', array(&$this, 'add_admin_stuff')); } function add_admin_stuff() { add_theme_page(__('My Theme'), __('My Theme'), 'switch_themes', 'my-theme', array(&$this, 'display_theme_admin_page')); } function display_theme_admin_page() { include (TEMPLATEPATH.'/admin/options.php'); } function save_settings() { if (isset($_POST['custom-theme-save-options']) &&check_admin_referer('custom-theme-save-options') && current_user_can('switch_themes')) { $settings = $this->get_settings(); $settings['header-color'] = stripslashes($_POST['custom-theme-header-color']); $this->set_settings($settings); wp_redirect(admin_url('themes.php?page=my-theme&updated=1')); } } function get_settings() { if (null === $this->settings) { $this->settings = get_option('My Theme CustomSettings', array()); } return $this->settings; } function set_settings($settings) { if (is_array($settings)) { $this->settings = $settings; update_option('My Theme Custom Settings', $this->settings); } } } $my_theme = new My_Theme(); function get_custom_theme_header_color() { global $my_theme; $settings = $my_theme->get_settings(); $color = $settings['header-color']; if(empty($color)) { $color = '000000'; } return $color; } function the_custom_theme_header_color() { echo get_custom_theme_header_color(); }} This file hooks into two different WordPress administrative hooks. First, you add the administrative menu page by hooking into admin_menu. Then, you hook to admin_init to process and save the custom options present on the custom admin page. After you save these files, go to your administrative menu and look at the sidebar on the left-hand side under the Appearance heading. You should see a My Theme link, as shown in the following screenshot: Now, click on the My Theme link under the Appearance menu heading. If you've done everything correctly, you should see a page that looks like the following screenshot: Enter a value such as 99000 and click on the Save button, and you'll see a Settings saved! success message, as seen in the following screenshot: Now, you need to use your custom value somewhere in your theme. Open up your theme header (usually header.php or index.php) and insert the following code between the opening and closing <head> tags: <h1 style="color:#<?php the_custom_theme_header_color(); ?>;"><?php bloginfo(); ?></h1> View your site in a browser to see the change in color of the site title (this is usually the only text that uses the <h1> tag) with the custom option set to hexadecimal color value 990000: Now, whatever value you set for the custom option that we created will be used as the color for the site title. How it works... There are quite a few moving parts here, so let's go through them one by one. First, you created the administrative page. This was saved to /yourthemefolder/admin/options.php. This file contains all of the items contained on a typical WordPress admin page: A containing <div> with the wrap class A <h2> tag with the custom theme options title A form that posts back to itself Form elements arranged inside a <table> with the form-table class With all of these elements in place, you get a slick looking administrative page that blends in with the rest of the WordPress admin control panel. Next, you created a small script within the functions.php file that hooks the administrative menu into place and saves the options when the page is posted. You hooked to admin_menu to add the administrative page and admin_init to save the options using the WordPress add_action() function that accepts a key value pair of the named action as a descriptive string and the actual action to take place. Your custom options are saved when three conditions are met: The form posts back to itself. The system verifies the security nonce from the form. The currently logged-in user has the ability to switch themes (usually just the blog administrator). The options are saved as an array to the WordPress options table by using the update_ option function. When you need to retrieve the options, you call get_option and pass the appropriate key. In addition to the hooks that provide the core functionality of this script, you created two template tags. The tag the_custom_theme_header_color() allowed you to access, and get_custom_theme_header_color() allowed you to print the values you stored on the custom options page. Finally, you used the template tags that you created to take advantage of your custom option on the front-end by adding <?php _the_custom_theme_header_color(); ?>; to the style of the <h1> tag that controls the color and size of the blog title. In this particular instance, you're allowing your theme's users to modify the color of the theme's header. However, endless possibilities exist as you become more familiar with WordPress, and by expanding the options, you allow your users to modify your themes. There's more… You can add additional theme option settings to customize how users can edit your theme. Diving into administrative settings for themes Visit the WordPress codex at http://codex.wordpress.org/Function_Reference to learn more about the functions available to you for creating custom theme edit forms in the administrative area of WordPress. Allowing for multiple theme color schemes In the previous recipe, we covered the general way in which you provide your theme's users with an options page. In this recipe, you'll implement one of the most straightforward features that many premium themes possess: a theme color scheme chooser. Getting started You need to have created a WordPress theme containing at least a style.css file and an index.php file. Inside the template file containing your theme's <head> tag, you need to call the wp_head function. How to do it... You're going to be controlling the color schemes that users can select, by putting each one in a different CSS file. As such, the first thing that you have to do is to create these files. Open your theme's directory and create a new directory named schemes. Inside the schemes directory, create the files blue.css, red.css, and green.css. They should contain the following styles: @charset "utf-8";/* Blue.CSS Color Schemes Document Chapter 11 Example 2 */body{ color:#00f; /* very bright medium blue*/ background-color:#99ccff; /* light blue*/}/* theme links*/a., a:link, a:hover, a:visited {}a., a:link{color:#000099;} /* medium dark blue*/a:hover{color: #0066FF;} /* bright medium blue*/a:visited{color:#000099;}/* blog title styles*/h1.blog-title, h1.blog-title a{ color:#000033; /* dark blue*/ text-decoration:none;}#header a { color: #000033; text-decoration: none;}#header a:hover { color: #0066FF; text-decoration: underline;}#header a:visited{color:#000099;}h2{ color:#003399; /* medium blue*/ text-decoration:none;} #header{ background:none; font-family:arial, verdana, sans-serif; }h2 a { color:#003399;/* medium blue */ text-decoration:none;}h3.storytitle, h3.storytitle a{ color:#003399; /* medium blue*/ text-decoration:none;} @charset "utf-8";/* Red.CSS Color Schemes Document Chapter 11 Example 2 */body{ color:#660000; /* dark red */ background-color:#ffffcc; /* light orange-pink*/}/* theme links*/a., a:link, a:hover, a:visited {}a., a:link{color:#ff0000;} /* bright red */a:hover{color: #ff0033} /* bright pink */a:visited{color:#ff0000;}/* blog title styles*/h1.blog-title, h1.blog-title a{ color:#ff3333; /* medium pink-red*/ text-decoration:none;}#header a { color: #ff3333; text-decoration: none;}#header a:hover { color: #ff0033; text-decoration: underline;}#header a:visited{color:#ff3333;}h2{ color:#660000; /* medium medium dull red*/ text-decoration:none;}h2 a { color:#660000; /* medium medium dull red*/ text-decoration:none;}h3.storytitle, h3.storytitle a{ color:#ff3333; /* medium pink-red*/ text-decoration:none;}@charset "utf-8";/* Green.CSS Color Schemes Document Chapter 11 Example 2 */body{ color:#009933; /* dull medium green*/ background-color:#005826; /* dull dark green */}/* theme links*/a., a:link, a:hover, a:visited {}a., a:link{color:#00ff00;} /* bright light neon green*/a:hover{color: #33ff00;} /* bright green*/a:visited{color:#00ff00;}/* blog title styles*/h1.blog-title, h1.blog-title a{ color:#99cc99; /* light pale green */ text-decoration:none;}h2{ color:#33cc66; /* medium green */ text-decoration:none;}h2 a { color:#33cc66; /* medium green*/ text-decoration:none;}h3.storytitle, h3.storytitle a{ color:#33cc66; /* medium green*/ text-decoration:none;} Next, you have to create the options page that lets users make their choice and save it. Open your theme's directory and create a new directory inside it called admin. Inside the admin directory, create a file called options.php. Open the options.php file, and insert the following code: <?php$settings = $this->get_settings();$custom_schemes = $this->get_custom_themes();?><div class="wrap"> <h2><?php _e('My Theme Options' ); ?></h2> <?php if('1'==$_GET['updated']) { ?> <div id="my-theme-options-updated" class="updated fade"> <p><?php _e( 'Settings saved!' ); ?></p></div> <?php } ?> <form method="post"> <table class="form-table"> <tbody> <tr> <th scope="row"><label for="custom-theme-header-color"> <?php _e('Custom Color Scheme'); ?></label></th> <td> <select name="custom-theme-color"> <option <?php selected( $settings[ 'color' ], '' ); ?> value=""><?php _e('None'); ?></option> <?php foreach( (array)$custom_schemes as $key => $name ) { ?> <option <?php selected( $settings[ 'color' ], $key ); ?> value="<?php echo esc_attr($key); ?>"><?php echo esc_html($name); ?></option> <?php } ?> </select> </td> </tr> </tbody> </table> <p class="submit"> <?php wp_nonce_field( 'custom-theme-save-options' ); ?> <input type="submit" class="button-primary" name="custom-theme-save-options" id="custom-theme-save-options" value="<?php _e( 'Save'); ?>" /> </p> </form></div> This file contains all of the code necessary for the theme options page. This particular options page contains a <select> drop-down menu that displays the available color schemes to the theme's user. The next thing that you need to do is to hook the admin page into the WordPress administrative menu. Open or create your themes functions.php file, and insert the following code: <?php if (!class_exists('My_Theme')) { class My_Theme { var $settings = null; function My_Theme() { add_action('admin_init', array(&$this, 'save_settings')); add_action('admin_menu', array(&$this, 'add_admin_stuff')); add_action('init', array(&$this, 'enqueue_color_css')); } function add_admin_stuff() { add_theme_page(__('My Theme'), __('My Theme'), 'switch_themes', 'my-theme', array(&$this, 'display_theme_admin_page')); } function display_theme_admin_page() { include (TEMPLATEPATH.'/admin/options.php'); } function enqueue_color_css() { $settings = $this->get_settings(); if( !empty( $settings['color'] ) && !is_admin() ) { wp_enqueue_style( 'custom-theme-color', get_bloginfo( 'stylesheet_directory' ) . '/schemes/' . $settings[ 'color' ] ); } } function get_custom_themes() { $schemes_dir = TEMPLATEPATH . '/schemes/'; $schemes = array(); if( is_dir($schemes_dir) && is_readable( $schemes_dir ) ) { $dir = opendir($schemes_dir); while(false !== ($file = readdir($dir))) { if('.' != $file && '..' != $file) { $scheme_name = ucwords(str_replace( array('-','_','.css'), array(' ',' ',''), $file)); $schemes[$file] = $scheme_name; } } } return $schemes; } function save_settings() { if (isset($_POST['custom-theme-save-options']) && check_admin_referer('custom-theme-save-options') && current_user_can('switch_themes')) { $settings = $this->get_settings(); $settings['color'] = stripslashes( $_POST['custom-theme-color']); $this->set_settings($settings); wp_redirect(admin_url('themes.php?page=my-theme&updated=1')); } } function get_settings() { if (null === $this->settings) { $this->settings = get_option( 'My Theme Custom Settings', array()); } return $this->settings; } function set_settings($settings) { if (is_array($settings)) { $this->settings = $settings; update_option('My Theme Custom Settings', $this->settings); } } } $my_theme = new My_Theme();} This file hooks into two different WordPress administrative hooks. First, you add the administrative menu page by hooking to admin_menu. Then, you hook to admin_init to process and save the custom options present on the custom admin page. Finally, you hook to the init hook to enqueue the custom CSS stylesheet the user has selected. After you save these files, go to your administrative menu and look at the sidebar on the left-hand side, under the Appearance heading. You should see a My Theme link, as shown in the following screenshot: Now, click on the My Theme link under the Appearance menu heading. If you've done everything correctly, you should see an administrative page that looks like the one shown in the following screenshot: Select a value, such as Red, from the drop-down selection menu, and then click on the Save button. You'll see the Settings saved! message, as well as the chosen color scheme selected in the Custom Color Scheme drop-down menu. Finally, you can view the results of the color scheme change by opening up your site in a browser window. In the following screenshot, you can see what the page header of each of the three color schemes will look like:
Read more
  • 0
  • 0
  • 1860
article-image-working-business-rules-define-decision-points-oracle-soa-suite-11g-r1
Packt
29 Jun 2010
9 min read
Save for later

Working with Business Rules to Define Decision Points in Oracle SOA Suite 11g R1

Packt
29 Jun 2010
9 min read
Calling a business rule from BPEL Save the rule, and then switch back to our composite and double-click the LeaveRequest BPEL process to edit it. Drag a Business Rule from the BPEL Activities and Components palette into your BPEL process (before the Human Task activity). This will open the Business Rule dialog (as shown in the following screenshot): First, we need to specify a name for the Business Rule activity within our BPEL process, so give it a meaningful name such as LeaveApprovalRules. Next we need to specify the Business Rule Dictionary that we wish to use. If we click on the drop-down list, it will list all the dictionaries within our composite application, which in our case is LeaveApprovalRules that we have just defined. Select this and the rule dialog will be updated (as shown in the following screenshot) to enable us to specify additional information about how we want to invoke the rule. First, we need to select the decision service that we want to invoke from BPEL. Our rule only contains a single decision service, LeaveApprovalDecisionService, so select it. Once we've specified the service, we need to specify how we want to invoke the decision service. We specify this through the Operation attribute. Here we have two options: Execute function and reset the session Execute function If we choose the option Execute function and thus don't reset the session, if we were then to call the decision service several times within the same instance of our BPEL process, each new invocation would reuse the same session and would also evaluate facts asserted in any previous invocation. For our purposes, we just need to assert a single fact and run the ruleset, so accept the default value of Execute function and reset the session. Assigning facts The final step to invoke our business rules is to assign BPEL variables to the input and output facts. Click on the green plus symbol (as shown in the preceding screenshot), and this will launch the Decision Fact Map window, as shown in the following screenshot: At first glance, this looks like the standard Create Copy Operation window that we use when carrying out assigns within BPEL (which in reality is exactly what it is). The key difference is that we are using this to assign values to the input facts to be submitted to the rules engines, so the Type on the To side of the copy operation is a Business Rule Facts. The reverse is true for an output fact, where we use this dialog to map the output from the decision service back into a corresponding BPEL variable. For our purpose, we just want to map the initial LeaveRequest in the process inputVariable into the corresponding fact, as shown in the preceding screenshot. Then we will map the output fact, which will contain our updated LeaveRequest back into our inputVariable. When JDeveloper opens the Decision Fact Map window, the Variables folder for the Business Rules Facts (circled in the preceding screenshot) is closed and it appears that there are no input facts. You must double-click on this to open it and expose the facts. We have now wired the rule invocation into our BPEL process, before finally running our process; we need to modify our process to only invoke the workflow if the leave request hasn't been automatically approved. To do this, just drag a switch onto your process, and then drag your workflow task into the first branch in the switch and define a test to check that the LeaveRequest hasn't been approved. You are now ready to deploy and run your modified process. Using functions Our current rule only approves vacations of one day in duration, requiring all other leave requests to be manually approved. Ideally, we would like to approve holidays of varying duration as long as sufficient notice has been given, for example: Approve vacations of one day in duration with a start date that's two weeks or more in the future Approve if for 2-3 days and more than 30 days in the future Approve if 5 days or less and more than 60 days in the future Approve if 10 days or less and more than 120 days in the future To write these rules, we will need to calculate the duration of the leave period, as well as calculate how long it is before the start date. Out of the box, the rule engine provides the Duration extension methods, which allow us to calculate the number of days between two dates, but doesn't allow us to exclude weekends. So we will need to write our own logic to calculate these values. Rather than embedding this logic directly in each rule, best practice dictates that we place this logic into a separate function. This not only ensures that we have a single version of the logic to implement but minimizes the size of our rules, thus making them simpler and easier to maintain. For our purposes, we will create the following functions: startsIn: Which returns the number of days before the specified start date leaveDuration: Which returns the number of days from the start date to the end date, excluding weekends Creating a function To create our first function, within the rule editor, click on the Functions tab. This will list all the functions currently defined to our ruleset. To create a new function, click on the green plus icon, as shown in the following screenshot: This will add a new function with a default name (for example, Function_1) to our list. Click on the function name to select it and update it to startsIn. From the drop-down list, select the Return Type of the function, which is int in our case. Next, we need to specify the arguments we wish to pass to our function. Click on the green plus sign, as shown in the following screenshot, and this will add an argument to our list. Here we can specify the argument name (for example, startDate), and from the drop-down list, the argument Type, which should be XMLGregorianCalendar (when creating XML facts, the JAXB processor maps the type xsd:date to javax.xml.datatype.XMLGregorianCalendar). The list of valid types is made up of the basic types (for example, int, double, char, and so on), plus the XML facts (excluding object factories) and the Java Facts (excluding the Rules Extension Method) defined in our rules dictionary. The final step is to implement the business logic of our function, which consists of one or more actions. We enter these actions in the Body section of the function. The first action we need to create is one that creates a local variable of type calendar, which holds the current date. To do this, click on <insert action> within the Body section of our function. The rule editor will display a drop-down list that lists all the available actions. For our purpose, we want to create a new variable and assign a value to it, so select the assign new action, as shown in the preceding screenshot. This will insert atemplate for the assign new action into our function body (as shown in the following screenshot). We then configure the action by clicking on each part within the template and defining it as appropriate. The first part we need to define is the type of variable we wish to create. Click on the &lttype> element within our &ltassign> statement, and the rule editor displays a drop-down list displaying all the available types. For our purposes, select Calendar. Next, click on var. This will prompt us to enter the name of the variable that we want to create. Specify today, and hit enter. Finally, we need to specify the value we want to initialize our variable with. Click on the &ltexpression> element. The rule editor will display a drop-down box listing all the valid values we can assign to our variable, as shown in the following screenshot: Select Calendar.getInstance(), which will initialize our variable to hold the current date. For our second action, we want to calculate the number of days before the specified start date and place the result into the variable duration. To calculate this, we will make use of the Duration extension method provided with the rules engine. We will do this by defining another assign new action in a similar way to the previous action. The key difference is how we specify the &ltexpression>. This time, instead of selecting a value from the drop-down list, click on the Expression Builder icon (circled in the preceding screenshot) to launch the Expression Builder for the rules editor. The Expression Builder provides a graphical tool for writing rule expressions and is accessed from various parts of the rule editor. It consists of the following areas: Expression: The top textbox contains the rule expression that you are working on. You can either type data directly in here or use the Expression Builder to insert code fragments to build up the expression required. Variables, Functions, Operators, Constants: This part of the Expression Builder lets you browse the various components that you can insert into your expression. Once you've located the component that you wish to use, click the Insert Into Expression button, and this will insert the appropriate code fragment into the expression.<> The code fragment is inserted at the point within the expression that the cursor is currently positioned. Content Preview: This box displays a preview of the content that would be inserted into the expression if you clicked the Insert Into Expression button.
Read more
  • 0
  • 1
  • 6349

article-image-using-business-rules-define-decision-points-oracle-soa-suite-11g-r1-introduction
Packt
29 Jun 2010
6 min read
Save for later

Using Business Rules to Define Decision Points in Oracle SOA Suite 11g R1- An Introduction

Packt
29 Jun 2010
6 min read
At runtime, there may be many potential paths through a BPEL process, controlled by conditional statements such as switch or while activities. Typically, the business rules that govern which path to take at any given point are written as XPath expressions embedded within the appropriate activity. Although this is an acceptable approach, we often find that while the process itself may be relatively static, the business rules embedded within the activities may change on a more frequent basis. This will require us to update the BPEL process and redeploy it, even though the process flow itself hasn't changed. In addition, by embedding the rule directly within the decision point, we often end up having to reimplement the same rule every time it is used, either within the same process or across multiple processes. Apart from being inefficient, this can lead to inconsistent implementations of the rules, as well as requiring us to update the rules in multiple places every time it changes. The Oracle Business Rules engine that comes as part of the SOA Suite provides a declarative mechanism for defining business rules externally to our application. This not only ensures that each rule is used in a consistent fashion, but in addition, it makes it simpler and quicker to modify. We only have to modify a rule once and can do this with almost immediate effect, thus increasing the agility of our solution. For those of you familiar with 10gR3, you will notice that JDeveloper comes with a new rules editor which is a lot more intuitive and simpler to use than the old browser-based editor. In addition, 11gR1 introduces decision tables, which provide a spreadsheet-like format for defining rules. While still very much a developer-oriented tool, these improvements make the tool a lot friendlier for business analysts, allowing them to better understand the rules that have been written as well as make simple changes. In this article, we will introduce the new rules editor and look at how we can use it to define a decisions service to automate the approval of leave requests. Then, once we've done this, we'll see how to invoke the rule from the leave approval BPEL process. We will first implement these as a standard set of rules and then examine how we can simplify these rules by using a decision table. Business rule concepts Before we implement our first rule, let's briefly introduce the key components which make up a business rule. These are: Facts: Represent the data or business objects that rules are applied to. Rules: A rule consists of two parts, namely, an IF part that consists of one or more tests to be applied to a fact(s), and a THEN part that lists the actions to be carried out, should the test evaluate to true. Rule Set: As the name implies, it is just a set of one or more related rules that are designed to work together. Dictionary: A dictionary is the container of all components that make up a business rule. It holds all the Facts, Rule Sets, and Rules for a business rule. In addition, a dictionary may also contain decision tables, functions, variables, and constraints. We will introduce these in more detail later in this article. To execute a business rule, you assert (submit) one or more facts to the rules engine. It will apply the rules to the facts, that is, each fact will be tested against the IF part of the rule, and if it evaluates to true, then it will perform the specified actions for that fact. This may result in the creation of new facts or the modification of existing facts (which may result in further rule evaluation). XML facts The rule engine supports four types of facts: Java Facts, XML Facts, RL Facts, and ADF Facts. The type of fact that you want to use typically depends on the context in which you will be using the rules engine. For example, if you are calling the rule engine from Java, then you would work with Java Facts as this provides a more integrated way of combining the two components. As we are using the rule engine within a composite, it makes sense to use XML facts. The rule editor uses XML schemas to generate JAXB 2.0 classes, which are then imported to implement the corresponding XML facts. Using JAXB, particularly when used in conjunction with BPEL, places a number of constraints on how we define our XML schemas, including: Within BPEL, you can only define variables based on globally defined elements. Thus all input and output facts passed to the decision service must be defined as global elements within our XML schemas. When defining the input and output facts for any complexType (for example, tLeaveRequest), there can only be one global element of that type (for example, leaveRequest). The element naming convention for JAXB means that elements or types with underscores in their names can cause compilation errors. Decision services To invoke a business rule within a composite, we need to go through a number of steps. First, we must create a session with the rules engine, then we can assert one or more facts, before executing the ruleset and finally we can retrieve the results. We do this via a decision service (or function). This is essentially a web-service wrapper around a rules dictionary, which takes care of managing the session with the rules engine as well as governing which ruleset we wish to apply. The wrapper allows a composite to assert one or more facts, execute a ruleset(s) against the asserted facts, retrieve the results, and then reset the session. This can be done within a single invocation of an operation or over multiple operations. Leave approval business rule For our first rule, we are going to build on Adding in Human Workflow. It's a simple process requiring every leave request to go to an individual's manager for approval. However, what we would like is a rule that automatically approves a request as long as it meets certain company guidelines. To begin with, we will write a simple rule to automatically approve a leave request that is of the type Vacation and only for one day's duration. This is a pretty trivial example, but once we've done this, we will look at how to extend this rule to handle more complex examples.
Read more
  • 0
  • 0
  • 2225
Modal Close icon
Modal Close icon