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

How-To Tutorials - Web Development

1802 Articles
article-image-version-management-upk-35-part-2
Packt
18 Nov 2009
5 min read
Save for later

Version Management with UPK 3.5: Part 2

Packt
18 Nov 2009
5 min read
Restoring a deleted document In a client/server environment, content objects are never really deleted; they still exist on the server. Instead, they are removed from the Library folders so that they are not visible within the Library itself. However, they will appear in the Deleted documents view, from where developers can display and restore them. The only way they can be truly deleted is by the Administrator purging them. The advantage of this is that you can always (up until the point that the Administrator has purged it) "un-delete" a content object, if you realize that you deleted it by mistake. To restore (un-delete) a content object, carry out the following steps: From the Library screen, click on the drop-down button for the View field (which will normally indicate Details view) on the View toolbar, and select Deleted documents. A list of all of the content objects that have been deleted (but not purged) is displayed, as shown in the following screenshot: Right-click on the document that you want to restore, and select Restore from the context menu. This is the only option available on this context menu. The document is restored to the Library, and placed back in the folder it was originally deleted from. This location is also shown in the Original location column in the Deleted documents view. This will create another version in the version history for the content object—just as deleting it did. This is shown in the screenshot below: Exporting and importing content If you are working in a stand-alone environment and want to share your developed content with another user, you will need to export it from your Library so they can import it into their Library. If you are a developer working in a client/server environment, it is unlikely that you will need to export your content because all users will be able to access it in the same Library. However, even then there may be a need to export your content, for example: Your company may use a "staged" approach to implementation, whereby all content is developed in a Development library before being migrated to a more secure production environment If you are working with multiple libraries, then it is recommended that you always export/ import folders, and not simply Outline Elements and their contents. This will reduce the possibility of elements that appear in multiple outlines being overwritten on successive imports. You have developed content in one environment (for example, your personal stand-alone environment) and now want to bring it into your company's client/server environment You want to take a copy of everything you have done, as a personal back-up You want to export all of your content before upgrading to a new version of UPK and importing your content into the new version's Library Whatever the reason, UPK makes it easy to export content. In this section we'll look at just how to do this. You would not normally use this approach to export content for translation. Exporting content objects You can use the Export function to export content objects as an archive, publishing options, sound files, and content objects for localization. This section covers exporting content objects as an archive. You can export any type of content object to an archive: Modules, Sections, and Topics, as well as Web Pages and Packages. You can also export any of the objects in the System folder, such as Templates and Publishing Packages. To export a content object, carry out the following steps: In the Library, select on the content objects that you want to export. You can select a single object, or multiple objects of various types. You also have the option of selecting a folder and exporting all of the content within the folder. Select menu option Tools|Export|Documents. The Export dialog box is displayed, as shown in the following screenshot: Click on the Browse button next to the Export content to: field. The Save As dialog box is displayed, as shown below: Enter a suitable file name for your export file in the File name field. Note that UPK will automatically select a file type of Content archives (*.odarc) and add the file prefix .odarc (for OnDemand Archive. Note the reference to OnDemand even though the product is no longer called OnDemand!). Click on Save to confirm the destination folder and file. Back in the Export dialog box, under Selection Options, select whether you want to export only the specific content that you have selected (Export my selection), or the selected content and all related documents (Export my selection and related documents). Related documents are typically content objects such as web pages that are linked to the selected object(s). You can see a list of these objects by clicking the View related documents link. Depending on how you have organized your Library, you should normally export entire folders and their contents, not Outline Elements. Otherwise, you risk missing out objects that are not directly linked into the Outline, such as Packages. You also risk having broken links when you (re)import the content object(s). Click on Export. The selected content objects (and all related documents, if you chose that option) are exported to the specified file. While this is being done, a progress indicator is displayed for the object currently being exported, and the overall percentage complete. The export may be very quick, especially if you are only exporting one or two Topics so don't blink or you'll miss it. An example of the progress indicator is shown below: Once the export is complete, you are returned to the Library. As the content is exported to a single file, you can easily send the file to another Developer for importing into their UPK Library, save it to CD as a back-up, and so on. How to import content objects is described next.
Read more
  • 0
  • 0
  • 2291

article-image-learning-informatica-powercenter-9x
Packt
08 May 2015
3 min read
Save for later

Learning Informatica PowerCenter 9.x

Packt
08 May 2015
3 min read
Informatica Corporation (Informatica), a multi-million dollar company established on February 1993, is an independent provider of enterprise data integration and data quality software and services. Informatica PowerCenter is the most widely used tool of Informatica across the globe for various data integration processes. Informatica PowerCenter tool helps integration of data from almost any business system in almost any format. This flexibility of PowerCenter to handle almost any data makes it most widely tool in the data integration world. (For more resources related to this topic, see here.) Key features Learn the functionalities of each component in the Informatica PowerCenter tool and deploy them to accomplish executive reporting using logical data stores Learn the core features of Informatica PowerCenter tool along with its administration and architectural aspects Develop skills to extract data and efficiently utilize it with the help of world’s most widely used integration tool, and make a promising career in Informatica PowerCenter Difference in approach The simple thought behind this book is to put all the essential ingredients of Informatica, starting from basic things, such as downloads, extraction, and installation to working on client tools and high-level aspects, such as scheduling, migration, and so on. There are multiple blogs available across the Internet that talk about the Informatica tool but none presents end-to-end answers. We have tried to put up all the steps and processes in a systematic manner to help you easily start with the learning. In this book, you will get a step-by-step procedure for every aspect of the Informatica PowerCenter tool. While writing this book, the author has kept in mind the importance of live, practical exposure of the graphical interface of the tool to the audience and hence, you will notice a lot of screenshots illustrating the steps to help you understand and follow the process. The chapters area arranged in such a way that all the aspects of the Informatica PowerCenter tool are covered, and they are in a proper flow in order to achieve the functionality. Here is a gist regarding the significant aspects of the book: Installation of Informatica and the information regarding the administrator console of the PowerCenter tool The basic and advanced topics of the Designer Screen. Implementation of the different types of Slowly Changing Dimension Understanding of the Workflow Manager Monitoring the code Implementation of mapping using different types of transformations Classification of transformations Usage of Repository Manager Required skills Before you make your mind up about learning Informatica, it is always recommended that you have a basic understanding of SQL and Unix. Though these are not mandatory and you can easily use 90 percent of the Informatica PowerCenter tool without knowledge of these, the confidence to work in real-time SQL and Unix projects is a must-have in your kitty. People who know SQL will easily understand that ETL tools are nothing but a graphical representation of SQL. Unix is utilized in Informatica PowerCenter with the scripting aspect, which makes your life easy in some scenarios. Summary Informatica PowerCenter has emerged as one of the most useful ETLs employed to build enterprise data warehouses. The PowerCenter tool can make your life easy and can offer you some great career path if learnt properly. This book will thereby help you get a know-how of PowerCenter. Resources for Article: Further resources on this subject: Transition to Readshift [article] Cloudera Hadoop and HP Vertica [article] Learning to Fly with Force.com [article]
Read more
  • 0
  • 0
  • 2286

article-image-creating-courses-blackboard-learn
Packt
14 Aug 2013
10 min read
Save for later

Creating Courses in Blackboard Learn

Packt
14 Aug 2013
10 min read
(For more resources related to this topic, see here.) Courses in Blackboard Learn The basic structure of any learning management system relies on the basic course, or course shell. A course shell holds all the information and communication that goes on within our course and is the central location for all activities between students and instructors. Let's think about our course shell as a virtual house or apartment. A house or apartment is made up of different rooms where we put things that we use in our everyday life. These rooms such as the living room, kitchen, or bedrooms can be compared to content areas within our course shell. Within each of these content areas, there are items such as telephones, dishwashers, computers, or televisions that we use to interact, communicate, or complete tasks. These items would be called course tools within the course shell. These content areas and tools are available within our course shells and we can use them in the same ways. While as administrators, we won't take a deep dive into all these tools; we should know that they are available and instructors use them within their courses. Blackboard Learn offers many different ways to create courses, but to help simplify our discussion, we will classify those ways in two categories, basic and advanced. This article will discuss the course creation options that we classify as basic. Course names and course IDs When we get ready to create a course in Blackboard Learn, the system requires a few items. It requires a course name and a course ID. The first one should be self-explanatory. If you are teaching a course on "Underwater Basket Weaving" (a hobby I highly recommend), you would simply place this information into the course name. Now the course ID is a bit trickier. Think of it like a barcode that you can find on your favorite cereal. That barcode is unique and tells the checkout scanner the item you have purchased. The course ID has a similar function in Blackboard Learn. It must be unique; so if you plan to have multiple courses on "Underwater Basket Weaving", you will need to figure out a way to express the differences in each course ID. We just talked about how each course ID in Blackboard has to be unique. We as administrators will find that most Blackboard Learn instances we deal with have numerous course shells. Providing multiple courses to the users might become difficult. So we should consider creating a course ID naming convention if one isn't already in place. Our conversation will not tell you which naming convention will be best for your organization, but here are some helpful tips for us to start with: Use a symbol to separate words, acronyms, and numbers from one another. Some admins may use an underscore, period, or dash. However, whitespace, percent, ampersand, less than, greater than, equals, or plus characters are not accepted within course IDs. If you plan to collect reporting data from your instance, make sure to include the term or session and department in the course ID. Collect input from people and teams within your organization who will enroll and support users. Their feedback about a course's naming convention will help it be successful. Many organizations use a student information system, (SIS), which manages the enrollment process.   Default course properties The first item in our Course Settings area allows us to set up several of the default access options within our courses. The Default Course Properties page covers when and who has access to a course by default. Available by Default: This option gives us the ability to have a course available to enrolled students when it is created. Most administrators will have this set to No, since the instructor may not want to immediately give access to the course. Allow Guests by Default and Allow Observers by Default: The next options allow us to set guest and observer access to created courses by default. Most administrators normally set these to No because the guest access and observer role aren't used by their organizations. Default Enrollment Options: We can set default enrollment options to either allow the instructor or system administrator to enroll students or allow the student to self enroll. If we choose the former, we can give the student the ability to e-mail the instructor to request access. If we set Self Enrollment, we can set dates when this option is available and even set a default access code for students to use when they can self enroll. Now that we have these two options for default enrollment, most administrators would suggest setting the default course enrollment option to instructors or system administrators, which will allow instructors to set self enrollment within their own course. Default Duration: The Continuous option allows the course to run continuously with no start or end date set. Select Dates sets specific start and end dates for all courses. The last option called Days from the Date of Enrollment sets courses to run for a specific number of days after the student was enrolled within our Blackboard Learn environment. This is helpful if a student self enrolls in a self-paced course with a set number of days to complete it. Pitfalls of setting start and end dates When using the Start and End dates to control course duration, we may find that all users enrolled within the course will lose access. Course themes and icons If we are using the Blackboard 2012 theme, we have the ability to enable course themes within our Blackboard instance. These themes are created by Blackboard and can be applied to an instructor's course by clicking on the theme icon, seen in the following screenshot, in the upper-right corner of the content area while in a course. They have a wide variety of options, but currently administrators cannot create custom course themes. We can also select which icon sets courses will use by default in our Blackboard instance. These icon themes are created by Blackboard and will appear beside different content items and tools within the course. In the following screenshot, we can see some of the icons that make up one of the sets. Unlike the course themes, these icons will be enforced across the entire instance. Course Tools The Course Tools area offers us the ability to set what tools and content items are available within courses by default. We can also control these settings along with organizations and system tools by clicking on the Tools link under the Tools and Utilities module. Let's review what tools are available and how to enable and disable them within our courses. The options we use to set course tools are exactly same as those used in the Tools area we just mentioned. Use the information provided here to set tool availability with a page. Let's take a more detailed look into the default availability setting within this page. We have four options for each tool. Every tool has the same options. Default On: A course automatically has this tool available to users, but an instructor or leader can disable the tool within it Default Off: Users in a course will not have access to this tool by default, but the instructor or leader can enable it Always On: Instructors or leaders are unable to turn this tool off in their course or organization Always Off: Users do not see this tool in a course or organization, nor can the instructor or leader turn it on within the course Once we make the changes, we must click on the Submit button. Quick Setup Guide The Quick Setup Guide page was introduced into Blackboard 9.1 Service Pack 8. As seen in the following screenshot, it offers instructors the basic introduction into the course if they have never used Blackboard before. Most of the links are to the content from the On Demand area of the Blackboard website. We as administrators can disable this from appearing when an instructor enters the course. If we leave the guide enabled, we can add custom text to the guide, which can help educate instructors about changes, help, and support available from our organization. Custom images We can continue to customize default look and feel of our course shells with images in the course entry point and at the top of the menu. We might use these images to spotlight that our organization has been honored with an award. Here we find an example of how these images would look. Two images can be located at the bottom of the course entry page, which is the page we see after entering a course. Another image can be located at the top of the course menu. This area also allows us to make these images linkable to a website. Here's an example. Default course size limits We can also create a default course size limit for the course and the course export and archive packages within this area. Course Size Limits allows administrators to control storage space, which may be limited in some instances. When a course size limit is within 10 percent of being reached, the administrator and instructor get an e-mail notification. This notification is triggered by the disk usage task that runs once a day. After getting the notification, the instructor can remove content from the course, or the administrator can increase the course quota for that specific course. Maximum Course disk size: This option sets the amount of disk space a course shell can use for storage. This includes all course and student files within the course shell. Maximum Course Package Size: This sets the maximum amount of content from the Course Files area included in a course copy, export, or archive. Grade Center settings This area allows us to set default controls over the Grade History portion of the Grade Center. Grade history is exactly what it says. It keeps a history of the changes within the Grade Center. Most administrators recommend having grade history enabled by default because of the historical benefits. There may be a discussion within your organization to permit instructors to disable this feature within their course or clear the history altogether. Course menu and structures The course menu offers the main navigation for any course user. Our organization can create a default course menu layout for all new course shells created based on the input from instructional designers and pedagogical experts. As seen in the following screenshot, we simply edit the default menu that appears on this page. As administrators, we should pay close attention when creating a default course menu. Any additions or removals to the default menu are automatically changed without clicking on the Submit or Cancel buttons, and are applied to any courses created from that point forward. Blackboard recently introduced course structures. If enabled, these pre-built course menus are available to the instructor within their course's control panel. The course structures fall into a number of different course instruction scenarios. An example of the course structure selection interface is shown in the following screenshot:
Read more
  • 0
  • 0
  • 2285

article-image-overview-joomla-virtuemart
Packt
15 Jun 2011
12 min read
Save for later

An overview of Joomla! and VirtueMart

