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

How-To Tutorials

7018 Articles
article-image-basics-exception-handling-mechanism-javascript-testing
Packt
25 Aug 2010
6 min read
Save for later

Basics of Exception Handling Mechanism in JavaScript Testing

Packt
25 Aug 2010
6 min read
(For more resources on JavaScript, see here.) Issues with combining scripts Consider the real-life situation where we typically use external JavaScript; what happens if we use more than one JavaScript file? What kind of issues can we expect if we use more than one external JavaScript file? We'll cover all of this in the subsections below. We'll start with the first issue—combining event handlers. JavaScript helps to bring life to our web page by adding interactivity. Event handlers are the heartbeat of interactivity. For example, we click on a button and a pop-up window appears, or we move our cursor over an HTML div element and the element changes color to provide visual feedback. To see how we can combine event handlers, consider the following example, which is found in the source code folder in the files combine-event-handlers.html and combine-event-handlers.js as shown in the following code: In combine-event-handlers.html, we have: <html> <head> <title>Event handlers</title> <script type="text/javascript" src="combine-event- handlers.js"></script> </head> <body> <div id="one" onclick="changeOne(this);"><p>Testing One</p></div> <div id="two" onclick="changeTwo(this);"><p>Testing Two</p></div> <div id="three" onclick="changeThree(this);"><p>Testing Three</p></div> </body></html> Notice that each of the div elements is handled by different functions, namely, changeOne(), changeTwo(), and changeThree() respectively. The event handlers are found in combine-event-handlers.js: function changeOne(element) { var id = element.id; var obj = document.getElementById(id); obj.innerHTML = ""; obj.innerHTML = "<h1>One is changed!</h1>"; return true;}function changeTwo(element) { var id = element.id; var obj = document.getElementById(id); obj.innerHTML = ""; obj.innerHTML = "<h1>Two is changed!</h1>"; return true;}function changeThree(element) { var id = element.id; var obj = document.getElementById(id); obj.innerHTML = ""; obj.innerHTML = "<h1>Three is changed!</h1>"; return true;} You might want to go ahead and test the program. As you click on the text, the content changes based on what is defined in the functions. However, we can rewrite the code such that all of the events are handled by one function. We can rewrite combine-event-handlers.js as follows: function combine(element) { var id = element.id; var obj = document.getElementById(id); if(id == "one"){ obj.innerHTML = ""; obj.innerHTML = "<h1>One is changed!</h1>"; return true;}else if(id == "two"){ obj.innerHTML = ""; obj.innerHTML = "<h1>Two is changed!</h1>"; return true;}else if(id == "three"){ obj.innerHTML = ""; obj.innerHTML = "<h1>Three is changed!</h1>"; return true;}else{ ; // do nothing }} When we use if else statements to check the id of the div elements that we are working on, and change the HTML contents accordingly, we will save quite a few lines of code. Take note that we have renamed the function to combine(). Because we have made some changes to the JavaScript code, we'll need to make the corresponding changes to our HTML. So combine-event-handlers.html will be rewritten as follows: <html> <head> <title>Event handlers</title> <script type="text/javascript" src="combine-event- handlers.js"></script> </head> <body> <div id="one" onclick="combine(this);"><p>Testing One</p></div> <div id="two" onclick="combine(this);"><p>Testing Two</p></div> <div id="three" onclick="combine(this);"><p>Testing Three</p></div> </body></html> Notice that the div elements are now handled by the same function, combine(). These rewritten examples can be found in combine-event-handlers-combined.html and combine-event-handlers-combined.js. Naming clashes Removing name clashes is the next issue that we need to deal with. Similar to the issue of combining event handlers, naming clashes occur when two or more variables, functions, events, or other objects have the same name. Although these variables or objects can be contained in different files, these name clashes do not allow our JavaScript program to run properly. Consider the following code snippets: In nameclash.html, we have the following code: <html> <head> <title>testing</title> <script type="text/javascript" src="nameclash1.js"></script> </head> <body> <div id="test" onclick="change(this);"><p>Testing</p></div> </body></html> In nameclash1.js, we have the following code: function change(element) { var id = element.id; var obj = document.getElementById(id); obj.innerHTML = ""; obj.innerHTML = "<h1>This is changed!</h1>"; return true;} If you run this code by opening the file in your browser and clicking on the text Testing, the HTML contents will be changed as expected. However, if we add &ltscript type="text/javascript" src="nameclash2.js"></script> after the &lttitle></title> tag, and if the content of nameclash2.js is as follows: function change(element) { alert("so what?!");} Then we will not be able to execute the code properly. We will see the alert box instead of the HTML contents being changed. If we switch the arrangement of the external JavaScript, then the HTML contents of the div elements will be changed and we will not be able to see the alert box. With such naming clashes, our program becomes unpredictable; the solution to this is to use unique names in your functions, classes, or events. If you have a relatively large program, it would be advisable to use namespaces, which is a common strategy in several JavaScript libraries such as YUI and jQuery.
Read more
  • 0
  • 0
  • 1985

article-image-ibm-websphere-mq-commands
Packt
25 Aug 2010
10 min read
Save for later

IBM WebSphere MQ commands

Packt
25 Aug 2010
10 min read
(For more resources on IBM, see here.) After reading this article, you will not be a WebSphere MQ expert, but you will have brought your knowledge of MQ to a level where you can have a sensible conversation with your site's MQ administrator about what the Q replication requirements are. An introduction to MQ In a nutshell, WebSphere MQ is an assured delivery mechanism, which consists of queues managed by Queue Managers. We can put messages onto, and retrieve messages from queues, and the movement of messages between queues is facilitated by components called Channels and Transmission Queues. There are a number of fundamental points that we need to know about WebSphere MQ: All objects in WebSphere MQ are case sensitive We cannot read messages from a Remote Queue (only from a Local Queue) We can only put a message onto a Local Queue (not a Remote Queue) It does not matter at this stage if you do not understand the above points, all will become clear in the following sections. There are some standards regarding WebSphere MQ object names: Queue names, processes and Queue Manager names can have a maximum length of 48 characters Channel names can have a maximum length of 20 characters The following characters are allowed in names: A-Z,a-z,0-9, and . / _ % symbols There is no implied structure in a name — dots are there for readability Now let's move on to look at MQ queues in a little more detail. MQ queues MQ queues can be thought of as conduits to transport messages between Queue Managers. There are four different types of MQ queues and one related object. The four different types of queues are: Local Queue (QL), Remote Queue (QR), Transmission Queue (TQ), and Dead Letter Queue, and the related object is a Channel (CH). One of the fundamental processes of WebSphere MQ is the ability to move messages between Queue Managers. Let's take a high-level look at how messages are moved, as shown in the following diagram: When the application Appl1 wants to send a message to application Appl2, it opens a queue - the local Queue Manager (QM1) determines if it is a Local Queue or a Remote Queue. When Appl1 issues an MQPUT command to put a message onto the queue, then if the queue is local, the Queue Manager puts the message directly onto that queue. If the queue is a Remote Queue, then the Queue Manager puts the message onto a Transmission Queue. The Transmission Queue sends the message using the Sender Channel on QM1 to the Receiver Channel on the remote Queue Manager (QM2). The Receiver Channel puts the message onto a Local Queue on QM2. Appl2 issues a MQGET command to retrieve the message from this queue. Now let's move on to look at the queues used by Q replication and in particular, unidirectional replication, as shown in the following diagram. What we want to show here is the relationship between Remote Queues, Transmission Queues, Channels, and Local Queues. As an example, let's look at the path a message will take from Q Capture on QMA to Q Apply on QMB. (Move the mouse over the image to enlarge.) Note that in this diagram the Listeners are not shown. Q Capture puts the message onto a remotely-defned queue on QMA (the local Queue Manager for Q Capture). This Remote Queue (CAPA.TO.APPB.SENDQ.REMOTE) is effectively a "place holder" and points to a Local Queue (CAPA.TO.APPB.RECVQ) on QMB and specifes the Transmission Queue (QMB.XMITQ) it should use to get there. The Transmission Queue has, as part of its defnition, the Channel (QMA.TO.QMB) to use. The Channel QMA.TO.QMB has, as part of its defnition, the IP address and Listening port number of the remote Queue Manager (note that we do not name the remote Queue Manager in this defnition—it is specifed in the defnition for the Remote Queue). The defnition for unidirectional Replication Queue Map (circled queue names) is: SENDQ: CAPA.TO.APPB.SENDQ.REMOTE on the source RECVQ: CAPA.TO.APPB.RECVQ on the target ADMINQ: CAPA.ADMINQ.REMOTE on the target Let's look at the Remote Queue defnition for CAPA.TO.APPB.SENDQ.REMOTE, shown next. On the left-hand side are the defnitions on QMA, which comprise the Remote Queue, the Transmission Queue, and the Channel defnition. The defnitions on QMB are on the right-hand side and comprise the Local Queue and the Receiver Channel. Let's break down these defnitions to the core values to show the relationship between the different parameters, as shown next: We defne a Remote Queue by matching up the superscript numbers in the defnitions in the two Queue Managers: For defnitions on QMA, QMA is the local system and QMB is the remote system. For defnitions on QMB, QMB is the local system and QMA is the remote system. Remote Queue Manager name Name of the queue on the remote system Transmission Queue name Port number that the remote system is listening on The IP address of the Remote Queue Manager Local Queue Manager name Channel name Queue names: QMB: Decide on the Local Queue name on QMB—CAPA.TO.APPB.RECVQ. QMA: Decide on the Remote Queue name on QMB—CAPA.TO.APPB.SENDQ.REMOTE. Channels: QMB: Defne a Receiver Channel on QMB, QMA.TO.QMB—make sure the channel type (CHLTYPE) is RCVR. The Channel names on QMA and QMB have to match: QMA.TO.QMB. QMA: Defne a Sender Channel, which takes the messages from the Transmission Queue QMB.XMITQ and which points to the IP address and Listening port number of QMB. The Sender Channel name must be QMA.TO.QMB. Let's move on from unidirectional replication to bidirectional replication. The bidirectional queue diagram is shown next, which is a cut-down version of the full diagram of the The WebSphere MQ layer and just shows the queue names and types without the details. The principles in bidirectional replication are the same as for unidirectional replication. There are two Replication Queue Maps—one going from QMA to QMB (as unidirectional replication) and one going from QMB to QMA. MQ queue naming standards The naming of the WebSphere MQ queues is an important part of Q replication setup. It may be that your site already has a naming standard for MQ queues, but if it does not, then here are some thoughts on the subject (WebSphere MQ naming standards were discussed in the Introduction to MQ section): Queues are related to Q Capture and Q Apply programs, so it would be useful to have that fact refected in the name of the queues. A Q Capture needs a local Restart Queue and we use the name CAPA.RESTARTQ. Each Queue Manager can have a Dead Letter Queue. We use the prefx DEAD.LETTER.QUEUE with a suffx of the Queue Manager name giving DEAD.LETTER.QUEUE.QMA. Receive Queues are related to Send Queues. For every Send Queue, we need a Receive Queue. Our Send Queue names are made up of where they are coming from, Q Capture on QMA (CAPA), and where they are going to, Q Apply on QMB (APPB), and we also want to put in that it is a Send Queue and that it is a remote defnition, so we end up with CAPA.TO.APPB.SENDQ.REMOTE. The corresponding Receive Queue will be called CAPA.TO.APPB.RECVQ. Transmission Queues should refect the names of the "to" Queue Manager. Our Transmission Queue on QMA is called QMB.XMITQ, refecting the Queue Manager that it is going to, and that it is a Transmission Queue. Using this naming convention on QMB, the Transmission Queue is called QMA.XMITQ. Channels should refect the names of the "from" and "to" Queue Managers. Our Sender Channel defnition on QMA is QMA.TO.QMB refecting that it is a channel from QMA to QMB and the Receiver Channel on QMB is also called QMA.TO.QMB. The Receiver Queue on QMA is called QMB.TO.QMA for a Sender Channel of the same name on QMB. A Replication Queue Map defnition requires a local Send Queue, and a remote Receive Queue and a remote Administration Queue. The Send Queue is the queue that Q Capture writes to, the Receive Queue is the queue that Q Apply reads from, and the Administration Queue is the queue that Q Apply writes messages back to Q Capture with. MQ queues required for different scenarios This section lists the number of Local and Remote Queues and Channels that are needed for each type of replication scenario. The queues and channels required for unidirectional replication (including replicating to a Stored Procedure) and Event Publishing are shown in the following tables. Note that the queues and channels required for Event Publishing are a subset of those required for unidirectional replication, but creating extra queues and not using them is not a problem. The queues and channels required for unidirectional (including replicating to a Stored Procedure) are shown in the following table: QMA (7) QMB (7) 3 Local Queues: CAPA.ADMINQ CAPA.RESTARTQ DEAD.LETTER.QUEUE.QMA 1 Remote Queue: CAPA.TO.APPB.SENDQ.REMOTE 1 Transmission Queue: QMB.XMITQ 1 Sender Channel: QMA.TO.QMB 1 Receiver Channel: QMB.TO.QMA 2 Local Queues: CAPA.TO.APPB.REVCQ DEAD.LETTER.QUEUE.QMB 1 Remote Queue: CAPA.ADMINQ.REMOTE 1 Transmission Queue: QMA.XMITQ 1 Sender Channel: QMB.TO.QMA 1 Receiver Channel: QMA.TO.QMB 1 Model Queue: IBMQREP.SPILL.MODELQ   The queues required for Event Publishing are shown in the following table: QMA (7) QMB (7) 3 Local Queues: CAPA.ADMINQ CAPA.RESTARTQ DEAD.LETTER.QUEUE.QMA 1 Remote Queue: CAPA.TO.APPB.SENDQ.REMOTE 1 Transmission Queue: QMB.XMITQ 1 Sender Channel: QMA.TO.QMB 1 Receiver Channel: QMB.TO.QMA 2 Local Queues: CAPA.TO.APPB.REVCQ DEAD.LETTER.QUEUE.QMB 1 Receiver Channel: QMA.TO.QMB The queues and channels required for bidirectional/P2P two-way replication are shown in the following table: QMA (10) QMB (10) 4 Local Queues: CAPA.ADMINQ CAPA.RESTARTQ DEAD.LETTER.QUEUE.QMA CAPB.TO.APPA.RECVQ 2 Remote Queues: CAPA.TO.APPB.SENDQ.REMOTE CAPB.ADMINQ.REMOTE 1 Transmission Queue: QMB.XMITQ 1 Sender Channel: QMA.TO.QMB 1 Receiver Channel: QMB.TO.QMA 1 Model Queue: IBMQREP.SPILL.MODELQ 4 Local Queues: CAPB.ADMINQ CAPB.RESTARTQ DEAD.LETTER.QUEUE.QMB CAPA.TO.APPB.RECVQ 2 Remote Queues: CAPB.TO.APPA.SENDQ.REMOTE CAPA.ADMINQ.REMOTE 1 Transmission Queue: QMA.XMITQ 1 Sender Channel: QMB.TO.QMA 1 Receiver Channel: QMA.TO.QMB 1 Model Queue: IBMQREP.SPILL.MODELQ The queues and channels required for P2P three-way replication are shown in the following table: QMA (16) QMB (16) QMC (16) 5 Local Queues: CAPA.ADMINQ CAPA.RESTARTQ DEAD.LETTER.QUEUE. QMA CAPB.TO.APPA.RECVQ CAPC.TO.APPA.RECVQ 4 Remote Queues: CAPA.TO.APPB. SENDQ.REMOTE CAPB.ADMINQ.REMOTE CAPA.TO.APPC. SENDQ.REMOTE CAPC.ADMINQ.REMOTE 2 Transmission Queues: QMB.XMITQ QMC.XMITQ 2 Sender Channels: QMA.TO.QMC QMA.TO.QMB 2 Receiver Channels: QMC.TO.QMA QMB.TO.QMA 1 Model Queue: IBMQREP.SPILL. MODELQ 5 Local Queues: CAPB.ADMINQ CAPB.RESTARTQ DEAD.LETTER.QUEUE. QMB CAPA.TO.APPB.RECVQ CAPC.TO.APPB.RECVQ 4 Remote Queues: CAPB.TO.APPA. SENDQ.REMOTE CAPA.ADMINQ.REMOTE CAPB.TO.APPC. SENDQ.REMOTE CAPC.ADMINQ.REMOTE 2 Transmission Queues: QMA.XMITQ QMC.XMITQ 2 Sender Channels: QMB.TO.QMA QMB.TO.QMC 2 Receiver Channels: QMA.TO.QMB QMC.TO.QMB 1 Model Queue: IBMQREP.SPILL. MODELQ 5 Local Queues: CAPC.ADMINQ CAPC.RESTARTQ DEAD.LETTER. QUEUE.QMC CAPA.TO.APPC.RECVQ CAPB.TO.APPC.RECVQ 4 Remote Queues: CAPC.TO.APPA. SENDQ.REMOTE CAPA.ADMINQ.REMOTE CAPC.TO.APPB. SENDQ.REMOTE CAPB.ADMINQ.REMOTE 2 Transmission Queues: QMA.XMITQ QMB.XMITQ 2 Sender Channels: QMC.TO.QMA QMC.TO.QMB 2 Receiver Channels: QMA.TO.QMC QMB.TO.QMC 1 Model Queue: IBMQREP.SPILL. MODELQ
Read more
  • 0
  • 0
  • 13908

article-image-manipulating-images-javafx
Packt
25 Aug 2010
4 min read
Save for later

Manipulating Images with JavaFX

Packt
25 Aug 2010
4 min read
(For more resources on Java, see here.) One of the most celebrated features of JavaFX is its inherent support for media playback. As of version 1.2, JavaFX has the ability to seamlessly load images in different formats, play audio, and play video in several formats using its built-in components. To achieve platform independence and performance, the support for media playback in JavaFX is implemented as a two-tiered strategy: Platform-independent APIs—the JavaFX SDK comes with a media API designed to provide a uniform set of interfaces to media functionalities. Part of the platform-independence offerings include a portable codec (On2's VP6), which will play on all platforms where JavaFX media playback is supported. Platform-dependent implementations—to boost media playback performance, JavaFX also has the ability to use the native media engine supported by the underlying OS. For instance, playback on the Windows platform may be rendered by the Windows DirectShow media engine (see next recipe). This two-part article shows you how to use the supported media rendering components, including ImageView, MediaPlayer, and MediaView. These components provide high-level APIs that let developers create applications with engaging and interactive media content. Accessing media assets You may have seen the use of variable __DIR__ when accessing local resources, but may not fully know about its purpose and how it works. So, what does that special variable store? In this recipe, we will explore how to use the __DIR__ special variable and other means of loading resources locally or remotely. Getting ready The concepts presented in this recipe are used widely throughout the JavaFX application framework when pointing to resources. In general, classes that point to a local or remote resource uses a string representation of a URL where the resource is stored. This is especially true for the ImageView and MediaPlayer classes discussed in this article. How to do it... This recipe shows you three ways of creating a URL to point to a local or remote resource used by a JavaFX application. The full listing of the code presented here can be found in ch05/source-code/src/UrlAccess.fx. Using the __DIR__ pseudo-variable to access assets as packaged resources: var resImage = "{__DIR__}image.png"; Using a direct reference to a local file: var localImage = "file:/users/home/vladimir/javafx/ch005/source-code/src/image.png"; Using a URL to access a remote file: var remoteImage = "http://www.flickr.com/3201/2905493571_a6db13ce1b_d.jpg" How it works... Loading media assets in JavaFX requires the use of a well-formatted URL that points to the location of the resources. For instance, both the Image and the Media classes (covered later in this article series) require a URL string to locate and load the resource to be rendered. The URL must be an absolute path that specifies the fully-realized scheme, device, and resource location. The previous code snippets show the following three ways of accessing resources in JavaFX: __DIR__ pseudo-variable—often, you will see the use of JavaFX's pseudo variable __DIR__, used when specifying the location of a resource. It is a special variable that stores the String value of the directory where the executing class that referenced __DIR__ is located. This is valuable, especially when the resource is embedded in the application's JAR file. At runtime, __DIR__ stores the location of the resource in the JAR file, making it accessible for reading as a stream. In the previous code, for example, the expression {__DIR__}image.png explodes as jar:file:/users/home/vladimir/javafx/ch005/source-code/dist/source-code.jar!/image.png. Direct reference to local resources—when the application is deployed as a desktop application, you can specify the location of your resources using URLs that provides the absolute path to where the resources are located. In our code, we use file:/users/home/vladimir/javafx/ch005/source-code/src/image.png as the absolute fully qualified path to the image file image.png. Direct reference to remote resources—finally, when loading media assets, you are able to specify the path of a fully-qualified URL to a remote resource using HTTP. As long as there are no subsequent permissions required, classes such as Image and Media are able to pull down the resource with no problem. For our code, we use a URL to a Flickr image http://www.flickr.com/3201/2905493571_a6db13ce1b_d.jpg. There's more... Besides __DIR__, JavaFX provides the __FILE__ pseudo variable as well. As you may well guess, __FILE__ resolves to the fully qualified path of the of the JavaFX script file that contains the __FILE__ pseudo variable. At runtime, when your application is compiled, this will be the script class that contains the __FILE__ reference.
Read more
  • 0
  • 0
  • 5839

article-image-building-facebook-clone-using-ruby
Packt
25 Aug 2010
8 min read
Save for later

Building the Facebook Clone using Ruby

Packt
25 Aug 2010
8 min read
(For more resources on Ruby, see here.) This is the largest clone and has many components. Some of the less interesting parts of the code are not listed or described here. To get access to the full source code please go to http://github.com/sausheong/saushengine. Configuring the clone We use a few external APIs in Colony so we need to configure our access to these APIs. In a Colony all these API keys and settings are stored in a Ruby file called config.rb as below. S3_CONFIG = {}S3_CONFIG['AWS_ACCESS_KEY'] = '<AWS ACCESS KEY>'S3_CONFIG['AWS_SECRET_KEY'] = '<AWS SECRET KEY>'RPX_API_KEY = '<RPX API KEY>' Modeling the data You will find a large number of classes and relationships in this article. The following diagram shows how the clone is modeled: User The first class we look at is the User class. There are more relationships with other classes and the relationship with other users follows that of a friends model rather than a followers model. class User include DataMapper::Resource property :id, Serial property :email, String, :length => 255 property :nickname, String, :length => 255 property :formatted_name, String, :length => 255 property :sex, String, :length => 6 property :relationship_status, String property :provider, String, :length => 255 property :identifier, String, :length => 255 property :photo_url, String, :length => 255 property :location, String, :length => 255 property :description, String, :length => 255 property :interests, Text property :education, Text has n, :relationships has n, :followers, :through => :relationships, :class_name => 'User', :child_key => [:user_id] has n, :follows, :through => :relationships, :class_name => 'User', :remote_name => :user, :child_key => [:follower_id] has n, :statuses belongs_to :wall has n, :groups, :through => Resource has n, :sent_messages, :class_name => 'Message', :child_key => [:user_id] has n, :received_messages, :class_name => 'Message', :child_key => [:recipient_id] has n, :confirms has n, :confirmed_events, :through => :confirms, :class_name => 'Event', :child_key => [:user_id], :date.gte => Date.today has n, :pendings has n, :pending_events, :through => :pendings, :class_name => 'Event', :child_key => [:user_id], :date.gte => Date.today has n, :requests has n, :albums has n, :photos, :through => :albums has n, :comments has n, :activities has n, :pages validates_is_unique :nickname, :message => "Someone else has taken up this nickname, try something else!" after :create, :create_s3_bucket after :create, :create_wall def add_friend(user) Relationship.create(:user => user, :follower => self) end def friends (followers + follows).uniq end def self.find(identifier) u = first(:identifier => identifier) u = new(:identifier => identifier) if u.nil? return u end def feed feed = [] + activities friends.each do |friend| feed += friend.activities end return feed.sort {|x,y| y.created_at <=> x.created_at} end def possessive_pronoun sex.downcase == 'male' ? 'his' : 'her' end def pronoun sex.downcase == 'male' ? 'he' : 'she' end def create_s3_bucket S3.create_bucket("fc.#{id}") end def create_wall self.wall = Wall.create self.save end def all_events confirmed_events + pending_events end def friend_events events = [] friends.each do |friend| events += friend.confirmed_events end return events.sort {|x,y| y.time <=> x.time} end def friend_groups groups = [] friends.each do |friend| groups += friend.groups end groups - self.groups endend As mentioned in the design section above, the data used in Colony is user-centric. All data in Colony eventually links up to a user. A user has following relationships with other models: A user has none, one, or more status updates A user is associated with a wall A user belongs to none, one, or more groups A user has none, one, or more sent and received messages A user has none, one, or more confirmed and pending attendances at events A user has none, one, or more user invitations A user has none, one, or more albums and in each album there are none, one, or more photos A user makes none, one, or more comments A user has none, one, or more pages A user has none, one, or more activities Finally of course, a user has one or more friends Once a user is created, there are two actions we need to take. Firstly, we need to create an Amazon S3 bucket for this user, to store his photos. after :create, :create_s3_bucketdef create_s3_bucket S3.create_bucket("fc.#{id}")end We also need to create a wall for the user where he or his friends can post to. after :create, :create_walldef create_wall self.wall = Wall.create self.saveend Adding a friend means creating a relationship between the user and the friend. def add_friend(user) Relationship.create(:user => user, :follower => self) end Colony treats the following relationship as a friends relationship. The question here is who will initiate the request to join? This is why when we ask the User object to give us its friends, it will add both followers and follows together and return a unique array representing all the user's friends. def friends (followers + follows).uniqend In the Relationship class, each time a new relationship is created, an Activity object is also created to indicate that both users are now friends. class Relationship include DataMapper::Resource property :user_id, Integer, :key => true property :follower_id, Integer, :key => true belongs_to :user, :child_key => [:user_id] belongs_to :follower, :class_name => 'User', :child_key => [:follower_id] after :save, :add_activity def add_activity Activity.create(:user => user, :activity_type => 'relationship', :text => "<a href='/user/#{user.nickname}'>#{user.formatted_name}</a> and <a href='/user/#{follower.nickname}'>#{follower.formatted_name}</a> are now friends.") end end Finally we get the user's news feed by taking the user's activities and going through each of the user's friends, their activities as well. def feed feed = [] + activities friends.each do |friend| feed += friend.activities end return feed.sort {|x,y| y.created_at <=> x.created_at}end Request We use a simple mechanism for users to invite other users to be their friends. The mechanism goes like this: Alice identifies another Bob whom she wants to befriend and sends him an invitation This creates a Request class which is then attached to Bob When Bob approves the request to be a friend, Alice is added as a friend (which is essentially making Alice follow Bob, since the definition of a friend in Colony is either a follower or follows another user) class Request include DataMapper::Resource property :id, Serial property :text, Text property :created_at, DateTime belongs_to :from, :class_name => User, :child_key => [:from_id] belongs_to :user def approve self.user.add_friend(self.from) endend Message Messages in Colony are private messages that are sent between users of Colony. As a result, messages sent or received are not tracked as activities in the user's activity feed. class Message include DataMapper::Resource property :id, Serial property :subject, String property :text, Text property :created_at, DateTime property :read, Boolean, :default => false property :thread, Integer belongs_to :sender, :class_name => 'User', :child_key => [:user_id] belongs_to :recipient, :class_name => 'User', :child_key => [:recipient_id] end A message must have a sender and a recipient, both of which are users. has n, :sent_messages, :class_name => 'Message', :child_key => [:user_id]has n, :received_messages, :class_name => 'Message', :child_key => [:recipient_id] The read property tells us if the message has been read by the recipient, while the thread property tells us how to group messages together for display. Album An activity is logged, each time an album is created. class Album include DataMapper::Resource property :id, Serial property :name, String, :length => 255 property :description, Text property :created_at, DateTime belongs_to :user has n, :photos belongs_to :cover_photo, :class_name => 'Photo', :child_key => [:cover_photo_id] after :save, :add_activity def add_activity Activity.create(:user => user, :activity_type => 'album', :text => "<a href='/user/#{user.nickname}'>#{user.formatted_name}</a> created a new album <a href='/album/#{self.id}'>#{self.name}</a>") end end
Read more
  • 0
  • 0
  • 2431

article-image-trapping-errors-using-built-objects-javascript-testing
Packt
25 Aug 2010
6 min read
Save for later

Trapping Errors by Using Built-In Objects in JavaScript Testing

Packt
25 Aug 2010
6 min read
(For more resources on JavaScript, see here.) The Error object An Error is a generic exception, and it accepts an optional message that provides details of the exception. We can use the Error object by using the following syntax: new Error(message); // message can be a string or an integer Here's an example that shows the Error object in action. The source code for this example can be found in the file error-object.html. <html><head><script type="text/javascript">function factorial(x) { if(x == 0) { return 1; } else { return x * factorial(x-1); } } try { var a = prompt("Please enter a positive integer", ""); if(a < 0){ var error = new Error(1); alert(error.message); alert(error.name); throw error; } else if(isNaN(a)){ var error = new Error("it must be a number"); alert(error.message); alert(error.name); throw error; } var f = factorial(a); alert(a + "! = " + f); } catch (error) { if(error.message == 1) { alert("value cannot be negative"); } else if(error.message == "it must be a number") { alert("value must be a number"); } else throw error; } finally { alert("ok, all is done!"); } </script> </head> <body> </body> </html> You may have noticed that the structure of this code is similar to the previous examples, in which we demonstrated try, catch, finally, and throw. In this example, we have made use of what we have learned, and instead of throwing the error directly, we have used the Error object. I need you to focus on the code given above. Notice that we have used an integer and a string as the message argument for var error, namely new Error(1) and new Error("it must be a number"). Take note that we can make use of alert() to create a pop-up window to inform the user of the error that has occurred and the name of the error, which is Error, as it is an Error object. Similarly, we can make use of the message property to create program logic for the appropriate error message. It is important to see how the Error object works, as the following built-in objects, which we are going to learn about, work similarly to how we have seen for the Error object. (We might be able to show how we can use these errors in the console log.) The RangeError object A RangeError occurs when a number is out of its appropriate range. The syntax is similar to what we have seen for the Error object. Here's the syntax for RangeError: new RangeError(message); message can either be a string or an integer. <html><head><script type="text/javascript">try { var anArray = new Array(-1); // an array length must be positive}catch (error) { alert(error.message); alert(error.name);}finally { alert("ok, all is done!");}</script></head><body></body></html> We'll start with a simple example to show how this works. Check out the following code that can be found in the source code folder, in the file rangeerror.html: When you run this example, you should see an alert window informing you that the array is of an invalid length. After this alert window, you should receive another alert window telling you that The error is RangeError, as this is a RangeError object. If you look at the code carefully, you will see that I have deliberately created this error by giving a negative value to the array's length (array's length must be positive). The ReferenceError object A ReferenceError occurs when a variable, object, function, or array that you have referenced does not exist. The syntax is similar to what you have seen so far and it is as follows: new ReferenceError(message); message can either be a string or an integer. As this is pretty straightforward, I'll dive right into the next example. The code for the following example can be found in the source code folder, in the file referenceerror.html. <html><head><script type="text/javascript">try { x = y; // notice that y is not defined // an array length must be positive}catch (error) { alert(error); alert(error.message); alert(error.name);}finally { alert("ok, all is done!");}</script></head><body></body></html> Take note that y is not defined, and we are expecting to catch this error in the catch block. Now try the previous example in your Firefox browser. You should receive four alert windows regarding the errors, with each window giving you a different message. The messages are as follows: ReferenceError: y is not defined y is not defined ReferenceError ok, all is done If you are using Internet Explorer, you will receive slightly different messages. You will see the following messages: [object Error] message y is undefined TypeError ok, all is done The TypeError object A TypeError is thrown when we try to access a value that is of the wrong type. The syntax is as follows: new TypeError(message); // message can be a string or an integer and it is optional An example of TypeError is as follows: <html><head><script type="text/javascript">try { y = 1 var test = function weird() { var foo = "weird string"; } y = test.foo(); // foo is not a function}catch (error) { alert(error); alert(error.message); alert(error.name);}finally { alert("ok, all is done!");}</script></head><body></body></html> If you try running this code in Firefox, you should receive an alert box stating that it is a TypeError. This is because test.foo() is not a function, and this results in a TypeError. JavaScript is capable of finding out what kind of error has been caught. Similarly, you can use the traditional method of throwing your own TypeError(), by uncommenting the code. The following built-in objects are less used, so we'll just move through quickly with the syntax of the built-in objects.
Read more
  • 0
  • 0
  • 5505

article-image-troux-enterprise-architecture-managing-ea-function
Packt
25 Aug 2010
9 min read
Save for later

Troux Enterprise Architecture: Managing the EA function

Packt
25 Aug 2010
9 min read
(For more resources on Troux, see here.) Targeted charter Organizations need a mission statement and charter. What should the mission and charter be for EA? The answer to this question depends on how the CIO views the function and where the function resides on the maturity model. The CIO could believe that EA should be focused on setting standards and identifying cost reduction opportunities. Conversely, the CIO could believe the function should focus on evaluation of emerging technologies and innovation. These two extremes are polar opposites. Each would require a different staffing model and different success criteria. The leader of EA must understand how the CIO views the function, as well as what the culture of the business will accept. Are IT and the business familiar with top-down direction, or does the company normally follow a consensus style of management? Is there a market leadership mentality or is the company a fast follower regarding technical innovation? To run a successful EA operation, the head of Enterprise Architecture needs to understand these parameters and factor them into the overall direction of the department. The following diagram illustrates finding the correct position between the two extremes of being focused on standards or innovation: Using standards to enforce polices on a culture that normally works through consensus will not work very well. Also, why focus resources on developing a business strategy or evaluating emerging technology if the company is totally focused on the next quarter's financial results? Sometimes, with the appropriate support from the CIO and other upper management, EA can become the change agent to encourage long-term planning. If a company has been too focused on tactics, EA can be the only department in IT that has the time and resources available to evaluate emerging solutions. The leader of the architecture function must understand the overall context in which the department resides. This understanding will help to develop the best structure for the department and hire people with the correct skill set. Let us look at the organization structure of the EA function. How large should the department be, where should the department report, and what does the organization structure look like? In most cases, there are also other areas within IT that perform what might be considered EA department responsibilities. How should the structure account for "domain architects" or "application architects" who do not report to the head of Enterprise Architecture? As usual, the answer to these questions is "it depends". The architecture department can be sized appropriately with an understanding of the overall role Enterprise Architecture plays within the broader scope of IT. If EA also runs the project management office (PMO) for IT, then the department is likely to be as large as fifty or more resources. In the case where the PMO resides outside of architecture, the architecture staffing level is normally between fifteen and thirty people. To be effective in a large enterprise, (five hundred or more applications development personnel) the EA department should be no smaller than about fifteen people. The following diagram provides a sample organization chart that assumes a balance is required between being focused on technical governance and IT strategy: The sample organization chart shows the balance between resources applied to tactical work and strategic work. The left side of the chart shows the teams focused on governance. Responsibilities include managing the ARB and maintaining standards and the architecture website. An architecture website is critical to maintaining awareness of the standards and best practices developed by the EA department. The sample organizational model assumes that a team of Solution Architects is centralized. These are experienced resources who help project teams with major initiatives that span the enterprise. These resources act like internal consultants and, therefore, must possess a broad spectrum of skills. Depending on the overall philosophy of the CIO, the Domain Architects may also be centralized. These are people with a high degree of experience within specific major technical domains. The domains match to the overall architectural framework of the enterprise and include platforms, software (including middleware), network, data, and security. These resources could also be decentralized into various applications development or engineering groups within IT. If Domain Architects are decentralized, at least two resources are needed within EA to ensure that each area is coordinated with the others across technical disciplines. If EA is responsible for evaluation of emerging technologies, then a team is needed to focus on execution of proof-of-architecture projects and productivity tool evaluations. A service can be created to manage various contracts and relationships with outside consulting agencies. These are typically companies focused on providing research, tracking IT advancements, and, in some cases, monitoring technology evolution within the company's industry. There are leaders (management) in each functional area within the architecture organization. As the resources under each area are limited, a good practice is to assume the leadership positions are also working positions. Depending on the overall culture of the company, the leadership positions could be Director- or Manager-level positions. In either case, these leaders must work with senior leaders across IT, the business, and outside vendors. For this reason, to be effective, they must be people with senior titles granted the authority to make important recommendations and decisions on a daily basis. In most companies, there is considerable debate about whether standards are set by the respective domain areas or by the EA department. The leader of EA, working with the CIO or CTO, must be flexible and able to adapt to the culture. If there is a need to centralize, then the architecture team must take steps to ensure there is buy-in for standards and ensure that governance processes are followed. This is done by building partnerships with the business and IT areas that control the allocation of funds to important projects. If the culture believes in decentralized standards management, then the head of architecture must ensure that there is one, and only one, official place where standards are documented and managed. The ARB, in this case, becomes the place where various opinions and viewpoints are worked out. However, it must be clear that the ARB is a function of Enterprise Architecture, and those that do not follow the collaborative review processes will not be able to move forward without obtaining a management consensus. Staffing the function Staffing the EA function is a challenge. To be effective, the group must have people who are respected for their technical knowledge and are able to communicate well using consensus and collaboration techniques. Finding people with the right combination of skills is difficult. Enterprise Architects may require higher salaries as compared to other staff within IT. Winning the battle with the human resources department about salaries and reporting levels within the corporate hierarchy is possible through the use of industry benchmarks. Requesting that jobs be evaluated against similar roles in the same industry will help make the point about what type of people are needed within the architecture department. People working in the EA department are different and here's why. In baseball, professional scouts rate prospects according to a scale on five different dimensions. Players that score high on all five are called "five tool players." These include hitting, hitting for power, running speed, throwing strength, and fielding. In evaluating resources for EA, there are also five major dimensions to consider. These include program management, software architecture, data architecture, network architecture, and platform architecture. As the following figure shows, an experience scale can be established for each dimension, yielding a complete picture of a candidate. People with the highest level of attainment across all five dimensions would be "five tool players". To be the most flexible in meeting the needs of the business and IT, the head of EA should strive for a good mix of resources covering the five dimensions. Resources who have achieved level 4 or level 5 across all of these would be the best candidates for the Solution Architect positions. These resources can do almost anything technical and are valuable across a wide array of enterprise-wide projects and initiatives. Resources who have mastered a particular dimension, such as data architecture or network architecture, are the best candidates for the Domain Architect positions. Software architecture is a broad dimension that includes software design, industry best practices, and middleware. Included within this area would be resources skilled in application development using various programming languages and design styles like object-oriented programming and SOA. As already seen, the Business Architect role spans all IT domains. The best candidates for Business Architecture need not be proficient in the five disciplines of IT architecture, but they will do a better job if they have a good awareness of what IT Architects do. Business Architects may be centralized and report into the EA function, or they may be decentralized across IT or even reside within business units. They are typically people with deep knowledge of business functions, business processes, and applications. Business Architects must be good communicators and have strong analytical abilities. They should be able to work without a great deal of supervision, be good at planning work, and can be trusted to deliver results per a schedule. Following are some job descriptions for these resources. They are provided as samples because each company will have its own unique set. Vice President/Director of Enterprise Architecture The Vice President/Director of Enterprise Architecture would normally have more than 10 or 15 years of experience depending on the circumstances of the organization. He or she would have experience with, and probably has mastered, all five of the key architecture skill set dimensions. The best resource is one with superior communication skills who is able to effect change across large and diverse organizations. The resource will also have experience within the industry in which the company competes. Leadership qualities are the most important aspect of this role, but having a technical background is also important. This person must be able to translate complex ideas, technology, and programs into language upper management can relate to. This person is a key influencer on technical decisions that affect the business on a long-term basis.
Read more
  • 0
  • 0
  • 4501
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime
article-image-new-microsoft-books
Packt
24 Aug 2010
1 min read
Save for later

New Microsoft Books

Packt
24 Aug 2010
1 min read
New Microsoft Books Published MDX with Microsoft SQL Server 2008 R2 Analysis Services Cookbook 80 recipes for enriching your Business Intelligence solutions with high-performance MDX calculations and flexible MDX queries Microsoft Windows Azure Development Cookbook Over 80 advanced recipes for developing scalable services with the Windows Azure platform
Read more
  • 0
  • 0
  • 1837

article-image-implementing-panels-drupal-6
Packt
23 Aug 2010
4 min read
Save for later

Implementing Panels in Drupal 6

Packt
23 Aug 2010
4 min read
(For more resources on Drupal, see here.) Introduction This is an article centered on building website looks with Panels. We will create a custom front page for a website and a node edit form with a Panel. We will also see the process of generating a node override within Panels and take a look at Mini panels. Making a new front page using Panels and Views (for dynamic content display) We will now create a recipe with Views and Panels to make a custom front page. Getting ready We will need to install Views as the module, if not done already. As the Views and Panels projects are both led by Earl Miles (merlinofchaos), the UIs are very similar. We will not discuss Views in detail as it is out of the scope of the article. To use this recipe, a basic knowledge of Views is required. We will use our recipe of fl exible layout as our start for this recipe. To make a better layout and a custom website, I recommend using adaptive themes (http://adaptivethemes.com/). Here, in this recipe, I have used that theme. The adaptive theme is a starter theme and it includes several custom panels. There is also a built-in support for skins, which helps to make theming a lot easier. We will be using adaptive themes in this recipe for demonstration and will change our administration view from Garland to adaptive theme. The adaptive themes add extra layouts as shown in the following screenshot. How to do it... Go to the Flexible layout recipe we created or you can create your own layout using the same recipe. Now, we will create Views to be included in our Panels layout. Assuming that Views is installed, go to Site building | Views. Add a View. In the View name, add storyblock1, and add a description of your choice. Select the Row style as Node. Put in Items to display as 3. In the Style, we can select Unformatted or Grid depending on how you want to display the nodes. I will use Grid. In the Sort criteria, put in Node: Post date asc and Node: Type asc. In Filters, we just want the posts promoted to the first page. Do a live preview. We will need to add display of the default view as Block, so that the View is available as a block, which we can select in our Panels. We can also put the views default output as a Panel pane, but using blocks as a display of the Views gives the "read more" links by default. In the direct View, we have to create it. Say, we create a block—storyblock1, as shown in the following screenshot: Now, we need to go to the Flexible Layouts UI, as a layout created by you. Go to the Content tab. Earlier, we had displayed a static block; now we will display a dynamic View. Disable earlier panes in the first static row. Select the gears in first static rows and select Add content | Miscellaneous. The custom view block will be here, as shown in the following screenshot. Select it. Save and preview. So, we have now integrated the dynamic View in one of our Panel panes. Let's add sample content to each region now. You can select your own content as you want on your front page, as shown in the following screenshot: Go to Site configuration | Site information. Chan ge the default home pages to the created Panels page. Your home page is now the custom Panel page. How it works... In this recipe, we implemented Panel panes with views and blocks to make a separate custom page and separate display for the existing content in the website.
Read more
  • 0
  • 0
  • 1829

article-image-upgrading-opencart
Packt
23 Aug 2010
3 min read
Save for later

Upgrading OpenCart

Packt
23 Aug 2010
3 min read
This article is suggested reading even for an experienced user. It will show us any possible problems that might occur while upgrading, so we can avoid them. Making backups of the current OpenCart system One thing we should certainly do is backup our files and database before starting any upgrade process. This will allow us to restore the OpenCart system if the upgrade fails and if we cannot solve the reason behind it. Time for action – backing up OpenCart files and database In this section, we will now learn how to back up the necessary files and database of the current OpenCart system before starting the upgrading processes. We will start with backing up database files. We have two choices to achieve this. The first method is easier and uses the built-in OpenCart module in the administration panel. We need to open the System | Backup / Restore menu. In this screen, we should be sure that all modules are selected. If not, click on the Select All link first. Then, we will need to click on the Backup button. A backup.sql file will be generated for us automatically. We will save the file on our local computer. The second method to backup OpenCart database is through the Backup Wizard on cPanel administration panel which most hosting services provide this as a standard management tool for their clients. If you have applied the first method which we have just seen, skip the following section to apply. Still, it is useful to learn about alternative Backup Wizard tool on cPanel. Let's open cPanel screen that our hosting services provided for us. Click on the Backup Wizard item under the Files section. On the next screen, click on the Backup button. We will click on the MySQL Databases button on the Select Partial Backup menu. We will right-click on our OpenCart database file backup and save it on our local computer by clicking on Save Link As. Let's return to the cPanel home screen and open File Manager under the Files menu. Let's browse into the web directory where our OpenCart store files are stored. Right-click on the directory and then Compress it. We will compress the whole OpenCart directory as a Zip Archive file. As we can see from the following screenshot, the compressed store.zip file resides on the web server. We can also optionally download the file to our local computer. What just happened? We have backed up our OpenCart database using cPanel. After this, we also backed up our OpenCart files as a compressed archive file using File Manager in cPanel.
Read more
  • 0
  • 0
  • 2238

Packt
20 Aug 2010
11 min read
Save for later

Adding Features to your Joomla! Form using ChronoForms

Packt
20 Aug 2010
11 min read
(For more resources on ChronoForms, see here.) Introduction We have so far mostly worked with fairly standard forms where the user is shown some inputs, enters some data, and the results are e-mailed and/or saved to a database table. Many forms are just like this, and some have other features added. These features can be of many different kinds and the recipes in this article are correspondingly a mixture. Some, like Adding a validated checkbox, change the way the form works. Others, like Signing up to a newsletter service change what happens after the form is submitted. While you can use these recipes as they are presented, they are just as useful as suggestions for ways to use ChronoForms to solve a wide range of user interactions on your site. Adding a validated checkbox Checkboxes are less often used on forms than most of the other elements and they have some slightly unusual behavior that we need to manage. ChronoForms will do a little to help us, but not everything that we need. In this recipe, we'll look at one of the most common applications—a stand alone checkbox that the user is asked to click to ensure that they've accepted some terms and conditions. We want to make sure that the form is not submitted unless the box is checked. Getting ready We'll just add one more element to our basic newsletter form. It's probably going to be best to recreate a new version of the form using the Form Wizard to make sure that we have a clean starting point. How to do it... In the Form Wizard, create a new form with two TextBox elements. In the Properties box, add the Labels "Name" and "Email" and the Field Names "name" and "email" respectively. Now drag in a CheckBox element. You'll see that ChronoForms inserts the element with three checkboxes and we only need one. In the Properties box remove the default values and type in "I agree". While you are there change the label to "Terms and Conditions". Lastly, we want to make sure that this box is checked so check the Validation | One Required checkbox and add "please confirm your agreement" in the Validation Message box. Apply the changes to the Properties. To complete the form add the Button element, then save your form, publish it, and view it in your browser. To test, click the Submit button without entering anything. You should find that the form does not submit and an error message is displayed. How it works... The only special thing to notice about this is that the validation we used was validate-one- required and not the more familiar required. Checkbox arrays, radio button groups, and select drop-downs will not work with the required option as they always have a value set, at least from the perspective of the JavaScript that is running the validation. There's more... Validating the checkbox server-side If the checkbox is really important to us, then we may want to confirm that it has been checked using the server-side validation box. We want to check and, if our box isn't checked, then create the error message. However, there is a little problem—an unchecked checkbox doesn't return anything at all, there is just no entry in the form results array. Joomla! has some functionality that will help us out though; the JRequest::getVar() function that we use to get the form results allows us to set a default value. If nothing is found in the form results, then the default value will be used instead. So we can add this code block to the server-side validation box: <?php $agree = JRequest::getString('check0[]', 'empty', 'post'); if ( $agree == 'empty' ) { return 'Please check the box to confirm your agreement'; } ?> Note: To test this, we need to remove the validate-one-required class from the input in the Form HTML. Now when we submit the empty form, we see the ChronoForms error message. Notice that the input name in the code snippet is check0[]. ChronoForms doesn't give you the option of setting the name of a checkbox element in the Form Wizard | Properties box. It assigns a check0, check1, and so on value for you. (You can edit this in the Form Editor if you like.) And because checkboxes often come in arrays of several linked boxes with the same name, ChronoForms also adds the [] to create an array name. If this isn't done then only the value of the last checked box will be returned. Locking the Submit button until the box is checked If we want to make the point about terms and conditions even more strongly then we can add some JavaScript to the form to disable the Submit button until the box is checked. We need to make one change to the Form HTML to make this task a little easier. ChronoForms does not add ID attributes to the Submit button input; so open the form in the Form Editor, find the line near the end of the Form HTML and alter it to read: <input value="Submit" name="submit" id='submit' type="submit" /> Now add the following snippet into the Form JavaScript box: // stop the code executing // until the page is loaded in the browser window.addEvent('load', function() { // function to enable and disable the submit button function agree() { if ( $('check00').checked == true ) { $('submit').disabled = false; } else { $('submit').disabled = true; } }; // disable the submit button on load $('submit').disabled = true; //execute the function when the checkbox is clicked $('check00').addEvent('click', agree); }); Apply or save the form and view it in your browser. Now as you tick or untick the checkbox, the submit button will be enabled and disabled. This is a simple example of adding a custom script to a form to add a useful feature. If you are reasonably competent in JavaScript, you will find that there is quite a lot more that you can do. There are different styles of laying out both JavaScript and PHP and sometimes fierce debates about where line breaks and spaces should go. We've adopted a style here that is hopefully fairly clear, reasonably compact, and more or less the same for both JavaScript and PHP. If it's not the style you are accustomed to, then we're sorry. Adding an "other" box to a drop-down Drop-downs are a valuable way of offering a list of choices to your user to select from. And sometimes it just isn't possible to make the list complete, there's always another option that someone will want to add. So we add an "other" option to the drop-down. But that tells us nothing, so we need to add an input to tell us what "other" means here. Getting ready We'll just add one more element to our basic newsletter form. We haven't used a drop-down before but it is very similar to the check-box element from the previous recipe. How to do it... Use the Form Wizard to create a form with two TextBox elements, a DropDown element, and a Button element. The changes to make in the element are: Add "I heard from" in the Label Change the Field Name to "hearabout" Add some options to the Options box—"Google", "Newspaper", "Friend", and "Other" Leave the Add Choose Option box checked and leave Choose Option in the Choose Option Text box. Apply the Properties box. Make any other changes you need to the form elements; then save the form, publish it, and view it in your browser. Notice that as well as the four options we added the Choose Option entry is at the top of the list. That comes from the checkbox and text field that we left with their default values. It's important to have a "null" option like this in a drop-down for two reasons. First, so that it is obvious to a user that no choice has been made. Otherwise it's very easy for them to leave the first option showing and this value—Google in this case—will be returned by default. Second, so that we can validate select-one-required if necessary. The "null" option has no value set and so can be detected by validation script. Now we just need one more text box to collect details if Other is selected. Open the form in the Wizard Edit; add one more TextBox element after the DropDown element. Give it the Label please add details and the name "other". Even though we set the name to "other", ChronoForms will have left the input ID attribute as text_4 or something similar. Open the Form in the Form Editor and change the ID to "other" as well. The same is true of the drop-down. The ID there is select_2, change that to hearabout. Now we need a script snippet to enable and disable the "other" text box if the Other option is selected in the drop-down. Here's the code to put in the Form JavaScript box: window.addEvent('domready', function() { $('hearabout').addEvent('change', function() { if ($('hearabout').value == 'Other' ) { $('other').disabled = false; } else { $('other').disabled = true; } }); $('other').disabled = true; }); This is very similar to the code in the last recipe except that it's been condensed a little more by merging the function directly into the addEvent(). When you view the form you will see that the text box for please add details is grayed out and blocked until you select Other in the drop-down. Make sure that you don't make the please add details input required. It's an easy mistake to make but it stops the form working correctly as you have to select Other in the drop-down to be able to submit it. How it works Once again, this is a little JavaScript that is checking for changes in one part of the form in order to alter the display of another part of the form. There's more... Hiding the whole input It looks a little untidy to have the disabled box showing on the form when it is not required. Let's change the script a little to hide and unhide the input instead of disabling and enabling it. To make this work we need a way of recognizing the input together with its label. We could deal with both separately, but let's make our lives simpler. In the Form Editor, open the Form HTML box and look near the end for the other input block: <div class="form_item"> <div class="form_element cf_textbox"> <label class="cf_label" style="width: 150px;">please add details</label> <input class="cf_inputbox" maxlength="150" size="30" title="" id="other" name="other" type="text" /> </div> <div class="cfclear">&nbsp;</div> </div> That <div class="form_element cf_textbox"> looks like it is just what we need so let's add an ID attribute to make it visible to the JavaScript:   <div class="form_element cf_textbox" id="other_input"> Now we'll modify our script snippet to use this: window.addEvent('domready', function() { $('hearabout').addEvent('change', function() { if ($('hearabout').value == 'Other' ) { $('other_input').setStyle('display', 'block'); } else { $('other_input').setStyle('display', 'none'); } }); // initialise the display if ($('hearabout').value == 'Other' ) { $('other_input').setStyle('display', 'block'); } else { $('other_input').setStyle('display', 'none'); } }); Apply or save the form and view it in your browser. Now the input is invisible see the following screenshot labeled 1 until you select Other from the drop-down see the following screenshot labeled 2. The disadvantage of this approach is that the form can appear to "jump around" as extra fields appear. You can overcome this with a little thought, for example by leaving an empty space. See also In some of the script here we are using shortcuts from the MooTools JavaScript framework. Version 1.1 of MooTools is installed with Joomla! 1.5 and is usually loaded by ChronoForms. You can find the documentation for MooTools v1.1 at http://docs111.mootools.net/ Version 1.1 is not the latest version of MooTools and many of the more recent MooTools script will not run with the earlier version. Joomla 1.6 is expected to use the latest release.
Read more
  • 0
  • 0
  • 7986
article-image-getting-started-drupal-6-panels
Packt
20 Aug 2010
7 min read
Save for later

Getting Started with Drupal 6 Panels

Packt
20 Aug 2010
7 min read
(For more resources on Drupal, see here.) Introduction Drupal Panels are distinct pieces of rectangular content that create a custom layout of the page—where different Panels are more visible and presentable as a structured web page. Panels is a freely-distributed, open source module developed for Drupal 6. With Panels, you can display various content in a customizable grid layout on one page. Each page created by Panels can include a unique structure and content. Using the drag-and-drop user interface, you select a design for the layout and position various kinds of content (or add custom content) within that layout. Panels integrates with other Drupal modules like Views and CCK. Permissions, deciding which users can view which elements, are also integrated into Panels. You can even override system pages such as the display of keywords (taxonomy) and individual content pages (nodes). In the next section, we will see what the Panels can actually do, as defined on drupal.org: http://drupal.org/project/panels. Basically, Panels will help you to arrange a large content on a single page. While Panels can be used to arrange a lot of content on a single page, it is equally useful for small amounts of related content and/or teasers. Panels support styles, which control how individual content's panes, regions within a Panel, and the entire Panels will be rendered. While Panels ship with few styles, styles can be provided as plugins by modules, as well as by themes: The User Interface is nice for visually designing a layout, but a real HTML guru doesn't want the somewhat weighty HTML that this will create. Modules and themes can provide custom layouts that can fit a designer's exacting specifications, but still allow the site builders to place content wherever they like. Panels include a pluggable caching mechanism: a single cache type is included, the 'simple' cache, which is time-based. Since most sites have very specific caching needs based upon the content and traffic patterns, this system was designed to let sites that need to devise their own triggers for cache clearing and implement plugins that will work with Panels. A cache mechanism can be defined for each pane or region with the Panel page. Simple caching is a time-based cache. This is a hard limit, and once cached, it will remain that way until the time limit expires. If "arguments" are selected, this content will be cached per individual argument to the entire display; if "contexts" are selected, this content will be cached per unique context in the pane or display; if "neither", there will be only one cache for this pane. Panels can also be cached as a whole, meaning the entire output of the Panels can be cached, or individual content panes that are heavy, like large views, can be cached. Panels can be integrated with the Drupal module Organic Groups through the #og_Panels module to allow individual groups to have their own customized layouts. Panels integrates Views to allow administrators to add any view as content. We will discuss Module Integration in the coming recipes. Shown in the previous screenshot is one of the example sites that use Panels 3 for their home page (http://concernfast.org). The home page is built using a custom Panels 3 layout with a couple of dedicated Content types that are used to build nodes to drop into the various Panels areas. The case study can be found at: http://drupal.org/node/629860. Panels arrange your site content into an easy navigational pattern, which can be clearly seen in the following screenshot. There are several terms often used within Panels that administrators should become familiar with as we will be using the same throughout the recipes. The common terms in Panels are: Panels page: The page that will display your Panels. This could be the front page of a site, a news page, and so on. These pages are given a path just like any other node. Panels: A container for content. A Panel can have several pieces of content within it, and can be styled. Pane: A unit of content in a Panel. This can be a node, view, arbitrary HTML code, and so on. Panes can be shifted up and down within a Panel and moved from one Panel to another. Layout: Provides a pre-defined collection of Panels that you can select from. A layout might have two columns, a header, footer, or three columns in the middle, or even seven Panels stacked like bricks. Setting up Ctools and Panels We will now set up Ctools, which is required for Panels. "Chaos tools" is a centralized library, which is used by the most powerful modules of Drupal Panels and views. Most functions in Panels are inherited from the chaos library. Getting ready Download the Panels modules for the Drupal website: http://drupal.org/project/Panels You would need Ctools as a dependency module, which can be downloaded from: http://drupal.org/project/ctools How to do it... Upload both the files, Ctools and Panels, into /sites/all/modules. It is always a best practice to keep the installed modules separate from the "core" (the files that install with Drupal) into the /sites/all/modules folder. This makes it easy to upgrade the modules at a later stage when your site becomes complex and has too many modules. Go to the modules page in admin (Admin| Site Building | Modules) and enable Ctools, then enable Panels. Go to permissions (Admin | User Management | Permissions) and give site builders permission to use Panels. Enable the Page manager module in the Chaos tools suite. This module enables the page manager for Panels. To integrate views with Panels, enable the Views content panes module too. We will discuss more about views later on. Enable Panels and set the permissions. You will need to enable Panel nodes, the Panel module, and Mini panels too (as shown in the following screenshot) as we will use the same in our advanced recipes. Go to administer by module in the Site building | Modules. Here, you find the Panels User Interface. There is more Chaos tools suite includes the following tools that form the base of the Panels module. You do not need to go into the details of it to use Panels but it is good to know what it includes. This is the powerhouse that makes Panels the most efficient tool to design complex layouts: Plugins—tools to make it easy for modules to let other modules implement plugins from .inc files. Exportables—tools to make it easier for modules to have objects that live in database or live in code, such as 'default views'. AJAX responder—tools to make it easier for the server to handle AJAX requests and tell the client what to do with them. Form tools—tools to make it easier for forms to deal with AJAX. Object caching—tool to make it easier to edit an object across multiple page requests and cache the editing work. Contexts—the notion of wrapping objects in a unified wrapper and providing an API to create and accept these contexts as input. Modal dialog—tool to make it simple to put a form in a modal dialog. Dependent—a simple form widget to make form items appear and disappear based upon the selections in another item. Content—pluggable Content types used as panes in Panels and other modules like Dashboard. Form wizard—an API to make multi-step forms much easier. CSS tools—tools to cache and sanitize CSS easily to make user input CSS safe. How it works... Now, we have our Panels UI ready to generate layouts. We will discuss each of them in the following recipes. The Panels dashboard will help you to generate the layouts for Drupal with ease.
Read more
  • 0
  • 0
  • 2432

article-image-enterprise-instant-messaging-using-sametime-ibm-lotus-notes-85
Packt
19 Aug 2010
6 min read
Save for later

Enterprise Instant Messaging using Sametime in IBM Lotus Notes 8.5

Packt
19 Aug 2010
6 min read
(For more resources on IBM, see here.) Sametime is fantastic for corporations—both large and small. Many times we walk the corridors checking to see if someone is in their office. Now with Sametime we can see if they are online, offline, or unavailable; we can even have Sametime alert us when someone logs on or becomes available. Many corporations are encouraging their employees to work from home. This is where Sametime comes in handy—it allows us to communicate as though we were in the office and we can save our chats if important business decisions were discussed during a chat. It is also great for corporations that have branches or outlets in different regions. Being able to get quick responses to questions is important to businesses, and Sametime facilitates instant communication. What is Sametime Sametime gives us the ability to chat or send an instant message to others in a secure manner. Have you ever sent an e-mail and then wondered when the person will be able to respond? Do you get too many e-mails? Does listening to voicemail drive you nuts? If your question to all these questions is yes, then Sametime is the answer. Sametime allows us to first check if the person is available online, this is called presence awareness. Then if the person is available, we can start a chat with that person to see if he/she responds. Many people might say, why not just give them a call? Well, without Sametime you can't tell if the person is available—they could be in a meeting or they could be on the phone, plus there may be a cost to the call. So, being able to chat with a person using Sametime will typically give us instant results. Some other great features of Sametime are: It allows us to chat with two or more people at the same time, referred to as multi-way chat. There is an out of the box integration supported with e-mail and productivity applications such as Microsoft Office, Microsoft Outlook, Microsoft SharePoint, and IBM Lotus Notes. It has the ability to add or show rich text, timestamps, perform a spell check, and use emoticons in a chat session. Sametime also has the ability to search for contacts and display their details. It saves chat history so that one has a record of the conversation if required. Sametime helps manage our contact list by being able to sort, show short names, or show online contacts only. Sametime is included when we purchase Lotus Notes; however, some companies extend their license to include extra functionality. The following are the features of the standard and advanced versions, but be aware that there are more versions available. The license that is included with Lotus Notes is referred to as "Limited Use". Standard version: Built-in VoIP and point-to-point video Ability to transfer files via Sametime, and create, capture, and send screenshots Location awareness that automatically determines whether one is working from home or the office, and others can see this in their business card Contact information that can show photos and details of contacts when we float over their name Managed interoperability with supported public IM networks such as AOL The ability to conduct web conferencing, allowing us to start online meetings and share presentations Integration with supported audio, video, and telephony systems Advanced version: The ability to search for experts and answers, even when one doesn't know who to ask The ability to capture and reuse shared knowledge, reducing the burden on subject matter experts and on our help desk Provides a forum for teams to share information in real time Helps in speed communication by instantly sharing our screen with our co-workers for document review or clarifications In a company, Sametime might only have the ability to see the online status of people (presence awareness) and the ability to chat. For others, they may be able to chat and conduct online meetings. If one has the advanced version, then he/she may be able to use Sametime in a much more feature-rich way. In this article, we will focus on presence awareness and chat capabilities. To learn more about the standard, advanced, and other versions of Sametime, please visit the Lotus website at http://www.ibm.com/sametime The following is what the Sametime panel looks like when opened in sidebar: The Sametime panel has many options available that we will discuss throughout this article. To see menu options, click the menu icon to the right of Sametime Contacts as shown in the following screenshot. We can also view the menu by selecting Tools | Sametime from the Notes' client menu. If we cannot see the Sametime panel in the sidebar, we also have the option to select View|Right Sidebar Panels|Sametime Contacts, and click Sametime Contacts. Many people like to leave the Day-At-A-Glance open in their sidebar, so that we can see our Sametime contacts' select the menu option and then Open in New Window.This will float the Sametime contacts for easy access. How to use Sametime We will now explore how to use Sametime including chatting, presence awareness, and setting preferences. However, before we can use Sametime, we must fist log in by providing our username and password—this is part of the security that Sametime offers. This authenticates us with our organization and then chat transcripts are encrypted, which means no one else can read or access them. There are two ways we can log in: Clicking the Log In option on the Sametime panel if available. Selecting the Sametime icon and then select Log In from the menu. When we log in, our current status will default to available; however, there are other status options available for us to select from. Now that we are logged in, we will be able to see the availability of others. Understanding availability status Availability status icons appear next to people's names in Sametime, in our sidebar, inbox, contacts, and any Lotus Notes applications that have been Sametime enabled. The following screenshot shows the Sametime contacts in the sidebar: These icons indicate who is online, who are available to chat, and so on. Others in our company can also see our current status, so the first thing we will look at is how to change our status. We will need to complete the following steps: Click , situated in the top left-hand corner of the Sametime sidebar panel. Select status from the available choices; current selected status is I am Available. Each status has a particular icon; the following table describes each icon: We can set Sametime to change your status automatically, which is a good option, by completing the following steps: Select File | Preferences | Sametime | Auto-Status Changes. Check the situation in which we want our availability status to change. An excellent option is Meetings scheduled in my calendar; our status will automatically be changed when we are in meetings. Next, select preferred choices for Keyboard and mouse inactivity. Click Apply and then OK. Now that we know how to work with the different statuses, we should learn how to add contacts.
Read more
  • 0
  • 0
  • 3800

article-image-mail-basics-ibm-lotus-notes-85
Packt
19 Aug 2010
6 min read
Save for later

Mail Basics in IBM Lotus Notes 8.5

Packt
19 Aug 2010
6 min read
(For more resources on IBM, see here.) Accessing mail in Lotus Notes The first step in exploring mail is to open mail in Lotus Notes. There are a couple of ways that we can open mail: First, from the Home page by clicking the Mail icon as in the following screenshot. If we click the New button, it will create a new message. Also, by clicking Open and selecting Mail from the list. Creating and replying to messages In the following sections we will discuss how to create and reply to messages including reviewing message actions including setting delivery options. Creating a message Once we have opened mail, we can create a message by clicking on the New button and then selecting Message as shown next. As we can see from the message drop down list, there are other options available such as Meeting, Contact, and so on that we can create. Another way to create a message is by using the keyboard shortcut Ctrl+M. This can be done from anywhere within Lotus Notes, not just when we have mail opened—for example, we can create a message when we are in our Calendar, from within Contacts, or from the Home page using the Ctrl+M option. Message actions Now that we have created a message, we will explore some of the message actions. Along the top of the message, we can see buttons that enable us to do certain things. The following is a screenshot of the available options. We will briefly explore each of these options. Send: This speaks for itself; when clicked the message is sent! Send and File…: This is an excellent option when sending messages, as it allows us to not only send the message but also to file the message into our folders at the same time. When we click Send and File…, we will see the Folders dialog box with all our personal folders available. The following is a screenshot of the Folders dialog box that appears when we select the Send and File option. We would select the folder we want to file the message into and then click either the OK button or press the Enter key. The message will be filed in the folder; it will also be automatically filed into Sent and All Documents. Note that this does not mean we have three copies of the message filed in the three locations. There is only the one copy of the message in our personal folder; Sent and All Documents. This means if we delete the message from our personal folder, it will be deleted from the Sent and All Documents. When the Folders dialog box opens, if we know the name of the folder, we can start typing the folder name and that folder will be highlighted. Then if we press the Enter key, the message will be filed into that folder. Typically this is a quicker option than scrolling, especially if we have several folders. When you type the folder name you can see what you have typed in the Status bar, you can delete what you have typed if you have made a typing error. Save as Draft: This option saves our message into the Drafts folder. Delivery Options: Include options such as mood stamps and prevent copying. Flag: We can flag a message before sending it. Attachment: Clicking this icon will allow us to add an attachment to our message. Note that we can also drag an attachment into the body of the memo from Windows Explorer. Display: When we click on this button, we can see further options regarding how we want our messages to be displayed. We can select if we want to show the BCC field, Additional Mail Options, or Sender Information. The following is a screenshot of what we can see when we enable the Additional Mail Options option: High Importance is indicated to the sender by a red exclamation mark. Return receipt sends us a notification when the recipient/s have read or previewed the message. Sign adds an electronic signature to the message to ensure it has not been tampered with. Encrypt marks the message secret and can be read by only those whose name appears in the To, CC, and BCC fields. Mark Subject Confidential prepends "Mark Subject Confidential" to the subject field. More: This is the last message action, from here we can access Preferences…, Out of Office..., and so on as shown in the screenshot. Delivery options When we click the Delivery Options button in a new message, a dialog box opens with two tabs. Basic tab: Note the difference between Return receipt and Delivery report—the Return receipt option sends us notification when the person has read or previewed the message, whereas the Delivery Report option tells us when the message failed to reach the recipient, which is the default option Only on failure. Other options available are Confirm delivery or Trace entire path; the later option shows us the server route taken to deliver the message. Take the time to check out the Mood Stamps. I prefer adding the Good Job mood stamp to a message when I am congratulating someone. I often use the Confident mood stamp when I am sending a sensitive message. I will also select the Encrypt option that allows only those in the To, Cc, and Bcc fields to read it as well as Prevent copying which prevents people from forwarding, printing, copying to the clipboard and replying with history. Combining these options ensures the message is kept secure. The signing option adds digital signature to the message to confirm to the recipient the authenticity of the individual who has sent the mail. Note that all three of these options typically work only for a message sent within our organization and may not be applied to messages sent to people external to us such as someone at another company. Advanced tab: On the Advanced tab, there are options that allow us to add a Please reply by date. We can also select that replies to the memo go to another person or several other people. We can also add our name. Some organizations have shared mail files such as Sales where messages sent to sales at the company name will go into a central mail file. It is preferable to add those addresses, along with my own, to the Replies to this memo should be addressed to field so that those we work with are kept in the loop with particular communications.
Read more
  • 0
  • 0
  • 5449
article-image-feeds-ibm-lotus-notes-85
Packt
19 Aug 2010
5 min read
Save for later

Feeds in IBM Lotus Notes 8.5

Packt
19 Aug 2010
5 min read
(For more resources on IBM, see here.) Adding feeds A web feed is also known as RSS Feed. RSS stands for Really Simple Syndication and provides people with frequently updated content from websites. Content distributors syndicate a web feed, thereby allowing users to subscribe to it. Typically, feeds provide people with a summary of any recently added information or content such as a news headlines or blog entries to a website. Most often there are several sites that we want to subscribe to and there are tools that allow us to subscribe to these websites and have those feeds come into one place. Such a tool or software is known as a feed reader or aggregator. Many companies including news-related sites, blog sites, and many government and corporate sites distribute their content as web feeds. To know if a website is enabled for feed subscriptions, look for the feeds icon. The examples below can be placed anywhere on the website, however, typically we will see them placed somewhere on the first page. Often we can select what we want to subscribe to—for example, if it is a blog website, then we may be able to subscribe to the content or the comments that people make; on the other hand, if it is a news website, then we can select if we want content on sports or business. When we enable our subscription, we select how often we want to be updated and how long we want to keep the information. We will look into this in more detail further on in the article. Feeds sidebar panel Feeds can be accessed and managed from within the Lotus Notes sidebar(Details about sidebar is out of the scope of this article).The following is a screenshot of the Lotus Notes client with the Feeds sidebar expanded: If we can't see the Feeds sidebar panel, select View | Right Sidebar Panel and select Feeds. The Feeds panel can be collapsed by clicking click on Feeds in the sidebar. If we click on another panel in the sidebar such as the Day-At-A-Glance, then Feeds will close and we will see Day-At-A-Glance panel expanded in the sidebar. If we want to display our feeds separately, we can select Open in New Window when we right-click the Feeds option in the panel. Indentifying feed-enabled websites First, we need to identify if the website we are visiting has enabled syndication of its content (the fancy way of saying you can subscribe to it). We can tell if a website or blog syndicates its content by the feed icons displayed on the site, usually on the front page. We may also see the feed icon in the navigation toolbar of our browser. The following is an example of a web blog by Ed Brill, who is the Director of Product Management at IBM Lotus Software: The following is an example of a news website, USA Today: Both of these websites allow us to subscribe using feeds. Alternatively, on the USA Today website, we also see an area at the bottom of the front page that gives choices for subscriptions—the RSS option is circled in red. Once we have identified a website that is RSS enabled, there are a number of ways to add it to our Lotus Notes feed reader. Adding feeds to Lotus Notes Let's use the USA Today website as an example. There are a three different ways we can add feeds to Lotus Notes. Click on the RSS icon which, in the case of USA Today, is available on the first page of their website. Add the feed using any of the following techniques: Drag the RSS icon to the area where feeds are listed in our Feeds sidebar panel (make sure you hold your left mouse button down). This will open the Add New Subscription dialog box in Lotus Notes. Rather than dragging the RSS icon, this time click on it. This will take us to another web page. Select the URL on that web page and copy it to the clip board. Then go to Lotus Notes and select the Subscribe to Feed button in the Feeds sidebar panel. The Add New Subscription dialog box will now appear. Paste the URL into the space provided and then click the Go button. We can select our preferred options from within the Add New Subscription dialog box such as: Which feeds we want to subscribe to if it's a multiple feed name—for example, the selected feed name in the following screenshot is Top Headlines, which I would change to USA Today Top Headlines. How often to check for updates. How long to keep entries. Once we have selected all our choices, click the OK button. This will close the Add New Subscription dialog box and add that feed to the Feeds sidebar panel. Once we have added a subscription, we are given a choice as to how often we want the feeds to be updated and how long to keep entries for. The choices available in the Check for Updates drop-down list are: Every minute Every 10 or 30 minutes Every hour (default) Every 2, 4 or 8 hours Every day Once a week Manual (only check for updates manually) The choices for Keep entries for are: 1 day 1 week (default) 2 weeks 1 month 2 months Forever (only delete entries manually)
Read more
  • 0
  • 0
  • 4011

article-image-advanced-effects-using-blender-particle-system
Packt
18 Aug 2010
6 min read
Save for later

Advanced Effects using Blender Particle System

Packt
18 Aug 2010
6 min read
(For more resources on Blender, see here.) The list above might be a bit daunting to some users but don't worry, I will discuss as much as I could (and bear with me when I ramble a lot) and hopefully I'll succeed in imbibing as much information as possible so when you're done reading this, you're proud to say: “I know Particle System!”, just like how Neo said in the Matrix: “I know Kung-Fu”. Unlike the previous articles that I've written before where I solely used one version of Blender through the entirety of the process, this time we might switch between the legacy Blender 2.4* and the recently-developed Blender 2.5*. The reason for this is that some Particle System features that we have been happily using in Blender 2.4* isn't merged yet in Blender 2.5*, making it unusable for the moment. I guess that is reasonable enough since Blender 2.5* is still undergoing heavy development and is still in beta stage. But who knows, maybe during this time of writing, it is already being developed or already is. So in line with that, here are the basic requirements for you to get going: Blender 2.49b (http://www.blender.org/download/get-blender/) Blender 2.53 (http://www.blender.org/development/release-logs/blender-250/) Basic Blender Particle System Knowledge (refer to http://www.packtpub.com/article/getting-started-with-blender-particle-system-1 for some info) lots and lots of patience! And just a bonus, we decided to provide you with the .blend files for all of our examples illustrated here. So hop on! Disintegration Effect The disintegration effect has been a common and very popular visual effect seen in feature movies, advertisements, and simply an eye candy. Often, it starts by having an object in its original and full form then after a while it will dissipate and disappear as though it was now made of dust. You can see this effect in one of the tests I did before here: http://vimeo.com/6763010. Much of the inspiration came from Daniel (aka NionsChannel in Youtube) who has really some nice effects on his list. The basic requirements for achieving this kind of effect are: a suitable particle system, highly subdivided mesh, and a force field. With that said, let's go ahead and start tinkering, shall we? Fire up Blender 2.49b and delete the default Cube (if any). (Move the mouse over the image to enlarge it.) (Deleting the Default Cube) Next, add or model the object of your choice. For purposes of this tutorial, let's add a simple UV Sphere with 256 Segments and 256 Rings, however, if your machine couldn't handle the high subdivision levels, you can lower it down to your liking. NOTE: The higher number of subdivisions you set, the finer and the more seamless the “shards” will be. Additionally, you can always go to Edit mode and press W > Subdivide to subdivide your mesh accordingly or adding a Subsurf modifier and applying it afterwards. The higher number of subdivisions you set, the finer and the more seamless the “shards” will be. Additionally, you can always go to Edit mode and press W > Subdivide to subdivide your mesh accordingly or adding a Subsurf modifier and applying it afterwards. (Adding a UV Sphere) (Highly Subdivided UV Sphere) After the UV Sphere has been added, proceed to Edit Mode and check over at the header the amount of faces it has. We'll use this as a base for the amount of particles that we'll be adding later on for the actual simulation. (UV Sphere Face Count) While in Edit Mode and all the vertices selected, press W then choose Set Smooth to smooth out the geometry shading. Now go back to Object Mode and proceed to Object (F7) in the Buttons Window then on the Particle Buttons, then click on Add New under Particle System tab to add a new particle system. (Adding a New Particle System) Rename the just-added particle system to something more relevant like “disintegration”. Then on the Amount input, we'll be changing the default 1000 to the number of faces our UV Sphere currently has (that's the reason we checked a while back in edit mode). So in this case, type in 65536. This will then correspond to one particle is equal to one face of our uv sphere. Next, change the End value to something shorter than 100 which is default. Let's try 40 for this example, which means all of the 65536 particles will be emitted within 40 frames. Basing from the default 25 frames per second rate, this would mean all those particles will be emitted in less than 2 seconds, which is what we want for this. Next is the Life value which we should be set to something longer as compared to the default 50 which is a little bit too early for our simulation. Let's set Life to 150; this will make our particles stay in our simulation area longer and not disappear earlier than expected. Under “Emit From:” panel, enable Random and Even then leave the other defaults as they are. Then finally, alter the values in the Physics tab and see which ones you are satisfied with. Check the screenshot below for some reference. (Particle System Settings) The next part is the icing on the cake, where we'll be adding a force field to generate the particle system's motion as though it was affected by real world effects like wind, turbulence, etc. With your cursor centered on your UV Sphere, add an Empty, name it “force”, and make sure the object rotation is cleared (ALT R) such that the local z-axis is oriented on the world z-axis. The UV Sphere and the Empty (“force”) should be in the same layer for the following effect to work. (Empty “force” Added) After adding our Empty object, we need to tell Blender how this object will affect our particle system. We'll do this by adding force values to this object. Forces in Blender act as external effectors for physics systems, which includes our particle system. You'll see what I mean in a while. Let's select the UV Sphere object and add a new Material Datablock to the object. (Adding a New Material to the Sphere) After adding a new material datablock, you can go ahead and tweak the material and shader settings the way you want to. Just like how I did mine (see screenshot): (Adding Material to the Sphere) With the Sphere still selected, head over to the Texture buttons under Shading (F5) and add a new texture slot. (Adding a New Texture) Next, choose Clouds as the Texture Type, increase the Noise Size and Noise Depth accordingly and just leave the Noise Basis to the default Blender Original, this will ensure a better distinction for the form that our particle system will exhibit later on. And the last but not the least, increase the Contrast of the texture, which will exaggerate the shape of our particle form later on. (Cloud Texture Settings)
Read more
  • 0
  • 0
  • 6845
Modal Close icon
Modal Close icon