Packt
15 Jun 2011
12 min read
Navigating through the Joomla! and VirtueMart directories You should have a Joomla! and VirtueMart e-commerce site installed somewhere. If not, you should now install one first before reading on. From this point onward, we will assume that you can access a Joomla! VirtueMart site and can freely browse its content, either on your local computer using the file manager of your operating system or in a web server somewhere using an FTP client program. To work on the exercises, you should also be able to edit each of the files. OK. Let's start our study by navigating through the Joomla! directories. If you look at the root of your Joomla! site, you will be amazed how large the Joomla! project is. There are totally close to 5,000 files under some 350 directories! It would be difficult to find your way through this vast structure of files if there are no hints at all. Fortunately, Joomla! has a very good directory structure and will be easy to follow once you know its basic organization. Knowing your way through this vast structure is very important when embarking on any VirtueMart customization project of considerable size. The good news is that usually we only need to know a very small fraction of those 350 directories and 5,000 files. In the Joomla! root, the most important directories we need to know are the administrator, components, modules, and plugins directories (This does not mean that the other directories are not important. We highlight these few directories just because they are the directories we will reference from time-to-time) You will probably recognize that the last three of these shortlisted directories correspond to the three major extension types of Joomla! So within these directories, we will expect to see a series of subdirectories, each of which corresponds to an extension installed in the Joomla! framework. This is exactly the case, except for the plugins where the directories are arranged in terms of their type instead of their source. Let's take a closer look at one of the most important components that comes with Joomla!. Navigate to the components directory and open the subdirectory com_content. The com_content component is the one that manages articles we created in Joomla!. You have probably been using a lot of this component. Within this directory, you will find a number of files and a few subdirectories. We notice there is a file named controller.php and two subdirectories named models and views. We will have more to say on these in a moment. Let's move back to the root directory and take a look at the last important directory mentioned above. This administrator directory mimics the root directory in many respects. We see that most of the subdirectories we found in the root have a corresponding subdirectory within the administrator directory. For example, we find subdirectories named components and modules within the administrator as well. As we know, there are two main sections of a Joomla! website, also known as the frontend and the backend. The root directory and administrator directory are respectively the location where the frontend and backend files are located. While this dividing line is not rigid, we can use this as a guide when we want to locate a frontend or backend file. Since both the root and the administrator directories contain a subdirectory called components, to avoid ambiguity, we will refer to them as the root components and administrator components directory, respectively. Now, let's work our way a little bit down the directory tree to see how VirtueMart fits into this framework. Within the root components directory, you will see a subdirectory called com_virtuemart. Yes, this is the location where you can find all the files used by VirtueMart for the frontend. Under the com_virtuemart directory, among some other files and subdirectories, you will notice a themes subdirectory. You will find each of the VirtueMart themes you have installed there. The themes directory is the major work area. From now on, we will refer to the com_virtuemart directory under the root components directory as the root VirtueMart directory or the frontend VirtueMart directory. Within the administrator components directory, there is also a subdirectory called com_virtuemart where the backend VirtueMart files are located. Under this main directory, there are four subdirectories named as classes, html, languages, and sql. Obviously, these directories will contain, respectively, the class files, HTML files, language files, and SQL (also known as database) files. Actually, the classes and html directories have a deeper meaning than their names suggest, as we shall see in a moment. Structure of the Joomla! URL path Before leaving our high-level exploration of the Joomla! tree structure, let's digress a little bit to study how a Joomla! URL is built up. While the Joomla! directory structure is so complicated, the URL used to access the site is much simpler. Most of the time, the URL just starts with index.php?. (If you have a Search Engine Friendly or SEF system enabled, you should turn it off during the development and testing of your customization, or at least turn it off mentally while we are talking about the URL. You can turn off SEF in the Joomla! Configuration page.) For example, if we want to access the VirtueMart (frontend) home page, we can use the following URL: http://your_joomla_live_site/index.php?option=com_virtuemart Similarly, the URL http://your_joomla_live_site/administrator/index.php?option=com_virtuemart will bring up the VirtueMart backend control panel, if you're already logged in. All other Joomla! URL, in fact, work in the same way, although many times you see some additional parameters as well. (Don't forget to replace your_joomla_live_site in the above URL with your domain name and the Joomla! root directory, in case the site is not installed in the root.) Actually, the index.php script is the main entry into your Joomla! site. All major requests to the frontend start from here (major requests only since there are some other entry points as well, but they don't bother us at this point). Similarly, all major requests to the backend start from the file administrator/index.php. Restricting the entry point to the site makes it very easy to control authorized and unauthorized accesses. For example, if we want to put the site offline, we can simply change a configuration in Joomla! and all components will be offline as well. We don't need to change each page or even each component one-by-one. Understanding the structure of the Joomla! URL is pretty useful during the development and debugging process. Sometimes we may need to work on a partly live site in which the Joomla! site is already working, but the VirtueMart shop is still under construction. In such cases, it is common to unpublish the menu items for the shop so that the shop is still hidden from the public. The fact that the menu item is hidden actually means the shop is less accessible but not inaccessible. If we want to test the VirtueMart shop, we can still type the URL on the browser by ourselves. Using the URL http://your_joomla_live_site/index.php?option=com_virtuemart we can bring up the VirtueMart home page. We will learn some more tricks in testing individual shop pages along the way of our study of VirtueMart themes and templates. One simple application of what we learnt about the URL can be used when customizing Joomla!. When working with VirtueMart projects, we will need to go to the VirtueMart backend from time-to-time to modify the VirtueMart settings. As we all know, after logging in, what we have on the browser window is the control panel page. We will need to point to the components/virtuemart menu before we can open the VirtueMart backend home. This is not a complicated task, but will be very tedious if repeated every time we log back into the site. Can we make Joomla! smarter, to open the VirtueMart home by default when we log on? Yes, we can. The trick actually relates to what we talked about so far. If you want to customize Joomla! to open the VirtueMart backend by default, you can stay with me for the following warm-up exercise. I understand some of you may not want to change the default login page. Exercise 1.1: Making the Joomla! backend default to VirtueMart Open your favorite text editor. Navigate to the Joomla! site root. Open the file administrator/includes/helper.php. At around line 44 (the actual line may vary from version-to-version), change the code $option = 'com_cpanel'; to $option = 'com_virtuemart'; Save the file. Open your browser and log in to your Joomla! site. Alas, you should see the VirtueMart control panel instead of the Joomla! control panel. This simple exercise demonstrated that sometimes a useful change does not need complex coding. What we need is a little knowledge of how things work. I bet you probably understand what we have done above without explanation. After login, Joomla! will automatically go to the default component, hardcoded in the file helper.php. For standard Joomla!, this will be the com_cpanel component. In Exercise 1.1, we have changed this default backend component from com_cpanel to com_virtuemart. Instead of VirtueMart, we can certainly change the default to other components such as community builder or MOSET. Joomla! 1.5 presentation framework Since VirtueMart is a Joomla! component, it cannot exist outside Joomla!. So before diving into the detail of the VirtueMart engine, it pays to take a brief look at how Joomla! actually works. While an understanding of the presentation framework of Joomla! and VirtueMart may be useful for themes and templates development, it is not essential for the actual customization design. Joomla! emerged from version 1.0 and later developed into 1.5. In this upgrade, Joomla! has been basically rewritten from the ground up. A presentation structure called Model-View-Controller or MVC has been adopted in Joomla! 1.5. While a detailed explanation of the MVC structure is out of the scope, a basic understanding of its working will help us understand why and how VirtueMart 1.1 behaves in the way it is right now. Joomla! is a web application. Each page of Joomla! is in fact a text file consisting of HTML code. Depending on the detail parameters of a web request, Joomla! will generate a dynamic HTML page by combining data stored in the database and site configuration data stored in various PHP files. In the early history of dynamic web pages, program code were written in a way that HTML tags are mixed with presentation logic in one place. The spaghetti code, as it is sometimes called, makes maintenance and extension of the coding very difficult. As the basic structure of a dynamic web page is better understood, more and more new coding patterns emerge to make the life of a web developer easier. The MVC presentation framework is one of those patterns that have been proposed to build computer applications. This framework has gradually become the standard pattern for building web applications and has been adopted by many open source web projects. Models In the MVC presentation framework , the job of building a web page is divided into three main tiers. The backend tier is the data that is stored in the database (strictly speaking, there is no prescribed data storage format though a database is a natural way to manage the data). We need to grab data needed to build the web page. This tier of the job is done by the Model, which describes how data is stored and how data can be retrieved from the data server. Views The frontend tier determines what and how data is presented on the browser. This is the job of the View. For a given dataset from a Model, there can be many different ways to present the data. Let's say, we have a set of statistical data, for example. We can present this data as a bar graph or a pie chart. Each of these presentations is called a View of the same Model. Controllers Now statistical data is just a set of numbers. How can we convert them into a bar graph or a pie chart? That is exactly how the Controller comes into place. A Controller is a routine specifying how to convert the Model into various Views. One major advantage of this separation of data (Model) and presentation (View) makes changes to the application much easier. We can change the presentation independent of the underlying data and vice versa. So, in the Joomla! 1.5 world, we will have a set of Models which interface with the database, a set of Views to tell the browser how to present the data, and a set of Controllers that control how to convert the Model into the View. According to the best practice, all Joomla! 1.5 components should follow this same structure. Thus, each Joomla! 1.5 component should have two subdirectories called models and views. Also, the root directory will contain a controller.php which extends the Joomla! controller's capability. This structure is revealed as we look at the contents of a Joomla! component which we had done previously. However, because of historical reasons and others, not all components follow this best practice. VirtueMart is one of those exceptions.
Read more
  • 0
  • 0
  • 2280

article-image-replication-alert-monitor-monitoring-management
Packt
26 Nov 2010
10 min read
Save for later

Replication Alert Monitor: Monitoring Management

Packt
26 Nov 2010
10 min read
IBM InfoSphere Replication Server and Data Event Publisher Design, implement, and monitor a successful Q replication and Event Publishing project Covers the toolsets needed to implement a successful Q replication project Aimed at the Linux, Unix, and Windows operating systems, with many concepts common to z/OS as well A chapter dedicated exclusively to WebSphere MQ for the DB2 DBA Detailed step-by-step instructions for 13 Q replication scenarios with troubleshooting and monitoring tips Written in a conversational and easy to follow manner We use the ASNMCMD command to manage a running RAM monitor. When we issue the asnmcmd command, we need to specify: The monitor server name The monitor name And then one of the following keywords: chgparms <parameters>, reinit, status, stop, qryparms, suspend, resume. Where <parameters> can be: monitor_interval=<n>, autoprune= [yn], alert_prune_limit=<n>, trace_limit=<n>, max_notifications_per_alert=<n>, max_notifications_minutes=<n>| We can issue this command from a different screen from which the monitor was started. Checking which monitors are active To check which monitors are active, we can use the ASNMCMD command with the STATUS parameter. So to check the status of the monac1 monitor on mondb, we would issue: $ asnmcmd MONITOR_SERVER=mondb MONITOR_QUAL=monac1 STATUS ASN0600I "AsnMcmd" : "" : "Initial" : Program "asnmcmd 9.1.0" is starting. ASN0520I "AsnMcmd" : "MONAC1" : "Initial" : The STATUS command response: "HoldLThread" thread is in the "is resting" state. ASN0520I "AsnMcmd" : "MONAC1" : "Initial" : The STATUS command response: "AdminThread" thread is in the "is resting" state. ASN0520I "AsnMcmd" : "MONAC1" : "Initial" : The STATUS command response: "WorkerThread" thread is in the "is resting" state. If there is nothing running, then we get the following messages: ASN0600I "AsnMcmd" : "" : "Initial" : Program "asnmcmd 9.1.0" is starting. ASN0506E "AsnMcmd" : "ASN" : "Initial" : The command was not processed. The "Monitor" program is presumed down. Note that there is a slight delay of a few seconds between the ASN0600I message and the ASN0506E message. We can check when a monitor last ran using the following query: $ db2 "SELECT SUBSTR(monitor_qual,1,10) AS monqual, last_monitor_time, start_monitor_time, end_monitor_time, lastrun, lastsuccess, status FROM asn.ibmsnap_monservers" MONQUAL LAST_MONITOR_TIME START_MONITOR_TIME MONAC1 2007-03-16-10.18.57.750000 2007-03-16-10.18.57.750000 END_MONITOR_TIME 2007-03-16-10.18.59.765000 LASTRUN LASTSUCCESS STATUS 2007-03-16-10.18.57.750000 2007-03-16-10.18.57.750000 0 Changing or reinitializing a monitor If we change any of the following while the monitor is running such as contact information, alert conditions, or parameter values: $ asnmcmd MONITOR_SERVER=mondb MONITOR_QUAL=monac1 CHGPARMS MONITOR_INTERVAL=10 Then we do not have to stop and start the monitor, we can just reinitialize it as follows: $ asnmcmd MONITOR_SERVER=mondb MONITOR_QUAL=monac1 REINIT Stopping a monitor To stop a monitor called monac1, we would issue the following command: $ asnmcmd MONITOR_SERVER=mondb MONITOR_QUAL=monac1 STOP Suspending or resuming a monitor We cannot suspend a monitor from the Replication Center, we can only use ASNCLP scripts. We can stop checking Q Capture and Q Apply for all defined alert conditions using the ASNMCMD SUSPEND command. When we want to resume monitoring again, then we issue the ASNMCMD RESUME command. Note that using the ANSMCMD command is an all or nothing approach. The SUSPEND option will suspend all monitoring qualifiers. So what happens if we just want to suspend monitoring one monitored sever (DB2A or DB2B)? In this case, we would have to create a monitor suspension. We can suspend a monitor once only or on a repeatable basis. If we want to suspend a monitor on a repeatable basis, then it's best to first create a suspension template and then create a monitor suspension. If we want to suspend a monitor server once only, then we just need to create a monitor suspension. All dates and times for monitor suspensions are based on the clock at the system where the monitor is running (MONDB). The time format is HH:MM:SS and the date format is YYYY-MM-DD. The ASNCLP command to create a monitor suspension template is: CREATE MONITOR SUSPENSION TEMPLATE <template_name> START TIME <starting_time> REPEATS occ-clause Where occ_clause can be: DAILY FOR DURATION <n> [HOURS | MINUTES] Or: WEEKLY DAY OF WEEK <day> FOR DURATION <n> [HOURS/MINUTES/DAYS] Where <day> can be Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, or Saturday. The ASNCLP command to create a monitor suspension is: CREATE MONITOR SUSPENSION <name> [FOR SERVER <server_name> | ALIAS <server_alias>] STARTING DATE <date> [USING TEMPLATE <template_name> | STARTING TIME <starting_time>] ENDING DATE <date> ENDING TIME <ending_time> So when should we use templates? We should use them: If we want to suspend more than one monitor at the same date or time. If we want to suspend a monitor on anything but a daily basis. Note that, we can specify a day of week when we create a monitor suspension template, which is not possible in the monitor suspension definition. There are eight ASNCLP commands which deal with monitor suspensions: ASNCLP command:Description:LIST MONITOR SUSPENSIONGenerates a list of suspensions on a monitor control server.ALTER MONITOR SUSPENSIONAllows us to change the following properties of a monitor suspension: • The template that is used • The start or end date for using a template • The start or end date for suspending the monitor program one timeDROP MONITOR SUSPENSIONDeletes a monitor suspension from the monitor control tables.LIST MONITOR SUSPENSION TEMPLATEGenerates a list of monitor suspension templates on a monitor control server.ALTER MONITOR SUSPENSION TEMPLATEAllows us to change the frequency and length of monitor suspensions as defined in a suspension template.DROP MONITOR SUSPENSION TEMPLATEDeletes a monitor suspension template from the monitor control tables.CREATE MONITOR SUSPENSION TEMPLATECreates a monitor suspension template.CREATE MONITOR SUSPENSIONCreates a monitor suspension. Even though we want to monitor Q replication, we need to specify SQL replication in the ASNCLP SESSION line. So let's look at the ASNCLP command to create a monitor suspension template called LUNCH which starts daily at 12:00 and lasts for one hour: ASNCLP SESSION SET TO SQL REPLICATION; SET RUN SCRIPT NOW STOP ON SQL ERROR ON; SET SERVER MONITOR TO DB mondb; CREATE MONITOR SUSPENSION TEMPLATE lunch START TIME 12:00:00 REPEATS DAILY FOR DURATION 1 HOURS; In the preceding command, we have not specified a server on which to apply the suspension—we have only defined the monitor server where to store the metadata. We have also not specified a start and end date—only a start and end time. Once we have created a monitor suspension template, we can define a monitor suspension for a specific server (that is, source or target) and a specific date range, which uses the template we defined previously. ASNCLP SESSION SET TO SQL REPLICATION; SET RUN SCRIPT NOW STOP ON SQL ERROR ON; SET SERVER MONITOR TO DB mondb; SET SERVER TARGET TO DB db2b; CREATE MONITOR SUSPENSION NAME s1 FOR SERVER db2b STARTING DATE 2007-03-20 USING TEMPLATE lunch ENDING DATE 2007-12-31; In the above monitor suspension code, we do not have to specify a time value, because the time value is specified in the template definition. Note that now we have to specify a server for the template to work against. We can also define a monitor suspension without making reference to a template by specifying all the information that we need (this would be the once only processing model): CREATE MONITOR SUSPENSION NAME s2 FOR SERVER db2a STARTING DATE 2007-03-20 STARTING TIME 12:00:00 ENDING DATE 2007-12-31 ENDING TIME 13:00:00 In the above monitor suspension definition we have not specified a template, so we have included the start and end dates and times. We can list our monitor suspension templates and monitor suspensions using the following ASNCLP command: ASNCLP SESSION SET TO SQL REPLICATION; SET RUN SCRIPT NOW STOP ON SQL ERROR ON; SET SERVER MONITOR TO DB mondb; LIST MONITOR SUSPENSION TEMPLATE; LIST MONITOR SUSPENSION; This produces the following output: ==== CMD: LIST MONITOR SUSPENSION TEMPLATE; ==== TEMPLATE NAME START TIME FREQUENCY DURATION UNITS ------------------ ---------- --------- -------- ------- LUNCH 12:00:00 SUNDAY 1.0 HOURS 1 Template(s) found. ==== CMD: LIST MONITOR SUSPENSION; ==== SUSPENSION NAME SERVER NAME TEMPLATE NAME FREQUENCY DURATION ------------------ ------------------ ------------------ --------- S1 TARGET LUNCH SUNDAY 1.0 SUSPENDUNITS FIRST SUSPENSION STOP -------- ------- ------------------- ------------------- HOURS 2007-03-20-12:00:00 2007-12-31-00:00:00 1 Suspension(s) found. We can see the monitor suspension template called LUNCH, which we created and the monitor suspension S1. We can alter a monitor suspension template by using the ASNCLP command ALTER MONITOR SUSPENSION. Suppose we want to change the suspension day from Sunday to Monday, then the ASNCLP command would be: ASNCLP SESSION SET TO SQL REPLICATION; SET RUN SCRIPT NOW STOP ON SQL ERROR ON; SET SERVER MONITOR TO DB mondb; ALTER MONITOR SUSPENSION TEMPLATE lunch; LIST MONITOR SUSPENSION TEMPLATE; To drop a monitor suspension, we would use the DROP MONITOR SUSPENSION ASNCLP command: ASNCLP SESSION SET TO SQL REPLICATION; SET RUN SCRIPT NOW STOP ON SQL ERROR ON; SET SERVER MONITOR TO DB mondb; SET SERVER TARGET TO DB db2b; DROP MONITOR SUSPENSION s1; Dropping a monitor suspension involves running the following SQL: DELETE FROM ASN.IBMSNAP_SUSPENDS WHERE SUSPENSION_NAME = 'S1' To drop a monitor suspension template, we would use the DROP MONITOR SUSPENSION TEMPLATE ASNCLP command: ASNCLP SESSION SET TO SQL REPLICATION; SET RUN SCRIPT NOW STOP ON SQL ERROR ON; SET SERVER MONITOR TO DB mondb; DROP MONITOR SUSPENSION TEMPLATE lunch; Dropping a monitor suspension template involves running the following SQL: DELETE FROM ASN.IBMSNAP_TEMPLATES WHERE TEMPLATE_NAME = 'LUNCH' So let's look at an example in a bidirectional scenario as shown in the following diagram: In this example, we have created four monitors to monitor Q Capture and Q Apply on each of the two servers. The monitor_qual are MONAC1, MONAA1, MONBA1, and MONBC1. The monitor_server is MONDB. If we want to perform maintenance on the DB2B database every Sunday afternoon at 16:00 for one hour, we would create a monitor suspension template as follows: ASNCLP SESSION SET TO SQL REPLICATION; SET RUN SCRIPT NOW STOP ON SQL ERROR ON; SET SERVER MONITOR TO DB mondb; CREATE MONITOR SUSPENSION TEMPLATE tmaintbaft START TIME 16:00:00 REPEATS WEEKLY DAY OF WEEK SUNDAY FOR DURATION 1 HOURS; And then, we would create a monitor suspension as follows: ASNCLP SESSION SET TO SQL REPLICATION; SET RUN SCRIPT NOW STOP ON SQL ERROR ON; SET SERVER MONITOR TO DB mondb; SET SERVER TARGET TO DB db2b; CREATE MONITOR SUSPENSION NAME maintbaft FOR SERVER DB2B STARTING DATE 2007-03-20 USING TEMPLATE tmaintbaft ENDING DATE 2007-12-31; The ibmsnap_alerts table The IBMSNAP_ALERTS table contains a record of all the alerts issued by the Replication Alert Monitor. The table records what alert condition occurred, at which server, and when they were detected. Some common errors in the ALERT_CODE column are: ASN5153W MONITOR "<monitor_qualifier>". The latency exceeds the threshold value for program "<program_name>". The server is "<server_name>". The schema is "<schema>". The latency is "<latency>" seconds. The threshold is "<threshold>" seconds. ASN5157W MONITOR "<monitor_qualifier>". The Q subscription "<subscription_name>" is inactive. The server is "<server_name>". The schema is "<schema>". State information: "<stateinfo>". Summary In this article we described the Replication Alert Monitor and how to monitor the Q replication setup. Further resources on this subject: Lotus Notes Domino 8: Upgrader's Guide [Book] Q Replication Components in IBM Replication Server [Article] IBM WebSphere MQ commands [Article] WebSphere MQ Sample Programs [Article] Q Subscription Maintenance in IBM Infosphere [Article]
Read more
  • 0
  • 0
  • 2278

article-image-welcome-javascript-full-stack
Packt
15 Sep 2015
12 min read
Save for later

Welcome to JavaScript in the full stack

Packt
15 Sep 2015
12 min read
In this article by Mithun Satheesh, the author of the book Web Development with MongoDB and NodeJS, you will not only learn how to use JavaScript to develop a complete single-page web application such as Gmail, but you will also know how to achieve the following projects with JavaScript throughout the remaining part of the book: Completely power the backend using Node.js and Express.js Persist data with a powerful document oriented database such as MongoDB Write dynamic HTML pages using Handlebars.js Deploy your entire project to the cloud using services such as Heroku and AWS With the introduction of Node.js, JavaScript has officially gone in a direction that was never even possible before. Now, you can use JavaScript on the server, and you can also use it to develop full-scale enterprise-level applications. When you combine this with the power of MongoDB and its JSON-powered data, you can work with JavaScript in every layer of your application. (For more resources related to this topic, see here.) A short introduction to Node.js One of the most important things that people get confused about while getting acquainted with Node.js is understanding what exactly it is. Is it a different language altogether or is it just a framework or is it something else? Node.js is definitely not a new language, and it is not just a framework on JavaScript too. It can be considered as a runtime environment for JavaScript built on top of Google's V8 engine. So, it provides us with a context where we can write JS code on any platform and where Node.js can be installed. That is anywhere! Now a bit of history; back in 2009, Ryan Dahl gave a presentation at JSConf that changed JavaScript forever. During his presentation, he introduced Node.js to the JavaScript community, and after a, roughly, 45-minute talk, he concluded it, receiving a standing ovation from the audience in the process. He was inspired to write Node.js after he saw a simple file upload progress bar on Flickr, the image-sharing site. Realizing that the site was going about the whole process the wrong way, he decided that there had to be a better solution. Now let's go through the features of Node.js that make it unique from other server side programming languages. The advantage that the V8 engine brings in The V8 engine was developed by Google and was made open source in 2008. As we all know, JavaScript is an interpreted language and it will not be as efficient as a compiled language as each line of code gets interpreted one by one while the code is executed. The V8 engine brings in an efficient model here where the JavaScript code will be compiled into machine level code and the executions will happen on the compiled code instead of interpreting the JavaScript. But even though Node.js is using V8 engine, Joyent, which is the company that is maintaining Node.js development, does not always update the V8 engine to the latest versions that Google actively releases. Node is single threaded! You might be asking how does a single threaded model help? Typical PHP, ASP.NET, Ruby, or Java based servers follow a model where each client request results in instantiation of a new thread or even a process. When it comes to Node.js, requests are run on the same thread with even shared resources. A common question that we might be asking will be the advantage of using such a model. To understand this, we should understand the problem that Node.js tries to resolve. It tries to do an asynchronous processing on a single thread to provide more performance and scalability for applications, which are supposed to handle too much web traffic. Imagine web applications that handle millions of concurrent requests; the server makes a new thread for handling each request that comes in, it will consume many resources. We would end up trying to add more and more servers to add the scalability of the application. The single threaded asynchronous processing model has its advantage in the previous context and you can get to process much more concurrent requests with a less number of server side resources. But there is a downside to this approach, that Node.js, by default, will not utilize the number of CPU cores available on the server it is running on without using an extra module such as pm2. The point that Node.js is single threaded doesn't mean that Node doesn't use threads internally. It is that the developer and the execution context that his code has exposure to have no control over the threading model internally used by Node.js. If you are new to the concept of threads and processes, we would suggest you to go through some preliminary articles regarding this. There are plenty of YouTube videos as well on the same topic. The following reference could be used as a starting point: http://www.cs.ucsb.edu/~rich/class/cs170/notes/IntroThreads/ Nonblocking asynchronous execution One of the most powerful features of Node is that it is event-driven and asynchronous. So how does an asynchronous model work? Imagine you have a block of code and at some nth line you have an operation, which is time consuming. So what happens to the lines that follow the nth line while this code gets executed? In normal synchronous programming models, the lines, which follow the nth line, will have to wait until the operation at the nth line completes. An asynchronous model handles this case differently. To handle this scenario in an asynchronous approach, we need to segment the code that follows the nth line into two sections. The first section is dependent on the result from the operation at the nth line and the second is independent of the result. We wrap the dependent code in a function with the result of the operation as its parameter and register it as a callback to the operation on its success. So once the operation completes, the callback function will be triggered with its result. And meanwhile, we can continue executing the result-independent lines without waiting for the result. So, in this scenario, the execution is never blocked for a process to complete. It just goes on with callback functions registered on each ones completion. Simply put, you assign a callback function to an operation, and when the Node determines that the completion event has been fired, it will execute your callback function at that moment. We can look at the following example to understand the asynchronous nature in detail: console.log('One'); console.log('Two'); setTimeout(function() { console.log('Three'); }, 2000); console.log('Four'); console.log('Five'); In a typical synchronous programming language, executing the preceding code will yield the following output: One Two ... (2 second delay) ... Three Four Five However, in an asynchronous approach, the following output is seen: One Two Four Five ... (approx. 2 second delay) ... Three The function that actually logs three is known as a callback to the setTimeout function. If you are still interested in learning more about asynchronous models and the callback concept in JavaScript, Mozilla Developer Network (MDN) has many articles, which explain these concepts in detail. Node Package Manager Writing applications with Node is really enjoyable when you realize the sheer wealth of information and tools at your disposal! Using Node's built-in Package Manager (npm), you can literally find tens of thousands of modules that can be installed and used within your application with just a few keystrokes! One of the reasons for the biggest success of Node.js is npm, which is one of the best package managers out there with a very minute learning curve. If this is the first ever package manager that you are being exposed to, then you should consider yourself lucky! On a regular monthly basis, npm handles more than a billion downloads and it has around 1,50,000 packages currently available for you to download. You can view the library of available modules by visiting www.npmjs.com. Downloading and installing any module within your application is as simple as executing the npm install package command. Have you written a module that you want to share with the world? You can package it using npm, and upload it to the public www.npmjs.org registry just as easily! If you are not sure how a module you installed works, the source code is right there in your projects' node_modules folder waiting to be explored! Sharing and reusing JavaScript While you develop web applications, you will always end up doing the validations for your UI both as client and server as the client side validations are required for a better UI experience and server side validations for better security of app. Think about two different languages in action, you will have the same logic implemented in both server and client side. With Node.js, you can think of sharing the common function between server and client reducing the code duplication to a bigger extent. Ever worked on optimizing the load time for client side components of your Single Page Application (SPA) loaded from template engines like underscore? That would end up in you thinking about a way we could share the rendering of templates in both server and client at the same time—some call it hybrid templating. Node.js resolves the context of duplication of client templates better than any other server side technologies just because we can use the same JS templating framework and the templates both at server and client. If you are taking this point lightly, the problem it resolves is not just the issue of reusing validations or templates on server and client. Think about a single page application being built, you will need to implement the subsets of server-side models in the client-side MV* framework also. Now think about the templates, models, and controller subsets being shared on both client and server. We are solving a higher scenario of code redundancy. Isn't it? Not just for building web servers! Node.js is not just to write JavaScript in server side. Yes, we have discussed this point earlier. Node.js sets up the environment for the JavaScript code to work anywhere it can be installed. It can be a powerful solution to create command-line tools as well as full-featured locally run applications that have nothing to do with the Web or a browser. Grunt.js is a great example of a Node-powered command-line tool that many web developers use daily to automate everyday tasks such as build processes, compiling Coffee Script, launching Node servers, running tests, and more. In addition to command-line tools, Node is increasingly popular among the hardware crowd with the Node bots movement. Johnny-Five and Cylon.js are two popular Node libraries that exist to provide a framework to work with robotics. Search YouTube for Node robots and you will see a lot of examples. Also, there is a chance that you might be using a text editor developed on Node.js. Github's open source editor named Atom is one such kind, which is hugely popular. Real-time web with Socket.io One of the important reasons behind the origin of Node.js was to support real time web applications. Node.js has a couple of frameworks built for real-time web applications, which are hugely popular namely socket.io and sock.js. These frameworks make it quite simple to build instant collaboration based applications such as Google Drive and Mozilla's together.js. Before the introduction of WebSockets in the modern browsers, this was achieved via long polling, which was not a great solution for real-time experience. While WebSockets is a feature that is only supported in modern browsers, Socket.io acts as a framework, which also features seamless fallback implementations for legacy browsers. If you need to understand more on the use of web sockets in applictions, here is a good resource on MDN that you can explore: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications Networking and file IO In addition to the powerful nonblocking asynchronous nature of Node, it also has very robust networking and filesystem tools available via its core modules. With Node's networking modules, you can create server and client applications that accept network connections and communicate via streams and pipes. The origin of io.js io.js is nothing but a fork of Node.js that was created to stay updated with the latest development on both V8 and other developments in JS community. Joyent was taking care of the releases in Node.js and the process, which was followed in taking care of the release management of Node.js, lacked an open governance model. It leads to scenarios where the newer developments in V8 as well as the JS community were not incorporated into its releases. For example, if you want to write JavaScript using the latest EcmaScript6 (ES6) features, you will have to run it in the harmony mode. Joyent is surely not to be blamed on this as they were more concerned about stability of Node.js releases than frequent updates in the stack. This led to the io.js fork, which is kept up to date with the latest JavaScript and V8 updates. So it's better to keep your eyes on the releases on both Node and io.js to keep updated with the Node.js world. Summary We discussed the amazing current state of JavaScript and how it can be used to power the full stack of a web application. Not that you needed any convincing in the first place, but I hope you're excited and ready to get started writing web applications using Node.js and MongoDB! Resources for Article: Further resources on this subject: Introduction and Composition [article] Deployment and Maintenance [article] Node.js Fundamentals [article]
Read more
  • 0
  • 0
  • 2278
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-getting-started-facebook-application-development-using-coldfusionrailo
Packt
19 Jun 2010
5 min read
Save for later

Getting Started with Facebook Application Development using ColdFusion/Railo

Packt
19 Jun 2010
5 min read
There are other CFML Facebook articles on the internet such as Ray Camden’s tutorial with ColdFusion 8; however Facebook continues to innovate and change, and a majority of those resources are out of date for Facebook’s 2010 updates. Things such as “profile boxes” are passé, and now you have to work with “Application Tabs.” In addition, I have found that there are some general concepts of how Facebook applications work. These have not been covered well in other resources. Why Facebook? According to statistics, Facebook is the 3rd highest traffic site in the US right now (statistics for the rest of the world weren’t readily available). The nature of Facebook is that people socialize, and look at what other people are doing, which means that if your friends post that they are using certain applications or visiting certain sites, you know about it, and for most of us, that’s a good enough reason to check it out.  Thats what's called Grass roots marketing, and it works. “The average U.S. Internet user spends more time on Facebook than on Google, Yahoo, YouTube, Microsoft, Wikipedia and Amazon combined.” That should tell you something. There is a big market to tap into, and should answer the question—why Facebook. Even if you think Facebook isn't a useful tool for you, you can’t argue with the numbers when it comes to reaching potential customers. Why CFML with Facebook? Hopefully your interest in ColdFusion and/or Railo answers this. Since CFML is such an easy to learn and powerful extensible programming language, it only makes sense that we should be able to build Facebook applications with it. There are always some cautions with making websites talk to each other. Using CFML with Facebook is no different; however most of these have been overcome by people already, and you can easily zip through this by copy/pasting the work of others. The basic framework for my applications is the same, and you can use this as your jumping-off point to work on your own applications. Understanding Data Flow Facebook is rather unique in how it is structured, and understanding this structure is critical to being able to build applications properly. You will save yourself a lot of frustration by reviewing this section before you begin writing code. In most websites or web applications, people type in a web address, and they connect directly to your web server, where your application handles the business logic, database interaction and any other work, and then gives web content back to the requesting user. This is not the case with Facebook. With Facebook applications, users open up their web browsers to a Facebook web address (the “Canvas URL”), Facebook’s servers make a “behind the scenes” request to your web server (the “Callback URL”), your application then responds to Facebook’s request, and then, Facebook does the final markup and sends the web page content back to the user’s browser. If you followed that, you see that users always interact with Facebook, while Facebook’s server is the one that talks to your application. You can also connect back to Facebook via their RESTful API to get information about users, friends, photos, posts and more. So here are two important concepts to understand: Your Facebook application code lives on your web server, separate from Facebook. You will get web requests from Facebook on behalf of Facebook users. Users should always be interacting with Facebook’s web site; They should never go directly to your web server The Canvas URL is a Facebook address, which you will setup in the next section. The Callback URL is the root where you put your application files (*.cfc and *.cfm). It is also where you will put your CSS files, images, and anything else your application needs. The Callback URL can be a directory on any web hosting account, so there is no need to setup a separate web host for your Facebook application. Setting up a new Facebook application Generally speaking, setting up a new Facebook application is pretty easy. There are a few things that can trip you up, and I will highlight them. The first thing to do is log into your Facebook account, and authorize the Facebook Developer application by going to this URL:http://apps.facebook.com/developer/ Once you have authorized this application, you will see a link to create a new application. Create a new application, and give it a name: Fill in the description if you want, give it an icon and logo if you wish. Click on the Canvas menu option. Enter the canvas page url (this becomes the URL on facebook’s site that you and your users will go to – apps.facebook.com/yourapp). Enter the callback URL (the full URL to YOUR web server directory where your CFML code will reside. Very important: Select Render method to be “FBML” (which stands for Facebook Markup Language). The other options you can leave as their default values. When you are done, save your changes. The application summary page will show you some important information, specifically the API Key and Application Secret, which you will need in your application later. Consider using Facebook’s “sandbox” mode which makes your application invisible to the world while you are developing it. Likewise, when you are done with your application, consider using Facebook’s application directory to promote your application.
Read more
  • 0
  • 0
  • 2277

article-image-apache-roller-40-creating-theme
Packt
15 Nov 2010
11 min read
Save for later

Apache Roller 4.0: Creating a Theme

Packt
15 Nov 2010
11 min read
  Apache Roller 4.0 – Beginner's Guide A comprehensive, step-by-step guide on how to set up, customize, and market your blog using Apache Roller   Create, optimize, and maintain your own blog server using Apache Roller Incorporate multimedia content from popular web tools like YouTube, Google Maps, Twitter. and SlideShare in your posts Customize the appearance of your blog with visually appealing, powerful themes and templates Increase your blog's search engine ranking and keep track of visitors using Google Webmaster Tools         Read more about this book       For the following exercise, you'll need to download Chapter 7's support code from the book's website. Extract the chapter07.zip file's contents into a directory in your hard disk. For example, I used Ubuntu Linux in the exercise, created a chapter07 directory inside my Desktop directory, and copied the mytheme directory inside Desktop/chapter07. All the steps in the exercise are based on these assumptions. Creating a directory for your theme Every Roller theme has a directory and some required files such as weblog.vm, _day.vm, and theme.xml. The next exercise will show you how to create a directory for your new theme inside Roller's themes directory, and how to copy these required files from the support files. Time for action – creating a directory for your theme Now, I'll show you all the necessary steps to create your new theme directory inside Roller's themes directory in a Linux Ubuntu system, and then copy all the required files. If you're using Windows or any other flavor of Linux, the procedure is very similar: Go to your Roller themes directory and create a directory named mytheme: Open a terminal window, go to the themes subdirectory inside Desktop/chapter07, and type sudo cp * /usr/local/tomcat/webapps/roller/themes/mytheme to copy all the mytheme files to your Roller installation: In the end, your mytheme directory will have four files, as shown in the following screenshot: Now restart Tomcat and wait until it's running again. Then open your web browser, log into Roller, and go to the Design tab to see the Weblog Theme page: Click on the Shared Theme option and select My First Roller Theme from the drop-down listbox: Click on the Update Theme button to change your current Roller theme, and then click on the See how your blog will look with this theme link: Roller will open a new web browser tab to show you a preview of the new theme you selected: Close the preview tab and leave the Front Page: Weblog Theme page open for the next exercise. What just happened? The mytheme theme has a very basic functionality. That's because the CSS stylesheet (mystylesheet.css) is empty, so I'm going to show you how to add styles to your headings, links, and all the other elements displayed in your weblog. However, first we need to see a quick introduction to the four files that every Roller theme must have in order to run without any trouble: File Definition Tip weblog.vm Describes the main page of your weblog. In this file, you set the structure for your weblog, using macros and elements from Roller and the Velocity template language. _day.vm   Describes how to display one day's worth of entries in your weblog. Here you can configure how to display each entry's title, content, and comments, for example. You can set the font's color and size of each element, based on the CSS stylesheet definitions. mystylesheet.css Stylesheet override file that defines the CSS style code used by your weblog. Here you define all your weblog's styles, such as size and color for headings and fonts used in your posts. theme.xml Theme definition file that describes each file used in your weblog. You need to include some basic data about your theme, the stylesheet file, the weblog and _day templates, and every other file and/or resource used in your weblog. The stylesheet override file The first thing we need to do in order to change your new theme's visual appearance is edit the stylesheet override file: mystylesheet.css. We can do this in two ways: Edit the file directly from the mytheme directory inside Roller's themes directory, or use Roller's Custom Theme feature. If we use the first option, we'll need to restart Tomcat every time we make a modification to mystylesheet.css. On the other hand, if we choose the second option, we can edit the stylesheet inside Roller's admin interface and see how our changes affect our weblog's visual appearance immediately, so I'm going to show you how to use the second option. Time for action – editing the stylesheet override file It's very easy to edit the stylesheet override file for your custom theme inside Roller, and the next exercise will show you how to do it: Go to the Front Page: Weblog Theme tab in your web browser, select the Custom Theme option, click on the I want to copy the templates from an existing theme into my weblog checkbox, and click on the Update Theme button: Roller will show you the following success message: Now click on the Templates link to see a list of the templates you currently have in your custom space: Looking at the template list in the previous screenshot, there are some templates from the other custom theme and we need to remove them now. Click on the Remove link of the custom.css, mytemplate, and _css templates to delete them from your custom space, as we won't need them anymore, and they don't belong to mytheme. After removing all the unneeded files, there should be only two templates in your list: Now click on the Stylesheet link to see and start editing your mystylesheet.css file's code: As you can see, your custom stylesheet is empty. If you click on the Front Page link in Roller's menu bar, you'll see your weblog's current front page: Now click on your web browser's Back button to return to the stylesheet editing page, and add the following code to your custom stylesheet: div.dayTitle { color:brown; font-weight:bold; font-size:90%; text-transform:uppercase; border-bottom:1px dotted #666;}.entryTitle { font-weight: bold;} Your stylesheet should now contain the line beginning with /*, along with the code you've just entered: Click on the Save button to apply the changes to your stylesheet, and then select the Front Page link to see how the code you entered affects your weblog's visual appearance: If you compare the previous screenshot with the one from step 7, you'll see that the code you entered into the override stylesheet changed the way your weblog displays the day and entry titles. Now click on the Back button of your web browser to return to the stylesheet editing page, and add the following lines of code above the lines you entered in step 8: a { text-decoration: none;}a:link { color: blue; font-weight: medium;}a:visited { color: purple; font-weight: medium;}a:hover { text-decoration: underline overline;}body { font-family:"Lucida Grande", lucida, Geneva, Arial, sans-serif; background:#FFFFCC;} Your stylesheet should now look like this: Click on the Save button and then select the Front Page link to see your weblog's front page: Click on the Back button to return to your stylesheet editing page. What just happened? In the previous exercise, you edited your stylesheet override file (mystylesheet.css) to change your weblog's visual appearance. To understand what these code segments do, let's take a look at the _day template's code: <div class="dayBox"> <div class="dayTitle"> $utils.formatDate($day, "EEEE MMM dd, yyyy") </div> #foreach( $entry in $entries ) <div class="entryBox"> <p class="entryTitle">$entry.title</p> <p class="entryContent"> #if($model.permalink) $entry.displayContent #else $entry.displayContent($url.entry($entry.anchor)) #end </p> <p class="entryInfo"> Posted at <a href="$url.entry($entry.anchor)">$utils.formatDate ($entry.pubTime, "hh:mma MMM dd, yyyy")</a> by $entry.creator.userName in <span class="category">$entry.category.name</span> &nbsp;|&nbsp; #if ($utils.isUserAuthorizedToAuthor($entry.website)) <a href="$url.editEntry($entry.anchor)">Edit</a> &nbsp;|&nbsp; #end #if($entry.commentsStillAllowed || $entry.commentCount > 0) #set($link = "$url.comments($entry.anchor)" ) <a href="$link" class="commentsLink">Comments[$entry.commentCount] </a> #end </p> </div> #end</div> The lines in bold are the ones directly involved with the CSS code you entered in the exercise: <div class="dayTitle"> $utils.formatDate($day, "EEEE MMM dd, yyyy")</div> The div element represents a "division" or a section in a web page. The only code inside this division is $utils.formatDate($day, "EEEE MMM dd, yyyy"). This is a property from the $utils object used to show the date and time of each day containing one or more posts in the weblog, in the format specified by the "EEEE MMM dd, yyyy" string. The class="dayTitle" code segment indicates that this division will use the styles defined in the .dayTitle class from the stylesheet: div.dayTitle { color:brown; font-weight:bold; font-size:90%; text-transform:uppercase; border-bottom:1px dotted #666;} This CSS code indicates that every text element inside this division will be shown in brown color, in bold style, with a smaller size (90%) than the other fonts outside the division, and the text will be converted to uppercase. The last CSS element indicates that there will be a one pixel-wide, dotted grey border at the bottom of each text element (#666 is a hexadecimal color code). All this stuff means that each day in the weblog will be shown like this: Now, the next line in the _day template: <p class="entryTitle">$entry.title</p> The <p> HTML tag indicates a paragraph inside your web page, and $entry.title is the only code inside this paragraph. As we saw before, $entry.title shows the title of an entry in your weblog. The class="entryTitle" element is related to the .entryTitle code block in your stylesheet: .entryTitle { font-weight: bold;} This CSS code indicates that all the text inside the paragraph will be shown in bold. In this case, each entry's title of your weblog will be shown in bold: The rest of the bold lines in the _day template use an <a> element, known as an anchor in HTML. This element is used to display links in web pages, and is related to all the a elements in the stylesheet: a { text-decoration: none;}a:link { color: blue; font-weight: medium;}a:visited { color: purple; font-weight: medium;}a:hover { text-decoration: underline overline;} These elements define how the links in your weblog will be displayed. The first block of code indicates that the links won't have a text decoration (that is, links won't be underlined, as in most web pages), the color of each link will be blue, the font weight will be medium, and the color of visited links will be purple. The last block of code indicates that, if someone positions the mouse cursor over a link, it will be underlined and overlined. The following screenshot shows what happens when you put your mouse cursor over the date and time hyperlink created with the <a href="$url.entry($entry.anchor)">$utils.formatDate($entry.pubTime, "hh:mma MMM dd, yyyy")</a> line in the _day template: You can see the underline and overline effects from the a:hover CSS element, along with the purple color due to the a:visited CSS element. The <a href="$url.editEntry($entry.anchor)">Edit</a>  |  line from the _day template has similar effects: The last block of code we used in the previous exercise is: body { font-family:"Lucida Grande", lucida, Geneva, Arial, sans-serif; background:#FFFFCC;} In this case, the body CSS element defines the font used to display your weblog's data. There are several fonts included, to maximize browser compatibility. You can experiment with different fonts and font families to see how your changes affect your weblog's way of displaying data. Summary In this article we saw how to create a Roller theme from scratch. We also saw how to edit the mystylesheet.css stylesheet override file and how the _day.vm template uses CSS styles and Velocity code to display your weblog's data.
Read more
  • 0
  • 0
  • 2276

article-image-magento-14-theming-making-our-theme-shine
Packt
23 Aug 2011
8 min read
Save for later

Magento 1.4 Theming: Making Our Theme Shine

Packt
23 Aug 2011
8 min read
  Magento 1.4 Theming Cookbook Over 40 recipes to create a fully functional, feature rich, customized Magento theme         Read more about this book       (For more resources on this subject, see here.) Looks quite interesting, doesn't it? Let's get started! Introduction You will find all the necessary code in the code bundle; however, some JavaScript libraries won't be included. Don't worry, they are very easy to find and download! Using Cufón to include any font we like in our theme This technique, which allows us to use any font we like in our site, is quite common these days, and is very, very useful. Years ago, if we wanted to include some uncommon font in our design, we could only do it by using a substitutive image. Nowadays, we have many options, such as some PHP extensions, @font-face, Flash (sIFR), and, of course, Cufón. And that last option is the one we are about to use. Getting ready If you would like to copy the code, instead of writing it, remember you can find all the necessary code in the code bundle in Chapter 5, recipe 1. How to do it... Ready to start this first recipe? Let's go: First we have to decide which font to use; this is totally up to you. In this example I'm going to use this one: http://www.dafont.com/aldo.font. It's a free font, and looks very good! Thanks to Sacha Rein. Just download it or find any other font of your liking. Now we need to use the Cufón generator in order to create the font package. We will go to this URL: http://cufon.shoqolate.com/generate/. There we will be able to see something similar to the following screenshot: On that screen we only have to follow all the instructions and click on the Let's do this button: This will create a file called Aldo_600.font.js, which will be the one we will be using in this example. But we also need something more, the Cufón library. Download it by clicking the Download button: After downloading the Cufón library, we will download a file called cufon-yui.js. We now have all the necessary tools. It's time to make use of them. First place cufon-yui.js and Aldo_600.font.js inside skin/frontend/default/rafael/js. Now we need to edit our layout file. Let's open: app/design/frontend/default/rafael/layout/page.xml. Once we have this file opened we are going to look for this piece of code: <action method="addCss"><stylesheet>css/960_24_col.css</stylesheet></action> <action method="addCss"><stylesheet>css/styles.css</stylesheet></action> And just below it we are going to add the following: <action method="addJs"><script>../skin/frontend/default/rafael/js/cufon-yui.js</script></action> <action method="addJs"><script>../skin/frontend/default/rafael/js/Aldo_600.font.js</script></action> See, we are adding our two JavaScript files. The path is relative to Magento's root JavaScript folder. With this done, our theme will load these two JS files. Now we are going to make use of them. Just open app/design/frontend/default/rafael/template/page/2columns-right.phtml. At the bottom of this file we are going to add the following code: <script type="text/javascript"> Cufon.replace('h1'); </script></body></html> And that's all we need. Check the difference! Before we had something like the following: And now we have this: Every h1 tag of our site will now use our Aldo font, or any other font of your liking. The possibilities are endless! How it works... This recipe was quite easy, but full of possibilities. We first downloaded the necessary JavaScript files, and then made use of them with Magento's add JS layout tag. Later we were able to use the libraries in our template as in any other HTML file. SlideDeck content slider Sometimes our home page is crowded with info, and we still need to place more and more things. A great way of doing so is using sliders. And the SlideDeck one offers a very configurable one. In this recipe we are going to see how to add it to our Magento theme. You shouldn't miss this recipe! How to do it... Making use of the slider in our theme is quite simple, let's see: First we need to go to http://www.slidedeck.com/ and download SlideDeck Lite, as we will be using the Lite version in this recipe. Once downloaded we will end up with a file called slidedeck-1.2.1-litewordpress-1.3.6.zip. Unzip it. Go to skin/frontend/default/rafael/css and place the following files in it: slidedeck.skin.css slidedeck.skin.ie.css back.png corner.png slides.png spines.png Next, place the following files in skin/frontend/default/rafael/js: jquery-1.3.2.min.js slidedeck.jquery.lite.pack.js Good, now everything is in place. Next, open: app/design/frontend/default/rafael/layout/page.xml. Now look for the following piece of code: <block type="page/html_head" name="head" as="head"> <action method="addJs"><script>prototype/prototype.js</script></action> <action method="addJs" ifconfig="dev/js/deprecation"><script>prototype/deprecation.js</script></action> <action method="addJs"><script>lib/ccard.js</script></action> Place the jQuery load tag just before the prototype one, so we have no conflict between libraries: <block type="page/html_head" name="head" as="head"> <action method="addJs"><script>../skin/frontend/default/rafael/js/jquery-1.3.2.min.js</script></action> <action method="addJs"><script>prototype/prototype.js</script></action> <action method="addJs" ifconfig="dev/js/deprecation"><script>prototype/deprecation.js</script></action> Also add the following code before the closing of the block: <action method="addCss"><stylesheet>css/slidedeck.skin.css</stylesheet></action><action method="addCss"><stylesheet>css/slidedeck.skin.ie.css</stylesheet></action><action method="addJs"><script>../skin/frontend/default/rafael/js/slidedeck.jquery.lite.pack.js</script></action> The following steps require us to log in to the administrator panel. Just go to: http://127.0.0.1/magento/index.php/admin. Now to CMS/Pages, open the home page one: Once inside, go to the Content tab. Click on Show/Hide editor. Find the following code: <div class="grid_18"> <a href="#"><img src="{{skin url='img_products/big_banner.jpg'}}" alt="Big banner" title="Big banner" /></a> </div><!-- Big banner → And replace it with the following: <div class="grid_18"> <style type="text/css"> #slidedeck_frame { width: 610px; height: 300px; } </style> <div id="slidedeck_frame" class="skin-slidedeck"> <dl class="slidedeck"> <dt>Slide 1</dt> <dd>Sample slide content</dd> <dt>Slide 2</dt> <dd>Sample slide content</dd> </dl> </div> <script type="text/javascript"> jQuery(document).ready(function($) { $('.slidedeck').slidedeck(); }); </script> <!-- Help support SlideDeck! Place this noscript tag onyour page when you deploy a SlideDeck to provide a link back! --> <noscript> <p>Powered By <a href="http://www.slidedeck.com"title="Visit SlideDeck.com">SlideDeck</a></p> </noscript></div><!-- Big banner → Save the page and reload the frontend. Our front page should have a slider just like the one seen in the following screenshot: And we are done! Remember you can place any content you want inside these tags: <dl class="slidedeck"> <dt>Slide 1</dt> <dd>Sample slide content</dd> <dt>Slide 2</dt> <dd>Sample slide content</dd> </dl> How it works... This recipe is also quite easy. We only need to load the necessary JavaScript files and edit the content of the home page, in order to add the necessary code.
Read more
  • 0
  • 0
  • 2274

article-image-digging-architecture
Packt
30 Jul 2013
31 min read
Save for later

Digging into the Architecture

Packt
30 Jul 2013
31 min read
(For more resources related to this topic, see here.) The big picture A very short description of a WaveMaker application could be: a Spring MVC server running in a Java container, such as Tomcat, serving file and JSON requests for a Dojo Toolkit-based JavaScript browser client. Unfortunately, such "elevator" descriptions can create more questions than they answer. For starters, although we will often refer to it as "the server," the WaveMaker server might be more aptly called an application server in most architectures. Sure, it is possible to have a useful application without additional servers or services beyond the WaveMaker server, but this is not typical. We could have a rich user interface to read against some in memory data set, for example. Far more commonly, the Java services running in the WaveMaker server are calling off to other servers or services, such as relational databases and RESTful web services. This means the WaveMaker server is often the middle or application tier server of a multi-tier application's architecture. Yet at the same time, the WaveMaker server can be eliminated completely. Applications can be packaged for uploading to PhoneGap build, http://build.phonegap.com/,directly from WaveMaker Studio. Both PhoneGap and the associated Apache project Cordova, http://cordova.apache.org,provide APIs to enable JavaScript to access native device functionality, such as capturing images with the camera and obtaining GPS location information. Packaged up and installed as a native application, the JavaScript files are loaded from the devices, file system instead of being downloaded from a server via HTTP. This means there is no origin domain to be constrained by. If the application only uses web services, or otherwise doesn't need additional services, such as database access, the WaveMaker server is neither used nor needed. Just because an application isn't installed on a mobile device from an app store doesn't mean we can't run it on a mobile device. Browsers on mobile devices are more capable than ever before. This means our client could be any device with a modern browser. You must also consider licensing in light of the bigger picture. WaveMaker, WaveMaker Studio, and the applications create with the Studio are released under the Apache 2.0 license, http://www.apache.org/licenses/LICENSE-2.0. The WaveMaker project was first released by WaveMaker Software in 2007. In March 2011, VMware (http://vmware.com) acquired the WaveMaker project. It was under VMware that WaveMaker 6.5 was released. In April 2013, Pramati Technlogies (http://pramati.com) acquired the assets of WaveMaker for its CloudJee (http://cloudjee.com) platform. WaveMaker continues to be developed and released by Pramati Technologies. Now that we understand where our client and server sit in the larger world, we will be primarily focused within and between those two parts. The overall picture of the client and server looks as shown in the following diagram: We will examine each piece of this diagram in detail during the course of this book. We shall start with the JavaScript client. Getting comfortable with the JavaScript client The client is a JavaScript client that runs in a modern browser. This means that most of the client, the HTML and DOM nodes that the browser interfaces with specifically, are created by JavaScript at runtime. The application is styled using CSS, and we can use HTML in our applications. However, we don't use HTML to define buttons and forms. Instead, we define components, such as widgets, and set their properties. These component class names and properties are used as arguments to functions that create DOM nodes for us. Dojo Toolkit To do this, WaveMaker uses the Dojo Toolkit, http://dojotoolkit.org/. Dojo, as it is generally referred to, is a modular, cross-browser, JavaScript framework with three sections. Dojo Core provides the base toolkit. On top of which are Dojo's visual widgets called Dijits. Finally, DojoX contains additional extensions such as charts and a color picker. DojoCampus' Dojo Explorer, http://dojocampus.com/explorer/, has a good selection of single unit demos across the toolkit, many with source code. Dojo allows developers to define widgets using HTML or JavaScript. WaveMaker users will better recognize the JavaScript approach. Specifically, WaveMaker 6.5.X uses version 1.6.1 of Dojo. Of the browsers supported by Dojo 1.6.1, http://dojotoolkit.org/reference-guide/1.8/releasenotes/1.6.html, Opera's "Dojo Core only" support prevents it from being supported by WaveMaker. This could change with Opera's move to WebKit. Building on top of the Dojo Toolkit, WaveMaker provides its own collections of widgets and underlying components. Although both can be called components, the name component is generally used for the non-visible parts, such as service calls to the server and the event notification system. Widgets, such as the Dijits, are visible components such as buttons and editors. Many, but not all, of the WaveMaker widgets extend functionality from Dojo widgets. When they do extend Dijits, WaveMaker widgets often add numerous functions and behaviors that are not part of Dojo. Examples include controlling the read-only state, formatting display values for currency, and merging components, such as buttons with icons in them. Combined with the WaveMaker runtime layers, these enhancements make it easy to assemble rich clients using only properties. WaveMaker's select editor (wm.SelectMenu) for example extends the Dojo Toolkit ComboBox (dijit.form.ComboBox) or the FilteringSelect (dijit.form.FilteringSelect) as needed. By default, a select menu has Dojo FilteringSelect as its editor, but it will use ComboBox instead if the user is on a mobile device or the developer has cleared the RestrictValues property tick box. A required select menu editor Let's consider the case of disabling a submit button when the user has not made a required list selection. In Dojo, this is done using JavaScript code, and for an experienced Dojo developer, this is not difficult. For those who may primarily consider Dojo a martial arts Studio however, it is likely another matter altogether. Using the WaveMaker framework provided widgets, no code is required to set up this inter-connection. This is simply a matter of visually linking or binding the button's disabled property to the lists' emptySelection property in the graphical binding dialog. Now the button will be disabled if the user has not made a selection in the grid's list of items. Logically, we can think of this as setting the disabled property to the value of the grid's emptySelection property, where emptySelection is true unless and until a row has been selected. Where WaveMaker most notably varies from the Dojo way of things is the layout engine. WaveMaker handles the layout of container widgets using its own engine. Containers are those widgets that contain other widgets, such as panels, tabs, and dialogs. This makes it easier for developers to arrange widgets in WaveMaker Studio. A result of this is that border, padding, and margin are set using properties on widgets, not by CSS. Border, padding, and margin are widget properties in WaveMaker, and are not controlled by CSS. Dojo made easy Having the Dojo framework available to us makes web development easier both when using the WaveMaker framework and when doing custom work. Dojo's modular and object-oriented functions, such as dojo.declare and dojo.inherited, for example, simplify creating custom components. The key takeaway here is that Dojo itself is available to you as a developer if you wish to use it directly. Many developers never need to utilize this capability, but it is available to you if you ever do wish to take advantage of it. Running the CRM Simple sample again from either the console in the browser development tools or custom project page code, we could use Dojo's byId() function to get a div, for example, the main title label: >dojo.byId("main_labelTitle"). In practice, the WaveMaker style of getting a DOM node via the component name, for example, main.labelTitle.domNode, is more practical and returns the same result. If a function or ability in Dojo is useful, the WaveMaker framework usually provides a wrapper of some sort for you. Just as often, the WaveMaker version is friendlier or otherwise easier to use in some way. For example, this.connect(), WaveMaker's version of dojo.connect(), tracks connections for you. This avoids the need for you to remember to call disconnect() to remove the reference added by every call to connect(). For more information about using Dojo functions in WaveMaker, see the Dojo framework page in the WaveMaker documentation at: http://dev.wavemaker.com/wiki/bin/wmdoc_6.5/Dojo+Framework. Binding and events Two solid examples of WaveMaker taking a powerful feature of Dojo and providing friendlier versions are topic notifications and event handling. Dojo.connect() enables you to register a method to be called when something happens. In other words: "when X happens, please also do Y". Studio provides visual tooling for this in the events section of a component's properties. Buttons have an event drop-down menu for their click event. Asynchronous server call components, live variables, and service variables, have tooled events for reviewing data just before the call is made and for the successful, and not so successful, returns from the call. These menus are populated with listings of likely components and if appropriate, functions. Invoking other service calls, particularly when a server call depends on data from the results of some previous server call, and navigation calls to other layers and pages within the application are easy examples of how WaveMaker's visual tooling of dojo.connect simplifies web development. WaveMaker's binding dialog is a graphical interface on the topic subscription system. Here we are "binding" a live variable that returns rows from the lineitem table to be filtered by the data value of the orderid editor in the form on the new order page: The result of this binding is that when the value of the orderid editor changes, the value in the filter parameter of this live variable will be updated. An event indicating that the value of this orderid editor has changed is published when the data value changes. This live variable's filter is being subscribed to that topic and can now update its value accordingly. Loading the client Web applications start from index.html, and a WaveMaker application is no different. If we examine index.html of a WaveMaker application, we see the total content is less than 100 lines. We have some meta tags in the head, mostly for Internet Explorer (MSIE) and iOS support. In the body, there are more entries to help out with older versions of MSIE, including script tags to use Chrome Frame if we so choose. If we cut all that away, index.html is rather simple. In the head, we load the CSS containing the projects theme and define a few lines of style classes for wavemakerNode and _wm_loading: <script>var wmThemeUrl = "/wavemaker/lib/wm/base/widget/themes/wm_default/theme.css";</script> <style type="text/css"> #wavemakerNode { height: 100%; overflow: hidden; position: relative; } #_wm_loading { text-align: center; margin: 25% 0px 25% 0px; } </style> Next we load the file config.js, which as its name suggests, is about configuration. The following line of code is used to load the file: <script type="text/javascript" src = "config.js"></script> Config.js defines the various settings, variables, and helper functions needed to initialize the application, such as the locale setting. Moving into the body tag of index.html, we find a div named wavemakerNode: <div id="wavemakerNode"> The next div tag is the loader gif, which is given in the following code: <div id="_wm_loading" style="z-index: 100;"> <table style='width:100%;height: 100%;'><tr><td align='center'><img alt="Loading" src = "/wavemaker/lib/boot/images/loader.gif" />&nbsp;&nbsp;Loading...</td></tr></table> </div> This is the standard spinner shown while the application is loading. With the loader gif now spinning, we begin the real work with runtimeLoader.js, as given in the following line of code: <script type="text/javascript" src = "/wavemaker/lib/runtimeLoader.js"></script> When running a project from Studio, the client runtime is loaded from Studio via WaveMaker. Config.js and index.html are modified for deployment while the client runtime is copied into the applications webapproot. runtimeLoader, as its name suggests, loads the WaveMaker runtime. With the runtime loaded, we can now load the top level project.a.js file, which defines our application using the dojo.declare() method. The following line of code loads the file: <script type="text/javascript" src = "project.a.js"></script> Finally, with our application class defined, we set up an instance of our application in wavemakerNode and run it. There are two modes for loading a WaveMaker application: debug and gzip mode. The debug mode is useful for debugging, as you would expect. The gzip mode is the default mode. The test mode of the Run , Test , or Compile button in Studio re-deploys the active project and opens it in debug mode. This is the only difference between using Test and Run in Studio. The Test button adds ?debug to the URL of the browser window; the Run button does not. Any WaveMaker application can be loaded in debug mode by adding debug to the URL parameters. For example, to load the CRM Simple application from with WaveMaker in debug mode, use the URL http://crm_simple.localhost:8094.com/?debug; detecting debug in the URL sets the djConfig.debugBoot flag, which alters the path used in runtimeLoader. djConfig.debugBoot = location.search.indexOf("debug") >=0; Like a compiled program, debug mode preserves variable names and all the other details that optimization removes which we would want available to use when debugging. However, JavaScript is not compiled into byte code or machine specific instructions. On the other hand, in gzip mode, the browser loads a few optimized packages containing all the source code in merged files. This reduces the number of files needed to load our application, which significantly improves loading time. These optimized packages are also minified. Minification removes whitespace and replaces variable names with short names, further reducing the volume of code to be parsed by the browser, and therefore further improving performance. The result is a significant reduction in the number of requests needed and the number of bytes transferred to load an application. A stock application in gzip mode requires 22 to 24 requests to load some 300 KB to 400 KB of content, depending on the application. In debug mode, the same app transfers over 1.5 MB in more than 500 requests. The index.html file, and when security is enabled, login.html, are yours to edit. If you are comfortable doing so, you can customize these files such as adding additional script tags. In practice, you shouldn't need to customize index.html, as you have full control of the application loaded into the wavemakerNode. Also, upgraded scripts in future versions of WaveMaker may need to programmatically update index.html and login.html. Changes to the X-US-Compatible meta tag are often required when support for newer versions of Internet Explorer becomes available, for example. These scripts can't possibly know about every customization you may make. Customization of index.html may cause these scripts to fail, and may require you to manually update these files. If you do encounter such a situation, simply use the index.html file from a project newly created in the new version as a template. Springing into the server side The WaveMaker server is a Java application running in a Java Virtual Machine (JVM). Like the client, it builds upon proven frameworks and libraries. In the case of the server, the foundational block is the SpringSource framework, http://www.springsource.org/SpringSource, or the Spring framework. The Spring framework is the most popular enterprise Java development framework today, and for good reason. The server of a WaveMaker application is a Spring application that includes the WaveMaker common, json, and runtime modules. More specifically, the WaveMaker server uses the Spring Web MVC framework to create a DispatcherServlet that delegates client requests to their handlers. WaveMaker uses only a handful of controllers, as we will see in the next section. The effective result is that it is the request URL that is used to direct a service call to the correct service. The method value of the request is the name of the client exposed function with the service to be called. In the case of overloaded functions, the signature of the params value is used to find the method matching by signature. We will look at example requests and responses shortly. Behind this controller is not only the power of the Spring framework, but also a number of leading frameworks such as Hibernate and, JaxWS, and libraries such as log4j and Apache commons. Here too, these libraries are available to you both directly in any custom work you might do and indirectly as tooled features of Studio. As we are working with a Spring server, we will be seeing Spring beans often as we examine the server-side configuration. One need not be familiar with Spring to reap its benefits when using custom Java in WaveMaker. Spring makes it easy to get access to other beans from our Java code. For example, if our project has imported a database as MyDB, we could get access to the service and any exposed functions in that service using getServiceBean().The following code illustrates the use of getServiceBean(): MyDB myDbSvc = (MyDB)RuntimeAccess.getInstance().getServiceBean("mydb"); We start by getting an instance of the WaveMaker runtime. From the returned runtime instance, we can use the getServiceBean() method to get a service bean for our mydb database service. There are other ways we could have got access to the service from our Java code; this one is pretty straightforward.  Starting from web.xml Just as the client side starts with index.html, a Java servlet starts in WEB-INF with web.xml. A WaveMaker application web.xml is a rather straightforward Spring MVC web.xml. You'll notice many servlet-mappings, a few listeners, and filters. Unlike index.html, web.xml is managed directly by Studio. If you need to add elements to the web-app context, add them to user-web.xml. The content of user-web.xml is merged into web.xml when generating the deployment package.  The most interesting entry is probably contextConfigLocation of /WEB-INF/project-springapp.xml. Project-springapp.xml is a Spring beans file. Immediately after the schema declaration is a series of resource imports. These imports include the services and entities that we create in Studio as we import databases and otherwise add services to our project. If you open project-spring.xml in WEB-INF, near the top of the file you'll see a comment noting how project-spring.xml is yours to edit. For experienced Spring users, here is the entry point to add any additional imports you may need. An example of such can be found at http://dev.wavemaker.com/wiki/bin/Spring. In that example, an additional XML file, ServerFileProcessor.xml, is used to enable component scanning on a package and sets some properties on those components. Project-spring.xml is then used to import ServerFileProcessor.xml into the application context. Many users of WaveMaker still think of Spring as the season between Winter and Summer. Such users do not need to think about these XML files. However, for those who are experienced with Java, the full power of the Spring framework is accessible to them. Also in project-springapp.xml is a list of URL mappings. These mappings specific request URLs that require handling by the file controller. Gzipped resources, for example, require the header Content-Encoding to be set to gzip. This informs the browser the content is gzip encoded and must be uncompressed before being parsed. >There are a few names that use ag in the server. WaveMaker Software the company was formerly known as ActiveGrid, and had a previous web development tool by the same name. The use of ag and com.activegrid stems back to the project's roots, first put down when the company was still known as ActiveGrid. Closing out web.xml is the Acegi filter mapping. Acegi is the security module used in WaveMaker 6.5 . Even when security is not enabled in an application, the Acegi filter mapping is included in web.xml. When security is not enabled in the project, an empty project-security.xml is used. Client and server communication Now that we've examined the client and server, we need to better understand the communication between the two. WaveMaker almost exclusively uses the HTTP methods GET and POST. In HTTP, GET is used, as you might suspect even without ever having heard of RFC 2626 (https://tools.ietf.org/html/rfc2616), to request, or get, a specific resource. Unless installed as a native application on a mobile device, a WaveMaker web application is loaded via a GET method. From index.html and runtimeLoad.js to the user defined pages and any images used on those images, the applications themselves are loaded into the browser using GET. All service calls, database reads and writes, or otherwise any invocations of a Java service functions, on the other hand, are POST. The URL of these POST functions is always the service named .json. For example, calls to a Java service named userPrefSvc would always be to the URL /userPrefSvc.json. Inside the POST method's request payload will be any required parameters including the method of the service to be invoked. The response will be the response returned from that call. PUT methods are not possible because we cannot nor do not want to know all possible WaveMaker server calls at "designtime", while the project files are open for writing in the Studio. This pattern avoids any URL length constraints, enabling lengthy datasets to be transferred while freeing up the URL to pass parameters such as page state. Let's take a look at an example. If you want to follow along in your browser's console, this is the third request of three when we select "Fog City Books" in the CRM Simple application when running the application with the console open. The following URL is the request URL: http://crm_simple.localhost:8094/services/runtimeService.json The following is request payload: {"params":["custpurchaseDB","com.custpurchasedb.data.Lineitem",null,{"properties":["id","item"],"filters":["id.orderid=9"],"matchMode":"start","ignoreCase":false},{"maxResults":500,"firstResult":0}],"method":"read","id":251422} The response is as follows: {"dataSetSize":2,"result":[{"id":{"itemid":2,"orderid":9},"item":{"itemid":2,"itemname":"Kidnapped","price":12.99},"quantity":2},{"id":{"itemid":10,"orderid":9},"item":{"itemid":10,"itemname":"Gravitys Rainbow","price":11.99},"quantity":1}]} As we expect, the request URL is to a service (in this case named runtime service), with the .json extension. Runtime service is the built-in WaveMaker service for reading and writing with the Hibernate (http://www.hibernate.org), data models generated by importing a database. Security service and WaveMaker service are the other built-in services used at runtime. The security service is used for security functions such as getUserName() and logout(). Note this does not include login, which is handled by Acegi. The WaveMaker service has functions such as getServerTimeOffset(), used to adjust for time zones, and remoteRESTCall(), used to proxy some web service calls. How the runtime service functions is easy to understand by observation. Inside the request payload we have, as the URL suggested, a JavaScript Object Notation (JSON) structure. JSON (http://www.json.org/), is a lightweight data-interchange format regularly used in AJAX applications. Dissecting our example request from the top of the structure enclosed in the outer-most {}'s looks like the following: {"params":[…….],"method":"read","id":251422} We have three top level name-value pairs to our request object: params, method, and id. The id is 251422; method is read and the params value is an array, as indicated by the [] brackets: ["custpurchaseDB","com.custpurchasedb.data.Lineitem",null,{},{ }] In our case, we have an array of five values. The first is the database service name, custpurchaseDB. Next we have what appears to be the package and class name we will be reading from, not unlike from in a SQL query. After which, we have a null and two objects. JSON is friendly to human reading, and we could continue to unwrap the two objects in this request in a similar fashion.  when we discuss database services and check out the response. At the top level, we have dataSetSize, the number of results, and the array of the results: {"dataSetSize":2,"result":[]} Inside our result array we have two objects: [{"id":{"itemid":2,"orderid":9},"item":{"itemid":2,"itemname":"Kidnapped","price":12.99},"quantity":2},{"id":{"itemid":10,"orderid":9},"item":{"itemid":10,"itemname":"Gravitys Rainbow","price":11.99},"quantity":1}]} Our first item has the compound key of itemid 2 with orderid 9. This is the item Kidnapped, which is a book costing $11.99. The other object in our result array also has the orderid 9, as we expect when reading line items from the selected order. This one is also a book, the item Gravity's Rainbow. Types To be more precise about the com.custpurchasdb.data.Lineitem parameter in our read request, it is actually the type name of the read request. WaveMaker projects define types from primitive types such as Boolean and custom complex types such as Lineitem. In our runtime read example, com.custpurchasedb.data.Lineitem is both the package and class name of the imported Hibernate entity and the type name for the line item entity in the project. Maintaining type information enables WaveMaker to ease a number of development issues. As the client knows the structure of the data it is getting from the server, it knows how to display that data with minimal developer configuration, if any. At design time, Studio uses type information in many areas to help us correctly configure our application. For example, when we set up a grid, type information enables Studio to present us with a list of possible column choices for the grid's dataset type. Likewise, when we add a form to the canvas for a database insert, it is type information that Studio uses to fill the form with appropriate editors. Line item is a project-wide type as it is defined in the server side. In the process of compiling the project's Java services sources, WaveMaker defines system types for any type returned to the client in a client facing function. To be added to the type system, a class must: Be public Define public getters and setters Be returned by a client exposed function Have a service class that extends JavaServiceSuperClass or uses the @ExposeToClient annotation WaveMaker 6.5.1 has a bug that prevents types from being generated as expected. Be certain to use 6.5.2 or newer versions to avoid this defect. It is possible to create new project types by adding a Java service class to the project that only defines types. Following is an example that creates a new simple type called Record to the project. Our definition of Record consists of an integer ID and a string. Note that there are two classes here. MyCustomTypes is the service class containing a method returning the type Record. As we will not be calling it, the function getNewRecord() need not do anything other than return a record. Creating a new default instance is an easy way to do this. The class Record is defined as an inner class. An inner class is a class defined within another class. In our case, Record is defined within MyCustomTypes: // Java Service class MyCustomTypes package com.myco.types; import com.wavemaker.runtime.javaservice.JavaServiceSuperClass; import com.wavemaker.runtime.service.annotations.ExposeToClient; public class MyCustomTypes extends JavaServiceSuperClass { public Record getNewRecord(){ return new Record(); } // Inner class Record public class Record{ private int id; private String name; public int getId(){ return id; } public void setId(int id){ this.id = id; } public String getName(){ return this.name; } public void setName(String name){ this.name = name; } } }  To add the preceding code to our WaveMaker project, we would add a Java service to the project using the class name MyCustomTypes in the Package and Class Name editor of the New Java Service dialog. The preceding code extends JavaServiceSuperClass and uses the package com.myco.types. A project can also have client-only types using the type definition option from the advanced section of the Studio insert menu. Type definitions are useful when we want to be able to pass structured data around within the client but we will not be sending or receiving that type to the server. For example, we may want to have application scoped wm.Variable storing a collection of current record selection information. This would enable us to keep track of a number of state items across all pages. Communication with the server is likely to be using only a few of those types at a time, so no such structure exists in the server side. Using wm.Variable enables us to bind each Record ID without using code. The insert type definition menu brings up the Type Definition Generator dialog. The generator takes JSON input and is pre-populated with a sample type. The sample type defines a person object, albeit an unusual one, with a name, an array of numbers for age, a Boolean (hasFoot), and a related person object, friend. Replace the sample type with your own JSON structure. Be certain to change the type name to something meaningful. After generating the type, you'll immediately see the newly minted type in type selectors, such as the type field of wm.Variable. Studio is pretty good at recognizing type changes. If for some reason Studio does not recognize a type change, the easiest thing to do is to get Studio to re-read the owning object. If a wm.Variable fails to show a newly added field to a type in its properties, change the type of the variable from the modified type to some other type and then back again. Studio is also an application One of the more complex WaveMaker applications is the Studio. That's right, Studio is itself an application built out of WaveMaker widgets and using the runtime and server. Being the large, complex application we use to build applications, it can sometimes be difficult to understand where the runtime ends and Studio begins. With that said, Studio remains a treasure trove of examples and ideas to explore. Let's open a finder, explorer, shell, or however you prefer to view the file system of a WaveMaker Studio installation. Let's look in the studio folder. If you've installed WaveMaker to c:program filesWaveMaker6.5.3.Release, the default on Windows, we're looking at c:program filesWaveMaker6.5.3.Releasestudio. This is the webapproot of the Studio project: For files, we've discussed index.html in loading the client. The type definition for the project types is types.js. The types.js definition is how the client learns of the server's Java types. Moving on to the directories alphabetically, we start with the app folder. The app folder can be considered a large utility folder these days. The branding folder, http://dev.wavemaker.com/wiki/bin/wmdoc_6.5/Branding, is a sample of the branding feature for when you want to easily re-brand applications for different customers. The build folder contains the optimized build files we discussed when loading our application in gzip mode. This build folder is for the Studio itself. The images folder is, as we would hope, where images are kept. The content of the doc in jsdoc is pretty old. Use jsref at the online wiki, http://dev.wavemaker.com/wiki/bin/wmjsref_6.5/WebHome, for a client API reference instead. Language contains the National Language Support (NLS) files to localize Studio into other languages. In 6.5.X, there is a Japanese (ja) and Spanish (es) directory in addition to the English (en) default thanks to the efforts of the WaveMaker community and a corporate partner. For more on internationalization applications with WaveMaker, navigate to http://dev.wavemaker.com/wiki/bin/wmdoc_6.5/Localization#HLocalizingtheClientLanguage. The lib folder is very interesting, so let's wrap up this top level before we dig into that one. The META-INF folder contains artifacts from the WaveMaker Maven build process that probably should be removed for 6.5.2. The pages folder contains the page definitions for Studio's pages. These pages can be opened in Studio. They also can be a treasure trove of tips and tricks if you see something when using Studio that you don't know how to do in your application. Be careful however, as some pages are old and use outdated classes or techniques. Other constructs are only used by Studio and aren't tooled. This means some pages use components that can only be created by code. The other major difference between a project's pages folder is that Studio page folders do not contain the same number of files. They do not have the optimized pageName.a.js file, for example. The services folder contains the Service Method Definition (SMD) files for Studio's services. These are summaries of a projects exposed services, one file per service, used at runtime by the client. Each callable function, its input parameter, and its return types are defined. Finally, WEB-INF we have discussed already when we examined web.xml. In Studio's case, replace project with studio in the file names. Also under WEB-INF, we have classes and lib. The classes folder contains Java class files and additional XML files. These files are on the classpath. WEB-INFlib contains JAR files. Studio requires significantly more JAR files, which are automatically added to projects created by Studio. Now let's get back to the lib folder. Astute readers of our walk through of index.html likely noticed the references to /wavemaker/lib in src tags for things such as runtimeloader. You might have also noticed that this folder was not present in the project and wondered how these tags could not fail. As a quick look at the URL of Studio running in a browser will demonstrate, /wavemaker is the Studio's context. This means the JavaScript runtime is only copied in as part of generating the deployment package. The lib folder is loaded directly from Studio's context when you test run an application from Studio using the Run or Test button. RuntimeLoader.js we encountered following index.html as it is the start of the loading of client modules. Manifest.js is an entry point into the loading process. Boot contains pre-initialization, such as the spinning loader image. Next we have another build folder. This one is the one used by applications and contains all possible build files. Not every JavaScript module is packaged up into an optimized build file. Some modules are so specific or rarely used that they are best loaded individually. Otherwise, if there's a build package available to applications, these them. Dojo lives in the dojo folder. I hope you don't find it surprising to find a dijit, dojo, and dojox folder in there. The folder github provides the library path github for JS Beautifier, http://jsbeautifier.org/. The images in the project images folder include a copy of Silk Icons, http://www.famfamfam.com/lab/icons/silk/, a great Creative Common licensed PNG icon set. This brings us to wm. We definitely saved the most interesting folder for our last stop on this tour. For in lib/wm, we have manifest.js, the top level of module loading when using debug mode in the runtime loader. In wm/lib/base, is the top level of the WaveMaker module space used at runtime. This means in wm/lib/base we have the WaveMaker components and widgets folders. These two folders contain the most commonly used sets of classes by WaveMaker developers using any custom JavaScript in a project. This also means we will be back in these folders again too. Summary In this article, we reviewed the WaveMaker architecture. We started with some context of what we mean by "client" and "server" in the context of this book. We then proceeded to dig into the client and the server. We reviewed how both build upon leading frameworks, the Dojo Toolkit and the SpringSource Framework in particular. We examined the running of an application from the network point of view and how the client and server communicated throughout. We dissected a JSON request to the runtime service and encountered project types. We also learned about both project and client type definitions. We ended by revisiting the file system. This time, however, we walked through a Studio installation. Studio is also a WaveMaker application. In the next article, we'll get comfortable with the Studio as a visual tool. We'll look at everything from the properties panels to the built-in source code editors. Resources for Article : Further resources on this subject: Binding Web Services in ESB—Web Services Gateway [Article] Service Oriented JBI: Invoking External Web Services from ServiceMix [Article] Web Services in Apache OFBiz [Article]
Read more
  • 0
  • 0
  • 2274
article-image-media-module
Packt
06 Aug 2013
10 min read
Save for later

The Media module

Packt
06 Aug 2013
10 min read
(For more resources related to this topic, see here.) While there are many ways to build image integration into Drupal, they may all stem from different requirements and also each option should be carefully reviewed. Browsing around over 300 modules available in the Media category in Drupal's modules search for Drupal 7 (http://drupal.org/project/modules) may have you confused as to where to begin. We'll take a look at the Media module (http://drupal.org/project/media) which was sponsored by companies such as Acquia, Palantir, and Advomatic and was created to provide a solid infrastructure and common APIs for working with media assets and images specifically. To begin, download the 7.x-2.x version of the Media module (which is currently regarded as unstable but it is fairly different from 7.x-1.x which will be replaced soon enough) and unpack it to the sites/all/modules directory like we did before. The Media module also requires the File entity (http://drupal.org/project/file_entity) module to further extend how files are managed within Drupal by providing a fieldable file entity, display mods, and more. Use the 7.x-2.x unstable version for the File entity module too and download and unpack as always. To enable these modules navigate to the top administrative bar and click on Modules , scrolling to the bottom of the page we see the Media category with a collection of modules, toggle on all of them (Media field and Media Internet sources), and click on Save configuration . Adding a media asset field If you've noticed something missing in the rezepi content type fields earlier, you were right—what kind of recipes website would this be without some visual stimulation? Yes, we mean pictures! To add a new field, navigate to Structure | Content Types | rezepi | manage fields (/admin/structure/types/manage/rezepi/fields). Name the new field Picture and choose Image as the FIELD TYPE and Media file selector for the WIDGET select box and click on Save . As always, we are about to configure the new field settings, but a step before that presents first global settings for this new field, which is okay to leave as they are, so we will continue, and click on Save field settings . In the general field settings most defaults are suitable, except we want to toggle on the Required field setting and make sure the Allowed file extensions for uploaded files setting lists at least some common image types, so set it to PNG, GIF, JPG, JPEG . Click on Save settings to finalize and we've updated the rezepi content type, so let's start using it. When adding a rezepi, the form for filling up the fields should be similar to the following: The Picture field we defined to use as an image no longer has a file upload form element but rather a button to Select media . Once clicked on it, we can observe multiple tabbed options: For now, we are concerned only with the Upload tab and submit our picture for this rezepi entry. After browsing your local folder and uploading the file, upon clicking Save we are presented with the new media asset form: Our picture has been added to the website's media library and we can notice that it's no longer just a file upload somewhere, but rather it's a media asset with a thumbnail created and even has a way to configure the image HTML input element's attributes. We'll proceed with clicking on Save and once more on the add new content form too, to finalize this new rezepi submission. The media library To further explore the media asset tabs that we've seen before, we will edit the recently created rezepi entry and try to replace the previously uploaded picture with another. In the node's edit form, click on the Picture field's Select media button and browse the Library tab which should resemble the following: The Library tab is actually just a view (you can easily tell by the down-arrow and gear icons to the right of the screen) that lists all the files in your website. Furthermore, this view is equipped with some filters such as the filename, media type, and even sorting options. Straight-away, we can notice that our picture for the rezepi that was created earlier shows up there which is because it has been added as a media asset to the library. We can choose to use it again in further content that we create in the website. Without the media module and it's media assets management, we had to use the file field which only allowed to upload files to our content but never to re-use content that we, or other users, had created previously. Aside from possibly being annoying, this also meant that we had to duplicate files if we needed the same media file for more than one content type. The numbered images probably belong to some of the themes that we experimented before and the last two files are the images we've uploaded to our memo content type. Because these files were not created when the Media module was installed, they lack some of the metadata entries which the Media module keeps to better organize media assets. To manage our media library, we can click on Content from the top administrative bar which shows all content that has been created in your Drupal site. It features filtering and ordering of the columns to easily find content to moderate or investigate and even provides some bulk action updates on several content types. More important, after enabling the Media module we have a new option to choose from in the top right tabs, along with Content and Comments , we now have Files . The page lists all file uploads, both prior to the Media module as well as afterwards, and clearly states the relevant metadata such as media type, size, and the user who uploaded this file. We can also choose from List view or Thumbnail view using the top right tab options, which offers a nicer view and management of our content. The media library management page also features option to add media assets right from this page using the Add file and Import files links. While we've already seen how adding a single media file works, adding a bunch of files is something new. The Import files option allows you to specify a directory on your web server which contains media files and import them all to your Drupal website. After clicking on Preview , it will list the full paths to the files that were detected and will ask you to confirm and thus continue with the import process. Once that's successfully completed, you can return to the files thumbnail view (/admin/content/file/thumbnails) and edit the imported files, possibly setting some title text or removing some entries. You might be puzzled as to what's the point of importing media files directory from the server's web directory, after all, this would require one to have transferred the files there via FTP, SCP, or some other method, but definitely this is somewhat unconventional these days. Your hunch is correct, the import media is a nice to have feature but it's definitely not a replacement for bulk uploads of files from the web interface which Drupal should support and we will later on learn about adding this capability. When using the media library to manage these files, you will probably ask yourself first, before deleting or replacing an image, where is it actually being used? For that reason, Drupal's internal file handling keeps track of which entity makes use of each file and the Media module exposes this information via the web interface for us. Any information about a media asset is available in its Edit or View tabs, including where is it being used. Let's navigate through the media library to find the image we created previously for the rezepi entry and then click on Edit in the rightmost OPERATIONS column. In the Edit page, we can click on the USAGE tab at the top right of the page to get this information: We can tell which entity type is using this file, see the title of the node that it's being used for with a link to it, and finally the usage count. Using URL aliases If you are familiar with Drupal's internal URL aliases then you know that Drupal employs a convention of /node/<NID>[/ACTION], where NID is replaced by the node ID in the database and ACTION may be one of edit, view, or perhaps delete. To see this for yourself, you can click on one of the content items that we've previously created and when viewing it's full node display observe the URL in your browser's address bar. When working with media assets, we can employ the same URL alias convention for files too using the alias /file/<FID>[/ACTION]. For example, to see where the first file you've uploaded is being used, navigate in your browser to /file/1/usage. Remote media assets If we had wanted to replace the picture for this rezepi by specifying a link to an image that we've encountered in a website, maybe even our friend's personal blog, the only way to have done that without the Media module was to download it and upload using the file field's upload widget. With the Media module, we can specify the link for an image hosted and provided by a remote resource using the Web tab. I've Googled some images and after finding my choice for a picture, I simply copy-and-paste the image link to the URL input text as follows: After clicking on Submit , the image file will be downloaded to our website's files directory and the Media module will create the required metadata and present the picture's settings form before replacing our previous picture: There are plenty of modules such as Media: Flickr (http://drupal.org/project/media_flickr) which extends on the Media module by providing integration with remote resources for images and even provides support for a Flickr's photoset or slideshow. Just to list a few other modules: Media: Tableau (http://drupal.org/project/media_tableau) for integrating with the Tableau analytics platform Media: Slideshare (http://drupal.org/project/media_slideshare) for integrating with presentations at Slideshare website Media: Dailymotion (http://drupal.org/project/media_dailymotion) for integrating with the Dailymotion videos sharing website The only thing left for you is to download them from http://drupal.org/modules and start experimenting! Summary In this article, we dived into deep water with creating our very own content type for a food recipe website. In order to provide better user experience when dealing with images in Drupal sites, we learned about the prominent Media module and its extensive support for media resources such as providing a media library and key integration with other modules such as the Media Gallery. Resources for Article : Further resources on this subject: Installing and Configuring Drupal Commerce [Article] Drupal 7 Fields/CCK: Using the Image Field Modules [Article] Drupal 7 Preview [Article]
Read more
  • 0
  • 0
  • 2273

article-image-spicing-your-blog-uploading-files-and-images-your-weblog-using-apache-roller
Packt
30 Dec 2009
5 min read
Save for later

Spicing Up Your Blog: Uploading Files and Images to your Weblog using Apache Roller

Packt
30 Dec 2009
5 min read
This article gives you insight on weblogs and how they can be used to create a worldwide presence through the blogosphere. It also teaches you the difference between a blog and a CMS, the basics about newsfeeds and the important role they play for blogs, and how you can use them to spread information on the blogosphere. Before the action begins Before starting with this article's exercises, you need to download the support files (screenshots, videos, sounds, and so on) from http://www.packtpub.com/files/code/9508_Code.zip, and then unzip them into a folder—C:ApacheRollerBook, for example—on your hard drive. All these files are zipped in a file named chapter05.zip. Inside this file, there's an image file (chapter05_01.jpg), a sound file (seaontherocks.mp3), and several files for the video example (showvbox.mp4, showvbox_controller.swf, and FirstFrame.png). Uploading files to your weblog Now that you have the basic knowledge about how to manage your weblog, it's time to make things more interesting for you and your future visitors. So, how can we do that? Well, multimedia files (audio or video) are always a good addition to a web page, because they can express much more than using text-only posts. Imagine what you could offer to your clients, if you had an online specialty store. You could show your new items in your Roller weblog with full color photos, and you could also embed videos of your items in your posts, to give visitors a complete virtual tour of your store! To top that, you could show them a custom Google Map, where they could get directions from their location to your store! What else could you ask for? Using images on your posts An image can say a thousand words and if you include some of them in your posts, imagine the space you can save. Roller has a very friendly interface to help you upload and include images in your posts, and now you're about to learn how to do it! Time for action – uploading images into Roller In this exercise, I'll show you how to use Roller's file upload interface, so that you can add an image to an entry (post) in your blog:                                                                Open your web browser and log into Roller. The New Entry page will appear. Then click on the File Uploads link, under the Create & Edit tab: The File Uploads page will appear next, as shown in the following screenshot:      Click on the Browse... button of the first text field, and the File Upload dialog will appear. Go to the folder where you downloaded this article's support files, and double-click on the chapter5_01.png image to select it. The name of the file you selected will show up in the first textbox of the File Uploads page: Click on the Upload button to upload the image to your blog. Roller will respond with a success message as shown in the next screenshot: Take note of the URL shown in the previous message, because you'll use it when inserting the image inside a post in your blog. Now click on the New Entry link from the Create & Edit tab, and use the following screenshot as an example for your new post: Press Enter after the last line of text (Here's a screenshot of the official Website:) and click on the text editor's Insert/Modify Image button: The Insert Image dialog will show up. Type the URL of the image you uploaded to Roller (http://localhost/roller/main/resource/chapter5_01.png) inside the Image URL field, and click on the Preview button to see a small preview of the image. Then, type VirtualBox Web site in the Alternate text field and click on the OK button to insert the image in your post: You'll be taken back to the New Entry page again. To see the image, click on the Maximize/Minimize Editor button: The editor will fill up your web browser's entire workspace area and you will be able to see the image, as shown in the following screenshot: Click on the image to select it and change its size by dragging the little white square at the upper-right corner: Click on the Maximize/Minimize Editor button again to change the text editor to its original size. The image will now fit inside the text editor, as shown in the following screenshot: Use the down and right arrow keys to position the text cursor at the end of the post, press Enter and type the text shown in the following screenshot: Exit the text editor and scroll down the New Entry page until you locate the Post to Weblog button, and click on it to publish the post to the blog. Roller will show the Changes saved message inside a green box. Now click on the Front Page link in Roller's menu bar, at the upper-right corner of the screen, to go to your blog's front page: Your new post will appear on your weblog's front page, as shown in the following screenshot: You can logout from Roller and close your web browser now.
Read more
  • 0
  • 0
  • 2270

article-image-faqs-wordpress-3
Packt
15 Feb 2011
10 min read
Save for later

FAQs on WordPress 3

Packt
15 Feb 2011
10 min read
  WordPress 3 Complete Create your own complete website or blog from scratch with WordPress Learn everything you need for creating your own feature-rich website or blog from scratch Clear and practical explanations of all aspects of WordPress In-depth coverage of installation, themes, plugins, and syndication Explore WordPress as a fully functional content management system Clear, easy-to-follow, concise; rich with examples and screenshots         Read more about this book       (For more resources on WordPress, see here.) Q: What is WordPress? A: WordPress is an open source blog engine. Open source means that nobody owns it, everybody works on it, and anyone can contribute to it. Blog engine means a software application that can run a blog. It's a piece of software that lives on the web server and makes it easy for you to add and edit posts, themes, comments, and all of your other content. More expansively, WordPress can be called a publishing platform because it is by no means restricted to blogging.   Q: Why choose WordPress? A: WordPress is not the only publishing platform out there, but it has an awful lot to recommend it. A long time in refining Active in development Large community of contributors Amazingly extendable Compliant with W3C standards Multilanguage capable     Q: What are the system requirements for WordPress? A: The minimum system requirement for WordPress is a web server with the following software installed: PHP Version 4.3 or greater MySQL Version 4.1.2 or greater Although Apache and Nginx are highly recommended by the WordPress developers, any server running PHP and MySQL will do.     Q: What are the new features since 2.7? A: If you're new to WordPress, this list may not mean a whole lot to you, but if you're familiar with WordPress and have been using it for a long time, you'll find this list quite enlightening. The following are the new features: Adding support for "include" and "exclude" to [gallery] Changes Remove link on widgets to Delete because it doesn't just remove it, it deletes the settings for that widget instance Syntax highlighting and function lookup built into plugin and theme editors Improved revision comparison user interface Lots of new template files for custom taxonomies and custom post types, among others Browsing the theme directory and installing themes from the admin Allowing the dashboard widgets to be arranged in up to four columns Choosing username and password during installation rather than using "admin"     Q: How do I upgrade the existing Wordpress version with the latest one? A:If you're upgrading from a very early version of WordPress to a very recent version, you should do it in steps. That is, if you find yourself in a situation where you have to upgrade across a large span of version numbers, for example from 2.2 to 3.0.3, I highly recommend doing it in stages. Do the complete upgrade from 2.2 to 2.3.3, then from 2.3.3 to 2.5, then from 2.5 to 2.7, and finally from 2.7 to 3.0.3. When doing this, you can usually do the full content and database backup just once, but verify in between versions that the gradual upgrades are going well before you move onto the next one. You can download the previous stable versions of WordPress from this page: http://wordpress.org/download/release-archive/. Of course, another option would be to simply do a new installation of the latest version of WordPress and then move your previous content into it, and I encourage you to consider this course of action. However, sometimes contents are harder to move than it is to do the upgrades; this will be up to you to decide your specific server situation and your comfort level with the choices.   Q: What is the WordPress Codex? A: The WordPress Codex is the central repository of all the information the official WordPress team has published to help people work with WordPress. The Codex has some basic tutorials for getting started with WordPress, such as a detailed step-by-step discussion of installation, lists of every template tag and hook, and a lot more.     Q: Is WordPress available for download? A: WordPress is available in easily downloadable formats from its website, http://wordpress.org/download/. WordPress is a free, open source application, and is released under GNU General Public License (GPL). Take a look at the following screenshot in which the download links are available on the right side: The .zip file is shown as a big blue button because that'll be the most useful format for the most people. If you are using Windows, Mac, or Linux operating systems, your computer will be able to unzip that downloaded file automatically. (The .tar.gz file is provided because some Unix users prefer it.)     Q: What is the WordPress Admin Panel? A: WordPress installs a powerful and flexible administration area where you can manage all of your website content, and do much more. You can always get to the WP Admin by going to this URL: http://yoursite.com/wp-admin/. Your first time here, you'll be re-directed to the login page. In the future, WordPress will check to see if you're already logged in and, if so, you'll skip the login page. Following is the login page:     Q: How do I create a post on the blog that I created? A: To create a post, just click on New Post on the top menu. You'll be taken to the following page: Every post should have, at minimum, a title and some content. So go ahead and write in some text for those two things. When you are happy with it, click on the Publish button.     Q: What do I do if I have lost my password? A: If you have lost your password and can't get into your WP Admin panel, you can easily retrieve your password by clicking on the Lost your password? link on the login page. A newly generated password will be e-mailed to you at the e-mail address you gave during the WordPress installation. This is why you need to be sure that you enter a valid e-mail address. Otherwise, you will not be able to retrieve your password.   Q: What do you mean by Categories and Tags? A: Categories and tags are two types of information that you can add to a blog post. We use them to organize the information in your blog by topic and content (rather than just by, say, date), and to help visitors find what they are looking for on your blog.   Q: Which editor is used for writing and editing posts? A: WordPress comes with a Visual editor, otherwise known as a WYSIWYG editor. This is the default editor for typing and editing your posts. If you're comfortable with HTML, you may prefer to write and edit your posts using the HTML editor—particularly useful if you want to add special content or styling. To switch from the rich text editor to the HTML editor, click on the HTML tab next to the Visual tab at the top of the content box: You'll see your post in all its raw HTML glory, and you'll get a new set of buttons that lets you quickly bold and italicize text, as well as add link code, image code, and so on. You can make changes and swap back and forth between the tabs to see the result.     Q: What are Timestamps and how are they useful? A: WordPress will also let you alter the timestamp of your post. This is useful if you are writing a post today that you wish you'd published yesterday, or if you're writing a post in advance and don't want it to show up until the right day. By default, the timestamp will be set to the moment you publish your post. To change it, just find the Publish box, and click on the Edit link (next to the calendar icon and Publish immediately), and fields will show up with the current date and time for you to change: Change the details, click on the OK button, and then click on Publish to publish your post (or save a draft).     Q: Is there any way in which I can protect my content? A: WordPress gives you the option to hide posts. You can hide a post from everyone but yourself by marking it Private, or you can hide it from everyone but the people with whom you share a password by marking it as Password protected. To implement this, look at the Publish box at the upper right of the Edit Post page. If you click on the Edit link next to Visibility: Public, a few options will appear: If you click on the Password protected radio button, you'll get a box where you can type a password. Visitors to your blog will see the post title along with a note that they have to type in a password to read the post. If you click on the Private radio button, the post will not show up on the blog at all to any viewers, unless you are the viewer and you are logged in. If you leave the post Public and check the Stick this post to the front page checkbox, this post will be the first post on the front page, regardless of its publication date. Be sure to click on the OK button if you make any changes.     Q: What is a Widget? A: A widget is a small box of content, dynamic or not, that shows up somewhere on a widget-enabled site. Often, that location is in the sidebar of a blog, but that's not a rule. A widget area can be anywhere a theme developer wants it to be. Common widgets contain: A monthly archive of blog posts Recent comments posted on the blog A clickable list of categories A tag cloud A search box, and so on     Q: How do I add an Image gallery to my post? A: You can add an image gallery to any page or post in your website using WordPress's built-in Image Gallery functionality. There are just three simple steps: Choose a post or page for your image gallery. Upload the images you want in that gallery. Add a plugin, such as lightbox plugin, that will streamline your gallery, and save it. A lightbox effect is when the existing page content fades a little and a new item appears on top of the existing page. We can easily add the same effect to your galleries by adding a plugin. There are a number of lightbox plugins available, but the one I like these days uses jQuery Colorbox. Find this plugin, either through the WP Admin or in the Plugins Repository (http://wordpress.org/extend/plugins/jquery-colorbox/), and install it.   Summary In this article we covered some of the most frequently asked questions on WordPress 3. Further resources on this subject: WordPress 2.8 Themes Cookbook [Book] Getting Started with WordPress 3 [Article] How to Create an Image Gallery in WordPress 3 [Article] Performing Setup Tasks in the WordPress Admin Panel [Article]
Read more
  • 0
  • 0
  • 2267
article-image-plone-4-development-understanding-zope-security
Packt
30 Aug 2011
6 min read
Save for later

Plone 4 Development: Understanding Zope Security

Packt
30 Aug 2011
6 min read
Security primitives Zope's security is declarative: views, actions, and attributes on content objects are declared to be protected by permissions. Zope takes care of verifying that the current user has the appropriate access rights for a resource. If not, an AccessControl.Unauthorized exception will be raised. This is caught by an error handler which will either redirect the user to a login screen or show an access denied error page. Permissions are not granted to users directly. Instead, they are assigned to roles. Users can be given any number of roles, either site-wide, or in the context of a particular folder, in which case they are referred to as local roles. Global and local roles can also be assigned to groups, in which case all users in that group will have the particular role. (In fact, Zope considers users and groups largely interchangeable, and refers to them more generally as principals.) This makes security settings much more flexible than if they were assigned to individual users. Users and groups Users and groups are kept in user folders, which are found in the ZMI with the name acl_users. There is one user folder at the root of the Zope instance, typically containing only the default Zope-wide administrator that is created by our development buildout the first time it is run. There is also an acl_users folder inside Plone, which manages Plone's users and groups. Plone employs the Pluggable Authentication Service (PAS), a particularly flexible kind of user folder. In PAS, users, groups, their roles, their properties, and other security-related policy are constructed using various interchangeable plugins. For example, an LDAP plugin could allow users to authenticate against an LDAP repository. In day-to-day administration, users and groups are normally managed from Plone's Users and Groups control panel. Permissions Plone relies on a large number of permissions to control various aspects of its functionality. Permissions can be viewed from the Security tab in the ZMI, which lets us assign permissions to roles at a particular object. Note that most permissions are set to Acquire—the default—meaning that they cascade down from the parent folder. Role assignments are additive when permissions are set to acquire. Sometimes, it is appropriate to change permission settings at the root of the Plone site (which can be done using the rolemap.xml GenericSetup import step—more on that follows), but managing permissions from the Security tab anywhere else is almost never a good idea. Keeping track of which security settings are made where in a complex site can be a nightmare. Permissions are the most granular piece of the security puzzle, and can be seen as a consequence of a user's roles in a particular context. Security-aware code should almost always check permissions, rather than roles, because roles can change depending on the current folder and security policy of the site, or even based on an external source such as an LDAP or Active Directory repository. Permissions can be logically divided into three main categories: Those that relate to basic content operations, such as View and Modify portal content. These are used by almost all content types, and defined as constants in the module Products.CMFCore.permissions. Core permissions are normally managed by workflow. Those that control the creation of particular types of content, such as ATContentTypes: Add Image. These are usually set at the Plone site root to apply to the whole site, but they may be managed by workflow on folders. Those that control site-wide policy. For example, the Portlets: Manage portlets permission is usually given to the Manager and Site Administrator roles, because this is typically an operation that only the site's administrator will need to perform. These permissions are usually set at the site root and acquired everywhere else. Occasionally, it may be appropriate to change them here. For example, the Add portal member permission controls whether anonymous users can add themselves (that is, "join" the site) or not. Note that there is a control panel setting for this, under Security in Site Setup. Developers can create new permissions when necessary, although they are encouraged to reuse the ones in Products.CMFCore.permissions if possible. The most commonly used permissions are: Permission Constant Zope Toolkit name Controls Access contents information AccessContents Information zope2.AccessContents Information Low-level Zope permission controlling access to objects View View zope2.View Access to the main view of a content object List folder contents ListFolderContents cmf.ListFolderContents Ability to view folder listings Modify portal content ModifyPortalContent cmf.ModifyPortalContent Edit operations on content Change portal events N/A N/A Modification of the Event content type (largely a historical accident) Manage portal ManagePortal cmf.ManagePortal Operations typically restricted to the Manager role. Request review RequestReview cmf.RequestReview Ability to submit content for review in many workflows. Review portal content ReviewPortalContent cmf.ReviewPortalContent Ability to approve or reject items submitted for review in many workflows. Add portal content AddPortalContent cmf.AddPortalContent add new content in a folder. Note that most content types have their own "add" permissions. In this case, both this permission and the type-specific permission are required. The Constant column in the preceding table refers to constants defined in Products. CMFCore.permissions. The Zope Toolkit name column lists the equivalent names found in ZCML files in packages such as Products.CMFCore, Products.Five and (at least from Zope 2.13), AccessControl. They contain directives such as: <permission id="zope2.View" title="View" /> This is how permissions are defined in the Zope Toolkit. Custom permissions can also be created in this way. Sometimes, we will use ZCML directives which expect a permission attribute, such as: <browser:page name="some-view" class=".someview.SomeView" for="*" permission="zope2.View" /> The permission attribute here must be a Zope Toolkit permission ID. The title of the <permission /> directive is used to map the Zope 2-style permissions (which are really just strings) to Zope Toolkit permission IDs. To declare that a particular view or other resource defined in ZCML should not be subject to security checks, we can use the special permission zope.Public.
Read more
  • 0
  • 0
  • 2263

article-image-integrating-yahoo-user-interface-library-yui-moodle
Packt
13 May 2011
6 min read
Save for later

Integrating Yahoo! User Interface Library (YUI) with Moodle

Packt
13 May 2011
6 min read
  Moodle JavaScript Cookbook Over 50 recipes for making your Moodle system more dynamic and responsive with JavaScript In this article, we will cover: Initializing the YUI 3 library Loading YUI 3 modules Loading YUI 2 modules from YUI 3 Attaching basic event handlers Attaching advanced DOM event handlers Implementing Event Delegation Debugging with the YUI console Introduction There are a lot of common tasks that need to be performed when writing JavaScript. A large proportion of this simply involves dealing with differences between web browsers. The need for a way to hide or abstract the specifics of each browser into a standard interface gave rise to sets of tools known as JavaScript libraries. One of the leading libraries in use on the web today is the Yahoo! User Interface Library (YUI). Moodle includes a copy of the YUI as its preferred JavaScript library. YUI provides developers with access to a wide range of tools for enhancing their web applications: The YUI Library is a set of utilities and controls, written with JavaScript and CSS, for building richly interactive web applications using techniques such as DOM scripting, DHTML and AJAX. YUI is available under a BSD license and is free for all uses. YUI is proven, scalable, fast, and robust. Built by frontend engineers at Yahoo! and contributors from around the world, it's an industrial-strength JavaScript library for professionals who love JavaScript. Yahoo! Developer Network http://developer.yahoo.com/yui/ In this article, we will learn the basics of working with YUI. We will learn how to initialize the YUI and make it ready for use within our code and load additional modules from versions 2 and 3 of the YUI. We will also learn how to manage the execution of code by attaching events to our controls, and finally how to debug our code with YUI logging tools. Initializing the YUI 3 library In this recipe, we will learn how to initialize the YUI 3 environment within Moodle, which will get us ready to start using YUI 3 features. Moodle takes care of most of the initial setup, namely loading the required CSS and JavaScript files, so all we need to be concerned with is activating the YUI environment. This example will show how to execute JavaScript code from within the YUI environment. We will set up a small YUI script which will simply display a message including the version number of the active YUI environment in a JavaScript alert box. This provides a simple view of what is required to get YUI up and running that we will build on further in the subsequent recipes. Getting ready We begin by setting up a new PHP file yui_init.php in the cook directory with the following content: <?php require_once(dirname(__FILE__) . '/../config.php'); $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); $PAGE->set_url('/cook/yui_init.php'); $PAGE->requires->js('/cook/yui_init.js'); echo $OUTPUT->header(); echo $OUTPUT->footer(); ?> Notice that the preceding code references a JavaScript file yui_init.js, which has the following content: YUI().use ( function(Y) { alert('Hello from YUI ' + Y.version); } ); How to do it... We have created a PHP file that sets up a Moodle programming environment and includes a JavaScript file, in a way now familiar to us from previous recipes. What is new here is the content of the JavaScript file, which is where we will make ready the YUI 3 environment. Moodle has already included all the JavaScript files required for YUI (this happened when we output the value returned from $OUTPUT->header();). This means we now have a global object named YUI available within our JavaScript code. We create a new instance of the YUI object with the statement YUI() and then immediately call the use method. The only parameter we will pass to the use method is an anonymous function. This is just like a regular JavaScript function, except that it has no name specified; hence it is "anonymous". A name is not required, as it is not referred to again, but it is simply passed directly to the use method. This function itself accepts a single input parameter Y, which will be a reference to the new instance of the YUI object. (Note that the use method is also used to load additional YUI modules; this is the subject of the next recipe.) The anonymous function just created is the most important part of the code to take note of as this is where we will be putting our entire code that will be making use of the YUI features. In this example, you can see that we are just creating a JavaScript alert with a short message including the value of Y.version, which is simply a string containing the version number of YUI that has been loaded as seen in the following screenshot: Here, we can see that our code has successfully initialized the YUI 3.2.0 environment and is ready for us to start using the features available within the YUI and its additional modules. How it works... We have created a new instance of the global object YUI, and called the use method, passing in an anonymous function that contains the code we wish to run. When the new instance of the YUI object is fully loaded, it makes a call to our anonymous function, and our code is executed. In this example, our code displays a short message containing the version number of the YUI instance we created, confirming that we have a fully functional YUI 3 environment as a basis to implement further YUI features. Loading additional YUI modules YUI has a whole host of additional modules providing a very wide range of functionalities. Some examples of commonly used functionalities provided by additional modules include: Animation Drag and drop Manipulating DOM elements Handling DOM events (that is an input button's "click" event) Handling data (JSON/XML) For a current list of all the modules available, please refer to the Yahoo! Developer Network website for YUI 3 at the URL: http://developer.yahoo.com/yui/3/ How to do it... The loading of additional modules is achieved via the use method of the YUI object. In the previous recipe we learned how to run code via the use method with the following syntax: YUI().use ( function(Y) { /* <code to execute> */ } ); Note that the use method takes an arbitrarily long number of arguments (one or more) and only the last argument must be the anonymous function described in the previous recipe. The preceding arguments are a list of one or more modules you wish to load. So for example, to load the Animation module (anim) and the DOM Event Utility module (event), we would use the following syntax in place of the preceding one: YUI().use ( "anim", "event", function(Y) { /* <code to execute> */ } ); Now all of the features of these two additional modules (anim and event) will be available within the anonymous function that contains the code we want to execute. This technique will be used to load the modules we require in the examples contained in the subsequent recipes.
Read more
  • 0
  • 0
  • 2262
Modal Close icon
Modal Close icon