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
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials - CMS & E-Commerce

830 Articles
article-image-customizing-look-and-feel-uag
Packt
22 Feb 2012
8 min read
Save for later

Customizing Look and Feel of UAG

Packt
22 Feb 2012
8 min read
(For more resources on Microsoft Forefront UAG, see here.) Honey, I wouldn't change a thing! We'll save the flattery for our spouses, and start by examining some key areas of interest what you might want and be able to change on a UAG implementation. Typically, the end user interface is comprised of the following: The Endpoint Components Installation page The Endpoint Detection page The Login page The Portal Frame The Portal page The Credentials Management page The Error pages There is also a Web Monitor, but it is typically only used by the administrator, so we won't delve into that. The UAG management console itself and the SSL-VPN/SSTP client-component user interface are also visual, but they are compiled code, so there's not much that can be done there. The elements of these pages that you might want to adjust are the graphics, layout, and text strings. Altering a piece of HTML or editing a GIF in Photoshop to make it look different may sound trivial, but there's actually more to it than that, and the supportability of your changes should definitely be questioned on every count. You wouldn't want your changes to disappear upon the next update to UAG, would you? Nor would you look the page to suddenly become all crooked because someone decided that he wants the RDP icon to have an animation from the Smurfs. The UI pages Anyone familiar with UAG will know of its folder structure and the many files that make up the code and logic that is applied throughout. For those less acquainted however, we'll start with the two most important folders you need to know—InternalSite and PortalHomePage. InternalSite contains pages that are displayed to the user as part of the login and logout process, as well as various error pages. PortalHomePage contains the files that are a part of the portal itself, shown to the user after logging in. The portal layout comes in three different flavors, depending on the client that is accessing it. The most common one is the Regular portal, which happens to be the more polished version of the three, shown to all computers. The second is the Premium portal, which is a scaled-down version designed for phones that have advanced graphic capabilities, such as Windows Mobile phones. The third is the Limited portal, which is a text-based version of the portal, shown to phones that have limited or no graphic capabilities, such as the Nokia S60 and N95 handsets. Regardless of the type, the majority of devices connecting to UAG will present a user-agent string in their request and it is this string that determines the type of layout that UAG will use to render its pages and content. UAG takes advantage of this, by allowing the administrator to choose between the various formats that are made available, on a per application basis. The results are pretty cool and being able to cater for most known platforms and form factors, provides users with the best possible experience. The following screenshot illustrates an application that is enabled for the Premium portal, and how the portal and login pages would look on both a premium device and on a limited device: Customizing the login and admin pages The login and admin pages themselves are simple ASP pages, which contain a lot of code, as well as some text and visual elements. The main files in InternalSite that may be of interest to you are the following: Login.asp LogoffMsg.asp InstallAndDetect.asp Validate.asp PostValidate.asp InternalError.asp In addition, UAG keeps another version of some of the preceding files for ADFS, OTP, and OWA under similarly named folders. This means that if you have enabled the OWA theme on your portal, and you wish to customize it, you should work with the files under the /InternalSite/OWA folder. Of course, there are many other files that partake in the flow of each process, but the fact is there is little need to touch either the above or the others, as most of the appearance is controlled by a CSS template and text strings stored elsewhere. Certain requirements may even involve making significant changes to the layout of the pages, and leave you with no other option but to edit core ASP files themselves, but be careful as this introduces risk and is not technically supported. It's likely that these pages change with future updates to UAG, and that may cause a conflict with the older code that is in your files. The result of mixing old and new code is unpredictable, to say the least. The general appearance of the various admin pages is controlled by the file /InternalSite/CSS/template.css. This file contains about 80 different style elements including some of the 50 or so images displayed in the portal pages, such as the gradient background, the footer, and command buttons to name a few. The images themselves are stored in /InternalSite/Images. Both these folders have an OWA folder, which contains the CSS and images for the OWA theme. When editing the CSS, most of the style names will make sense, but if you are not sure, then why not copy the relevant ASP file and the CSS to your computer, so you can take a closer look with a visual editor, to better understand the structure. If you are doing this be careful not to make any changes that may alter the code in a damaging way, as this is easily done and can waste a lot of valuable time. A very useful piece of advice for checking tweaked code is to consider the use of Internet Explorer's integrated developer tool. In case you haven't noticed, it's a simple press of F12 on the keyboard and you'll find everything you need to get debugging. IE 9 and higher versions even pack a nifty trace module that allows you to perform low-level inspection on client-server interaction, without the need for additional third-party tools. We don't intend to devote this book to CSS, but one useful CSS element to be familiar with is the display: none; element, which can be used to hide any element it's put in. For example, if you add this to the .button element, it will hide the Login button completely. A common task is altering the part of the page where you see the Application and Network Access Portal text displayed. The text string itself can be edited using the master language files, which we will discuss shortly. The background of that part of the page, however, is built with the files headertopl.gif, headertopm.gif, and headertopr.gif. The original page design is classic HTML—it places headertopl on the left, headertopr on the right, and repeats headertopm in between to fill the space. If you need to change it, you could simply design a similar layout and put the replacement image files in /InternalSite/Images/CustomUpdate. Alternatively, you might choose to customize the logo only by copying the /InternalSite/Samples/logo.inc file into the /InternalSite/Inc/CustomUpdate folder, as this is where the HTML code that pertains to that area is located. Another thing that's worth noting is that if you create a custom CSS file, it takes effect immediately, and there's no need to do an activation. Well at least for the purposes of testing anyway. The same applies for image file changes too but as a general rule you should always remember to activate when finished, as any new configurations or files will need to be pushed into the TMG storage. Arrays are no exception to this rule either and you should know that custom files are only propagated to array members during an activation, so in this scenario, you do need to activate after each change. During development, you may copy the custom files to each member node manually to save time between activations, or better still, simply stop NLB on all array members so that all client traffic is directed to the one you are working on. An equally important point is that when you test changes to the code, the browser's cache or IIS itself may still retain files from the previous test or config, so if changes you've made do not appear first time around, then start by clearing your browser's cache and even reset IIS, before assuming you messed up the code. Customizing the portal As we said earlier, the pages that make up a portal and its various flavors are under the PortalHomePage folder. These are all ASP.NET files (.ASPX), and the scope for making any alterations here is very limited. However, the appearance is mostly controlled via the file /InternalSite/PortalHomePage/Standard.Master, which contains many visual parameters that you can change. For example, the DIV with ID content has a section pertaining to the side bar application list. You might customize the midTopSideBarCell width setting to make the bar wider or thinner. You can even hide it completely by adding style="display: none;" to the contentLeftSideBarCell table cell. As always, make sure you copy the master file to CustomUpdate, and not touch the original file, and as with the CSS files, any changes you make take effect immediately. Additional things that you can do with the portal are removing or adding buttons to the portal toolbar. For example, you might add a button to point to a help page that describes your applications, or a procedure to contact your internal technical support in case of a problem with the site.
Read more
  • 0
  • 0
  • 1989

article-image-article-understanding-services
Packt
07 Feb 2012
23 min read
Save for later

Understanding Services in JBoss

Packt
07 Feb 2012
23 min read
(For more resources on topic_name, see here.) Preparing JBoss Developer Studio The examples in this article are based on a standard ESB application template that can be found under the Chapter3 directory within the sample downloads..We will modify this template application as we proceed through this chapter. Time for action – opening the Chapter3 app Follow these steps: Click on the File menu and select Import. Now choose Existing Projects into workspace and select the folder where the book samples have been extracted: Then click on Finish. Now have a look at the jboss-esb.xml file. You can see that it has a single service and action as defined in the following snippet: <jbossesb parameterReloadSecs="5" xsi_schemaLocation="http://anonsvn.labs.jboss.com/labs/ jbossesb/trunk/product/etc/schemas/xml/ jbossesb-1.3.0.xsd http://anonsvn.jboss.org/repos/labs/ labs/jbossesb/trunk/product/etc/ schemas/xml/jbossesb-1.3.0.xsd"> <providers> <jms-provider connection-factory="ConnectionFactory" name="JBossMQ"> <jms-bus busid="chapter3GwChannel"> <jms-message-filter dest-name="queue/chapter3_Request_gw" dest-type="QUEUE"/> </jms-bus> <jms-bus busid="chapter3EsbChannel"> <jms-message-filter dest-name="queue/chapter3_Request_esb" dest-type="QUEUE"/> </jms-bus> </jms-provider> </providers> <services> <service category="Chapter3Sample" description="A template for Chapter3" name="Chapter3Service"> <listeners> <jms-listener busidref="chapter3GwChannel" is-gateway="true" name="Chapter3GwListener"/> <jms-listener busidref="chapter3EsbChannel" name="Chapter3Listener"/> </listeners> <actions mep="OneWay"> <action class="org.jboss.soa.esb.actions.SystemPrintln" name="PrintBefore"> <property name="message"/> <property name="printfull" value="true"/> </action> </actions> </service> </services></jbossesb> Examining the structure of ESB messages A service is an implementation of a piece of business logic which exposes a well defined service contract to consumers. The service will provide an abstract service contract which describes the functionality exposed by the service and will exhibit the following characteristics: Self contained: The implementation of the service is independent from the context of the consumers; any implementation changes will have no impact. Loosely coupled: The consumer invokes the service indirectly, passing messages through the bus to the service endpoint. There is no direct connection between the service and its consumers. Reusable: The service can be invoked by any consumer requiring the functionality exposed by the service. The provider is tied to neither a particular application nor process. Services which adhere to these criteria will be capable of evolving and scaling without affecting any consumers of that service. The consumer no longer cares which implementation of the service is being invoked, nor where it is located, provided that the exposed service contract remains compatible. Examining the message The structure of the message, and how it can be manipulated, plays an important part in any ESB application as a result of the message driven nature of the communication between service providers and consumers. The message is the envelope which contains all of the information relevant to a specific invocation of a service. All messages within JBoss ESB are implementations of the org.jboss.soa.esb.message. Message interface, the major aspects of which are: Header: Information concerning the identity, routing addresses, and correlation of the message Context: Contextual information pertaining to the delivery of each message, such as the security context Body: The payload and additional details as required by the service contract Attachment: Additional information that may be referenced from within the payload Properties: Information relating to the specific delivery of a message, usually transport specific (for example the original JMS queue name) Time for action – printing the message structure Let us execute the Chapter3 sample application that was opened up at the beginning of this chapter. Follow these steps: In JBoss Developer Studio, click Run and select Run As and Run on Server. Alternatively you can press Alt + Shift + X, followed by R. You can see the server runtime has been pre-selected. Choosing the Always use this server when running this project check box will always use this runtime and this dialog will not appear again. Click Next. A window with the project pre-configured to run on this server is shown. Ensure that we have only our project Chapter3 selected to the right hand side. Click Finish. The server runtime will be started up (if not already started) and the ESB file will be deployed to the server runtime. Select the src folder, expand it till the SendJMSMessage.java file is displayed in the tree. Now click Run, select Run As and Java Application. The entire ESB message contents will be printed in the console as follows: INFO [STDOUT] Message structure: INFO [STDOUT] [ message: [ JBOSS_XML ]header: [ To: JMSEpr [ PortReference < <wsa:Address jms:localhost:1099#queue/chapter3_Request_esb/>, <wsa:ReferenceProperties jbossesb:java.naming.factory.initial : org.jnp.interfaces.NamingContextFactory/>, <wsa:ReferenceProperties jbossesb:java.naming.provider.url : localhost:1099/>, <wsa:ReferenceProperties jbossesb:java.naming.factory.url.pkgs : org.jnp.interfaces/>, <wsa:ReferenceProperties jbossesb:destination-type : queue/>, <wsa:ReferenceProperties jbossesb:destination-name : queue/chapter3_Request_esb/>, <wsa:ReferenceProperties jbossesb:specification-version : 1.1/>, <wsa:ReferenceProperties jbossesb:connection-factory : ConnectionFactory/>, <wsa:ReferenceProperties jbossesb:persistent : true/>, <wsa:ReferenceProperties jbossesb:acknowledge-mode : AUTO_ACKNOWLEDGE/>, <wsa:ReferenceProperties jbossesb:transacted : false/>, <wsa:ReferenceProperties jbossesb:type : urn:jboss/esb/epr/type/jms/> > ] MessageID: e694a6a5-6a30-45bf-8f6d-f48363219ccf RelatesTo: jms:correlationID#e694a6a5-6a30-45bf-8f6d-f48363219ccf ]context: {}body: [ objects: {org.jboss.soa.esb.message.defaultEntry=Chapter 3 says Hello!} ]fault: [ ]attachments: [ Named:{}, Unnamed:[] ]properties: [ {org.jboss.soa.esb.message.transport.type=Deferred serialized value: 12d16a5, org.jboss.soa.esb.message.byte.size=2757, javax.jms.message.redelivered=false, org.jboss.soa.esb.gateway.original.queue.name=Deferred serialized value: 129bebb, org.jboss.soa.esb.message.source=Deferred serialized value: 1a8e795} ] ] What just happened? You have just created a Chapter3.esb file and deployed it to the ESB Runtime on the JBoss Application Server 5.1. You executed a gateway client that posted a string to the Bus. The server converted this message to an ESB message and the complete structure was printed out. Take a moment to examine the output and understand the various parts of the ESB message. Have a go hero – deploying applications Step 1 through step 4 describe how to start the server and deploy our application from within JBoss Developer Studio. For the rest of this chapter, and throughout this book, you will be repeating these steps and will just be asked to deploy the application. Message implementations JBoss ESB provides two different implementations of the message interface, one which marshalls data into an XML format and a second which uses Java serialization to create a binary representation of the message. Both of these implementations will only handle Java serializable objects by default, however it is possible to extend the XML implementation to support additional object types. Message implementations are created indirectly through the org.jboss.soa.esb. message.format.MessageFactory class. In general any use of serializable objects can lead to a brittle application, one that is more tightly coupled between the message producer and consumer. The message implementations within JBoss ESB mitigate this by supporting a 'Just In Time' approach when accessing the data. Care must still be taken with what data is placed within the message, however serialization/marshalling of these objects will only occur as and when required. Extending the ESB to provide alternative message implementations, and extending the current XML implementation to support additional types, is outside the scope of this book. The body This is the section of the message which contains the main payload information for the message, adhering to the contract exposed by the service. The payload should only consist of the data required by the service contract and should not rely on any service implementation details as this will prevent the evolution or replacement of the service implementation at a future date. The types of data contained within the body are restricted only by the requirements imposed by the message implementation, in other words the implementation must be able to serialize or marshall the contents as part of service invocation. The body consists of Main payload: accessed using the following methods: public Object get() ;public void add(final Object value) ; Named objects: accessed using the following methods: public Object get(final String name) ;public void add(final String name, final Object value) ; Time for action – examining the main payload Let us create another action class that simply prints the message body. We will add this action to the sample application that was opened up at the beginning of this chapter. Right click on the src folder and choose New and select Class: Enter the Name as "MyAction", enter the Package as "org.jboss.soa. samples.chapter3", and select the Superclass as "org.jboss.soa.esb. actions.AbstractActionLifecycle": Click Finish. Add the following imports and the following body contents to the code: import org.jboss.soa.esb.helpers.ConfigTree;import org.jboss.soa.esb.message.Message; protected ConfigTree _config;public MyAction(ConfigTree config) { _config = config;}public Message displayMessage(Message message) throws Exception { System.out.println( "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"); System.out.println("Body: " + message.getBody().get()); System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"); return message;} Click Save. Open the jboss-esb.xml file in Tree mode, expand till Actions is displayed in the tree. Select Actions, click Add | Custom Action: Enter the Name as "BodyPrinter" and choose the "MyAction" class and "displayMessage" process method: Click Save and the application will be deployed. If the server was stopped then deploy it using the Run menu and select Run As | Run on Server: Once the application is deployed on the server, run SendJMSMessage.java by clicking Run | Run As | Java Application. The following can be seen displayed in the console output: 12:19:32,562 INFO [STDOUT] &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&12:19:32,562 INFO [STDOUT] Body: Chapter 3 says Hello!12:19:32,562 INFO [STDOUT] &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& What just happened? You have just created your own action class that used the Message API to get the main payload of the message and printed it to the console. Have a go hero – additional body contents Now add another miscellaneous SystemPrintln action after our BodyPrinter. Name it PrintAfter and make sure printfull is set to true. Modify the MyAction class and add additional named content using the getBody().add(name, object) method and see what gets printed on the console. Here is the actions section of the config file <actions mep="OneWay"> <action class="org.jboss.soa.esb.actions.SystemPrintln" name="PrintBefore"> <property name="message"/> <property name="printfull" value="true"/> </action> <action class="org.jboss.soa.esb.samples.chapter3.MyAction" name="BodyPrinter" process="displayMessage"/> <action class="org.jboss.soa.esb.actions.SystemPrintln" name="PrintAfter"> <property name="message"/> <property name="printfull" value="true"/> </action></actions> The following is the listing of the MyAction class's modified displayMessage method public Message displayMessage(Message message) throws Exception { System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"); System.out.println("Body: " + message.getBody().get()); message.getBody().add("Something", "Unknown"); System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"); return message;} The header The message header contains the information relating to the identity, routing, and the correlation of messages. This information is based on, and shares much in common with, the concepts defined in the W3C WS-Addressing specification. It is important to point out that many of these aspects are normally initialized automatically by other parts of the codebase; a solid understanding of these concepts will allow the developer to create composite services using more advanced topologies. Routing information Every time a message is sent within the ESB it contains information which describes who sent the message, which service it should be routed to, and where any replies/faults should be sent once processing is complete. The creation of this information is the responsibility of the invoker and, once delivered, any changes made to this information, from within the target service, will be ignored by that service. The information in the header takes the form of Endpoint References (EPRs) containing a representation of the service address, often transport specific, and extensions which can contain relevant contextual information for that endpoint. This information should be treated as opaque by all parties except the party which was responsible for creating it. There are four EPRs included in the header, they are as follows: To: This is the only mandatory EPR, representing the address of the service to which the message is being sent. This will be initialized by ServiceInvoker with the details of the service chosen to receive the message. From: This EPR represents the originator of the message, if present, and may be used as the address for responses if there is neither an explicit ReplyTo nor FaultTo set on the message. ReplyTo: This EPR represents the endpoint to which all responses will be sent, if present, and may be used as the address for faults if there is no explicit FaultTo set on the message. This will normally be initialized by ServiceInvoker if a synchronous response is expected by the service consumer. FaultTo: This EPR represents the endpoint to which all faults will be sent, if present. When thinking about the routing information it is important to view these details from the perspective of the service consumer, as the EPRs represent the wishes of the consumer and must be adhered to. If the service implementation involves more advanced topologies, like chaining and continuations, which we will discuss later in the chapter, then care must be taken to preserve these EPRs when messages are propagated to subsequent services. Message identity and correlation There are two parts of the header which are related to the identity of the message and its correlation with a preceding message. These are as follows: MessageID: A unique reference which can be used to identify the message as it progresses through the ESB. The reference is represented by a Uniform Resource Name (URN), a specialized Uniform Resource Identifier (URI) which will represent the identity of the message within a specific namespace. The creator of the message may choose to associate it with an identity which is specific to the application context within which it is being used, in which case the URN should refer to a namespace which is also application context specific. If no MessageID has been associated with the message then the ESB will assign a unique identifier when it is first sent to a service. RelatesTo: When sending a reply, this represents the unique reference of the message representing the request. This may be used to correlate the response message with the original request. Service action The action header is an optional, service-specific URN that may be used to further refine the processing of the message by a service provider or service consumer. The URN should refer to an application-specific namespace. There are no restrictions on how this header is to be used by the application including, if considered appropriate, ignoring its contents.   Time for action – examining the header Let us modify MyAction to display some of the header information that we need: Open MyAction and edit the displayMessage method as follows: public Message displayMessage(Message message) throws Exception { System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"); System.out.println("From: " + message.getHeader().getCall().getFrom()); System.out.println("To: " + message.getHeader().getCall().getTo()); System.out.println("MessageID: " + message.getHeader().getCall().getMessageID()); System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"); return message;} Remove the PrintBefore and PrintAfter actions if they exist. Make sure that we have only the BodyPrinter action: Click on Save. If the server was still running (and a small red button appears in the console window), then you might notice the application gets redeployed by default. If this did not happen then deploy the application using the Run menu and select Run As | Run on Server. The following output will be displayed in the console: INFO [EsbDeployment] Stopping 'Chapter3.esb'INFO [EsbDeployment] Destroying 'Chapter3.esb'WARN [ServiceMessageCounterLifecycleResource] Calling cleanup on existing service message counters for identity ID-7INFO [QueueService] Queue[/queue/chapter3_Request_gw] stoppedINFO [QueueService] Queue[/queue/chapter3_Request_esb] stoppedINFO [QueueService] Queue[/queue/chapter3_Request_esb] started, fullSize=200000, pageSize=2000, downCacheSize=2000INFO [QueueService] Queue[/queue/chapter3_Request_gw] started, fullSize=200000, pageSize=2000, downCacheSize=2000INFO [EsbDeployment] Starting ESB Deployment 'Chapter3.esb' Run SendJMSMessage.java by clicking Run | Run As | Java Application. The following messages will be printed in the console INFO [STDOUT] &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&INFO [STDOUT] From: nullINFO [STDOUT] To: JMSEpr [ PortReference < <wsa:Address jms:localhost:1099#queue/chapter3_Request_esb/>, <wsa:ReferenceProperties jbossesb:java.naming.factory.initial : org.jnp.interfaces.NamingContextFactory/>, <wsa:ReferenceProperties jbossesb:java.naming.provider.url : localhost:1099/>, <wsa:ReferenceProperties jbossesb:java.naming.factory.url.pkgs : org.jnp.interfaces/>, <wsa:ReferenceProperties jbossesb:destination-type : queue/>, <wsa:ReferenceProperties jbossesb:destination-name : queue/chapter3_Request_esb/>, <wsa:ReferenceProperties jbossesb:specification-version : 1.1/>, <wsa:ReferenceProperties jbossesb:connection-factory : ConnectionFactory/>, <wsa:ReferenceProperties jbossesb:persistent : true/>, <wsa:ReferenceProperties jbossesb:acknowledge-mode : AUTO_ACKNOWLEDGE/>, <wsa:ReferenceProperties jbossesb:transacted : false/>, <wsa:ReferenceProperties jbossesb:type : urn:jboss/esb/epr/type/jms/> > ]INFO [STDOUT] MessageID: 46e57744-d0ac-4f01-ad78-b1f15a3335d1INFO [STDOUT] &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& What just happened? We examined some of the header contents through the API. We printed the From, To, and the MessageID from within our MyAction class. Have a go hero – additional header contents Now modify the MyAction class to print the Action, ReplyTo, RelatesTo, and FaultTo contents of the header to the console. Here is the listing of the modified MyAction class's method: public Message displayMessage(Message message) throws Exception { System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"); System.out.println("From: " + message.getHeader().getCall().getFrom()); System.out.println("To: " + message.getHeader().getCall().getTo()); System.out.println("MessageID: " + message.getHeader().getCall().getMessageID()); System.out.println("Action: " + message.getHeader().getCall().getAction()); System.out.println("FaultTo: " + message.getHeader().getCall().getFaultTo()); System.out.println("RelatesTo: " + message.getHeader().getCall().getRelatesTo()); System.out.println("ReplyTo: " + message.getHeader().getCall().getReplyTo()); System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"); return message;} The context The message context is used to transport the active contextual information when the message is sent to the target service. This may include information such as the current security context, transactional information, or even context specific to the application. This contextual information is not considered to be part of the service contract and is assumed to change between successive message deliveries. Where the message context really becomes important is when a service pipeline is invoked through an InVM transport, as this can allow the message to be passed by reference. When the transport passes the message to the target service it will create a copy of the message header and message context, allowing each to be updated in subsequent actions without affecting the invoked service. Have a go hero – printing message context Modify the MyAction class to print the context of the ESB message; obtain the context through the getContext() method. You will notice that the context is empty for our sample application as we currently have no security or transactional context attached to the message. Message validation The message format within JBoss ESB allows the consumer and producer to use any payload that suits the purpose of the service contract. No constraints are placed on this payload other than the fact that it must be possible to marshall the payload contents so that the messages can be transported between the consumer and producer. While this ability is useful for creating composite services, it can be a disadvantage when you need to design services that have an abstract contract, hide the details of the implementation, are loosely coupled, and can easily be reused. In order to encourage the loose coupling of services it is often advantageous to choose a payload that does not dictate implementation, for example XML. JBoss ESB provides support for enforcing the structure of XML payloads for request and response messages, through the XML schema language as defined through the W3C. An XML Schema Document (XSD) is an abstract, structural definition which can be used to formally describe an XML message and guarantee that a specific payload matches that definition through a process called validation. Enabling validation on a service is simply a matter of providing the schema associated with the request and/or response messages and specifying the validate attribute, as follows: <actions inXsd="/request.xsd" outXsd="/response.xsd" validate="true"> ...</actions> This will force the service pipeline to validate the request and response messages against the XSD files, if they are specified, with the request validation occurring before the first service action is executed and the response validation occurring immediately before the response message is sent to the consumer. If validation of the request or response message does fail then a MessageValidationException fault will be raised and sent to the consumer using the normal fault processing as defined in the MEPs and responses section. This exception can also be seen by enabling DEBUG logging through the mechanism supported by the server. Have a go hero – enabling validation Add a request.xsd or a response.xsd or both to your actions in the sample application provided. Enable validation and test the output. Configuring through the ConfigTree JBoss ESB handles the majority of its configuration through a hierarchical structure similar to the W3C DOM, namely, org.jboss.soa.esb.helpers.ConfigTree. Each node within the structure contains a name, a reference to the parent node, a set of named attributes, and references to all child nodes. This structure is used, directly and indirectly, within the implementation of the service pipeline and action processors, and will be required if you are intending to create your own action processors. The only exception to this is when using an annotated action class when the configuring of the action will be handled by the framework instead of programmatically. Configuring properties in the jboss-esb.xml file The ConfigTree instance passed to an action processor is a hierarchical representation of the properties as defined within the action definition of the jboss-esb.xml file. Each property defined within an action may be interpreted as a name/value pair or as hierarchical content to be parsed by the action. For example the following: <action ....> <!-- name/value property --> <property name="propertyName" value="propertyValue"/> <!-- Hierarchical property --><property name="propertyName"> <hierarchicalProperty attr="value"> <inner name="myName" random="randomValue"/> </hierarchicalProperty> </property></action> This will result in the following ConfigTree structure being passed to the action: Traversing the ConfigTree hierarchy Traversing the hierarchy is simply a matter of using the following methods to obtain access to the parent or child nodes: public ConfigTree getParent() ;public ConfigTree[] getAllChildren() ;public ConfigTree[] getChildren(String name) ;public ConfigTree getFirstChild(String name) ; Accessing attributes Attributes are usually accessed by querying the current ConfigTree instance for the value associated with the required name, using the following methods: public String getAttribute(String name) ;public String getAttribute(String name, String defaultValue) ;public long getLongAttribute(String name, long defaultValue) ;public float getFloatAttribute(String name, float defaultValue) ;public boolean getBooleanAttribute(String name, boolean defaultValue) ;public String getRequiredAttribute(String name) throws ConfigurationException ; It is also possible to obtain the number of attributes, names of all the attributes, or the set of key/value pairs using the following methods: public int attributeCount() ;public Set<String> getAttributeNames() ;public List<KeyValuePair> attributesAsList() ; Time for action – examining configuration properties Let us add some configuration properties to our MyAction. We will make the & and the number of times it needs to be printed as configurable properties. Follow these steps: Add two members to the MyAction class: public String SYMBOL = "&";public int COUNT = 48; Modify the constructor as follows: _config = config;String symbol = _config.getAttribute("symbol");if (symbol != null) { SYMBOL = symbol;}String count = _config.getAttribute("count");if (count != null) { COUNT = Integer.parseInt(count);} Add a printLine() method: private void printLine() { StringBuffer line = new StringBuffer(COUNT); for (int i = 0; i < COUNT; i++) { line.append(SYMBOL); } System.out.println(line);} Modify the printMessage() method as shown in the following snippet: printLine();System.out.println("Body: " + message.getBody().get());printLine();return message; Edit the jboss-esb.xml file and select the action, BodyPrinter. Add two properties symbol as * and count as 50: Click on Save or press Ctrl + S. Deploy the application using the Run menu and select Run As | Run on Server. Run SendJMSMessage.java by clicking Run, select Run As and Java Application. INFO [STDOUT] **************************************************INFO [STDOUT] Body: Chapter 3 says Hello!INFO [STDOUT] ************************************************** What just happened? You just added two properties to the MyAction class. You also retrieved these properties from the ConfigTree and used them. Have a go hero – additional header contents Experiment with the other API methods. Write hierarchicalProperty and see how that can be retrieved.
Read more
  • 0
  • 0
  • 1033

article-image-ext-js-4-working-tree-and-form-components
Packt
11 Jan 2012
6 min read
Save for later

Ext JS 4: Working with Tree and Form Components

Packt
11 Jan 2012
6 min read
Tree panel The tree component is much more simplified in Ext JS 4. Like grid, it is also a subclass of Ext.panel.Table. This means we can add most functionality of the grid in the tree as well. Let's start declaring a simple tree in Ext JS 3: new Ext.tree.TreePanel({ renderTo: 'tree-example', title: 'Simple Tree', width: 200, rootVisible: false, root: new Ext.tree.AsyncTreeNode({ expanded: true, children: [ { text: "Menu Option 1", leaf: true }, { text: "Menu Option 2", expanded: true, children: [ { text: "Sub Menu Option 2.1", leaf: true }, { text: "Sub Menu Option 2.2", leaf: true} ] }, { text: "Menu Option 3", leaf: true } ] }) }); Now, let's see how to declare the same tree in Ext JS: Ext.create('Ext.tree.Panel', { title: 'Simple Tree', width: 200, store: Ext.create('Ext.data.TreeStore', { root: { expanded: true, children: [ { text: "Menu Option 1", leaf: true }, { text: "Menu Option 2", expanded: true, children: [ { text: "Sub Menu Option 2.1", leaf: true }, { text: "Sub Menu Option 2.2", leaf: true} ] }, { text: "Menu Option 3", leaf: true } ] } }), rootVisible: false, renderTo: 'tree-example' }); In Ext JS 4, we also have the title, width, and div properties, where the tree is going to be rendered, and a config store. The store config is a new element for the tree. If we output both of the codes, we will have the same output, which is the following tree: If we take a look at the data package, we will see three files related to tree: NodeInterface, Tree, and TreeStore. NodeInterface applies a set of methods to the prototype of a record to decorate it with a Node API. The Tree class is used as a container of a series of nodes and TreeStore is a store implementation used by a Tree. The good thing about having TreeStore is that we can use its features, such as proxy and reader, as we do for any other Store in Ext JS 4. Drag-and-drop and sorting The drag-and-drop feature is very useful for rearranging the order of the nodes in the Tree class. Adding the drag-and-drop feature is very simple. We need to add the following code into the tree declaration: Ext.create('Ext.tree.Panel', { store: store, viewConfig: { plugins: { ptype: 'treeviewdragdrop' } }, //other properties }); And how do we handle drag-and-drop in store? We do it in the same way as we handled the edition plugin on the Grid, using a Writer: var store = Ext.create('Ext.data.TreeStore', { proxy: { type: 'ajax', api: { read : '../data/drag-drop.json', create : 'create.php' } }, writer: { type: 'json', writeAllFields: true, encode: false }, autoSync:true }); In the earlier versions of Ext JS 4, the autoSync config option does work. Another way of synchronizing the Store with the server is adding a listener to the Store instead of the autoSync config option, as follows: listeners: { move: function( node, oldParent, newParent, index, options ) { this.sync(); } } And, to add the sorting feature to the Tree class, we simply need to configure the sorters property in the TreeStore, as follows: Ext.create('Ext.data.TreeStore', { folderSort: true, sorters: [{ property: 'text', direction: 'ASC' }] }); Check tree To implement a check tree, we simply need to make a few changes in the data that we are going to apply to the Tree. We need to add a property called checked to each node, with a true or false value; true indicates the node is checked, and false, otherwise. For this example, we will use the following json code: [{ "text": "Cartesian", "cls": "folder", "expanded": true, "children": [{ "text": "Bar", "leaf": true, "checked": true },{ "text": "Column", "leaf": true, "checked": true },{ "text": "Line", "leaf": true, "checked": false }] },{ "text": "Gauge", "leaf": true, "checked": false },{ "text": "Pie", "leaf": true, "checked": true }] And as we can see, the code is the same as that for a simple tree: var store = Ext.create('Ext.data.TreeStore', { proxy: { type: 'ajax', url: 'data/check-nodes.json' }, sorters: [{ property: 'leaf', direction: 'ASC' }, { property: 'text', direction: 'ASC' }] }); Ext.create('Ext.tree.Panel', { store: store, rootVisible: false, useArrows: true, frame: true, title: 'Charts I have studied', renderTo: 'tree-example', width: 200, height: 250 }); The preceding code will output the following tree: Tree grid In Ext JS 3, the client JavaScript Component, Tree Grid, was an extension part of the ux package. In Ext JS 4, this Component is part of the native API but it is no longer an extension. To implement a Tree Grid, we are going to use the Tree Component as well; the only difference is that we are going to declare some columns inside the tree. This is the good part of Tree being a subclass of Ext.panel.Table, the same super class for Grid as well. First, we will declare a Model and a Store, to represent the data we are going to display in the Tree Grid. We will then load the Tree Grid: Ext.define('Book', { extend: 'Ext.data.Model', fields: [ {name: 'book', type: 'string'}, {name: 'pages', type: 'string'} ] }); var store = Ext.create('Ext.data.TreeStore', { model: 'Book', proxy: { type: 'ajax', url: 'data/treegrid.json' }, folderSort: true }); So far there is no news. We declared the variable store as any other used in a grid, except that this one is a TreeStore. The code to implement the Component Tree Grid is declared as follows: Ext.create('Ext.tree.Panel', { title: 'Books', width: 500, height: 300, renderTo: Ext.getBody(), collapsible: true, useArrows: true, rootVisible: false, store: store, multiSelect: true, singleExpand: true, columns: [{ xtype: 'treecolumn', text: 'Task', flex: 2, sortable: true, dataIndex: 'task' },{ text: 'Assigned To', flex: 1, dataIndex: 'user', sortable: true }] }); The most important line of code is highlighted—the columns declaration. The columns property is an array of Ext.grid.column.Column objects, as we declare in a grid. The only thing we have to pay attention to is the column type of the first column, that is, treecolumn; this way we know that we have to render the node into the Tree Grid. We also configured some other properties. collapsible is a Boolean property; if set to true it will allow us to collapse and expand the nodes of the tree. The useArrows is also a Boolean property, which indicates whether the arrow icon will be visible in the tree (expand/collapse icons). The property rootVisible indicates whether we want to display the root of the tree, which is a simple period (.). The property singleExpand indicates whether we want to expand a single node at a time and the multiSelect property indicates whether we want to select more than one node at once. The preceding code will output the following tree grid:
Read more
  • 0
  • 0
  • 4554
Visually different images

article-image-ext-js-4-working-grid-component
Packt
11 Jan 2012
10 min read
Save for later

Ext JS 4: Working with the Grid Component

Packt
11 Jan 2012
10 min read
(For more resources on JavaScript, see here.) Grid panel The grid panel is one of the most-used components when developing an application Ext JS 4 provides some great improvements related to this component. The Ext JS 4 Grid panel renders a different HTML than Ext JS 3 Grid did. Sencha calls this new feature Intelligent Rendering. Ext JS 3 used to create the whole structure, supporting all the features. But, what if someone just wanted to display a simple grid? All the other features not being rendered would just be wasted, because no one was using that structure. Ext JS 4 now renders only the features the grid uses, minimizing and boosting the performance. Before we examine the grid's new features and enhancements, let's take a look how to implement a simple grid in Ext JS 4: Ext.create('Ext.grid.Panel', { store: Ext.create('Ext.data.ArrayStore', { fields: [ {name: 'book'}, {name: 'author'} ], data: [['Ext JS 4: First Look','Loiane Groner']] }), columns: [ { text : 'Book', flex : 1, sortable : false, dataIndex: 'book' },{ text : 'Author', width : 100, sortable : true, dataIndex: 'author' }], height: 80, width: 300, title: 'Simple Grid', renderTo: Ext.getBody() }); As you can see in the preceding code, the two main parts of the grid are the store and the columns declarations. Note, as well, names of both store and model fields always have to match with the column's dataIndex (if you want to display the column in the grid). So far, nothing has changed. The way we used to declare a simple grid in Ext JS 3 is the same way we do for Ext JS 4. However, there are some changes related to plugins and the new features property. We are going to take a closer look at that in this section. Let's dive into the changes! Columns Ext JS 4 organizes all the column classes into a single package—the Ext.grid.column package. We will explain how to use each column type with an example. But first, we need to declare a Model and a Store to represent and load the data: Ext.define('Book', { extend: 'Ext.data.Model', fields: [ {name: 'book'}, {name: 'topic', type: 'string'}, {name: 'version', type: 'string'}, {name: 'released', type: 'boolean'}, {name: 'releasedDate', type: 'date'}, {name: 'value', type: 'number'} ] }); var store = Ext.create('Ext.data.ArrayStore', { model: 'Book', data: [ ['Ext JS 4: First Look','Ext JS','4',false,null,0], ['Learning Ext JS 3.2','Ext JS','3.2',tr ue,'2010/10/01',40.49], ['Ext JS 3.0 Cookbook','Ext JS','3',true,'2009/10/01',44.99], ['Learning Ext JS','Ext JS','2.x',true,'2008/11/01',35.99], ] }); Now, we need to declare a grid: Ext.create('Ext.grid.Panel', { store: store, width: 550, title: 'Ext JS Books', renderTo: 'grid-example', selModel: Ext.create('Ext.selection.CheckboxModel'), //1 columns: [ Ext.create('Ext.grid.RowNumberer'), //2 { text: 'Book',//3 flex: 1, dataIndex: 'book' },{ text: 'Category', //4 xtype:'templatecolumn', width: 100, tpl: '{topic} {version}' },{ text: 'Already Released?', //5 xtype: 'booleancolumn', width: 100, dataIndex: 'released', trueText: 'Yes', falseText: 'No' },{ text: 'Released Date', //6 xtype:'datecolumn', width: 100, dataIndex: 'releasedDate', format:'m-Y' },{ text: 'Price', //7 xtype:'numbercolumn', width: 80, dataIndex: 'value', renderer: Ext.util.Format.usMoney },{ xtype:'actioncolumn', //8 width:50, items: [{ icon: 'images/edit.png', tooltip: 'Edit', handler: function(grid, rowIndex, colIndex) { var rec = grid.getStore().getAt(rowIndex); Ext.MessageBox.alert('Edit',rec.get('book')); } },{ icon: 'images/delete.gif', tooltip: 'Delete', handler: function(grid, rowIndex, colIndex) { var rec = grid.getStore().getAt(rowIndex); Ext.MessageBox.alert('Delete',rec.get('book')); } }] }] }); The preceding code outputs the following grid: The first column is declared as selModel, which, in this example, is going to render a checkbox, so we can select some rows from the grid. To add this column into a grid, simply declare the selModel (also known as sm in Ext JS 3) as CheckBox selection model, as highlighted in the code (comment 1 in the code). The second column that we declared is the RowNumberer column. This column adds a row number automatically into the grid. In the third column (with text:'Book'), we did not specify a column type; this means the column will display the data itself as a string. In the fourth column, we declared a column with xtype as templatecolumn. This column will display the data from the store, specified by an XTemplate, as declared in the tpl property. In this example, we are saying we want to display the topic (name of the technology) and its version. The fifth column is declared as booleancolumn. This column displays a true or false value. But, if we do not want to display true or false in the grid, we can specify the values that we want to get displayed. In this example, we displayed the value as Yes (for true values) and No (for false values), as we declared in the trueText and falseText. The sixth column we declared as datecolumn, which is used to display dates. We can also declare a date format we want to be displayed. In this example, we want to display only the month and the year. The format follows the same rules for PHP date formats. The seventh column we declared as numbercolumn. This column is used to display numbers, such as a quantitative number, money, and so on. If we want to display the number in a particular format, we can use one of the Ext JS renderers to create a customized one. And the last column we declared is the actioncolumn. In this column, we can display icons that are going to execute an action, such as delete or edit. We declare the icons we want to display in the items property. topic: {name}{rows.length} Book topic: {name}{rows.length} Books Feature support In Ext JS 3, when we wanted to add a new functionality to a grid, we used to create a plugin or extend the GridPanel class. There was no default way to do it. Ext JS 4 introduces the Ext.grid.feature.Feature class that contains common methods and properties to create a plugin. Inside the Ext.grid.feature packages, we will find seven classes: AbstractSummary, Chunking, Feature, Grouping, GroupingSummary, RowBody, and Summary. A feature is very simple to use—we need to add the feature inside the feature declaration in the grid: features: [{ groupHeaderTpl: 'Publisher: {name}', ftype: 'groupingsummary' }] Let's take a look at how to use some of these native grid features. Ext.grid.feature.Grouping Grouping rows in Ext JS 4 has changed. Now, Grouping is a feature and can be applied to a grid through the features property. The following code displays a grid grouped by book topic: Ext.define('Book', { extend: 'Ext.data.Model', fields: ['name', 'topic'] }); var Books = Ext.create('Ext.data.Store', { model: 'Book', groupField: 'topic', data: [{ name: 'Learning Ext JS', topic: 'Ext JS' },{ name: 'Learning Ext JS 3.2', topic: 'Ext JS' },{ name: 'Ext JS 3.0 Cookbook', topic: 'Ext JS' },{ name: 'Expert PHP 5 Tools', topic: 'PHP' },{ name: 'NetBeans IDE 7 Cookbook', topic: 'Java' },{ name: 'iReport 3.7', topic: 'Java' },{ name: 'Python Multimedia', topic: 'Python' },{ name: 'NHibernate 3.0 Cookbook', topic: '.NET' },{ name: 'ASP.NET MVC 2 Cookbook', topic: '.NET' }] }); Ext.create('Ext.grid.Panel', { renderTo: Ext.getBody(), frame: true, store: Books, width: 350, height: 400, title: 'Books', features: [Ext.create('Ext.grid.feature.Grouping',{ groupHeaderTpl: 'topic: {name} ({rows.length} Book{[values.rows.length > 1 ? "s" : ""]})' })], columns: [{ text: 'Name', flex: 1, dataIndex: 'name' },{ text: 'Topic', flex: 1, dataIndex: 'topic' }] }); In the groupHeaderTpl attribute, we declared a template to be displayed in the grouping row. We are going to display one of the following customized strings, depending on the number of books belonging to the topic: The string comprises of the topic name ({name}) and the count of the book for the topic ({rows.length}). In Ext JS 3, we still had to declare a grouping field in the store; but, instead of a Grouping feature, we used to declare GroupingView, as follows: view: new Ext.grid.GroupingView({ forceFit:true, groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Books" : "Book"]})' }) If we execute the grouping grid, we will get the following output:   Ext.grid.feature.GroupingSummary The GroupingSummary feature also groups rows with a field in common, but it also adds a summary row at the bottom of each group. Let's change the preceding example to use the GroupingSummary feature: Ext.create('Ext.grid.Panel', { renderTo: Ext.getBody(), frame: true, store: Books, width: 350, height: 400, title: 'Books', features: [{ groupHeaderTpl: 'Topic: {name}', ftype: 'groupingsummary' }], columns: [{ text: 'Name', flex: 1, dataIndex: 'name', summaryType: 'count', summaryRenderer: function(value){ return Ext.String.format('{0} book{1}', value, value !== 1 ? 's' : ''); } },{ text: 'Topic', flex: 1, dataIndex: 'topic' }] }); We highlighted two pieces in the preceding code. The first line is the feature declaration: in the previous example (Grouping) we created the feature using the Ext.create declaration. But if we do not want to explicitly create the feature every time we declare, we can use the ftype property, which is groupingsummary in this example. The groupingsummary that we added to the grid's name column is in the second line of highlighted code. We declared a summaryType property and set its value as count. Declaring the summaryType as count means we want to display the number of books in that particular topic/category; it is going to count how many records we have for a particular category in the grid. It is very similar to the count of the PL/SQL language. Other summary types we can declare are: sum, min, max, average (these are self-explanatory). In this example, we want to customize the text that will be displayed in the summary, so we are going to use the summaryRenderer function. We need to pass a value argument to it, and the value is the count of the name column. Then, we are going to return a customized string that is going to display the count (token {0}) and the string book or books, depending on the count (if it is more than 1 we add s at the end of the string book). Ext.String.format is a function that allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each token must be unique and must increment in the format {0}, {1}, and so on. The preceding code will output the following grid: Ext.grid.feature.Summary The GroupingSummary feature adds a row at the bottom of each grouping. The Summary feature adds a row at the bottom of the grid to display summary information. The property configuration is very similar to that for GroupingSummary, because both classes are subclasses of AbstractSummary (a class that provides common properties and methods for summary features). Ext.create('Ext.grid.Panel', { renderTo: Ext.getBody(), frame: true, store: Books, width: 350, height: 300, title: 'Books', features: [{ ftype: 'summary' }], columns: [{ text: 'Name', flex: 1, dataIndex: 'name', summaryType: 'count', summaryRenderer: function(value){ return Ext.String.format('{0} book{1}', value, value !== 1 ? 's' : ''); } },{ text: 'Topic', flex: 1, dataIndex: 'topic' }] }); The only difference from the GroupingSummary feature is the feature declaration itself. The summayType and summaryRenderer properties work in a similar way. The preceding code will output the following grid: Ext.grid.feature.RowBody The rowbody feature adds a new tr->td->div in the bottom of the row that we can use to display additional information. Here is how to use it: Ext.create('Ext.grid.Panel', { renderTo: Ext.getBody(), frame: true, store: Books, width: 350, height: 300, title: 'Books', features: [{ ftype: 'rowbody', getAdditionalData: function(data, idx, record, orig) { return { rowBody: Ext.String.format( '->topic: {0}', data.topic) }; } }, { ftype: 'rowwrap' }], columns: [{ text: 'Name', flex: 1, dataIndex: 'name' }] });  In the preceding code, we are not only displaying the name of the book; we are using the rowbody to display the topic of the book as well. The first step is to declare the rowbody feature. One very important thing to be noted is that rowbody will be initially hidden, unless you override the getAdditionalData method. If we execute the preceding code, we will get the following output:
Read more
  • 0
  • 0
  • 5052

article-image-qooxdoo-working-layouts
Packt
27 Dec 2011
16 min read
Save for later

qooxdoo: Working with Layouts

Packt
27 Dec 2011
16 min read
(For more resources on this topic, see here.) qooxdoo uses the generic terminology of the graphical user interface. So, it is very easy to understand the concepts involved in it.. The basic building block in qooxdoo is termed a widget. Each widget (GUI component) is a subclass of the Widget class. A widget also acts as a container to hold more widgets. Wherever possible, grouping of the widgets to form a reusable component or custom widget is a good idea. This allows you to maintain consistency across your application and also helps you to build the application quicker than the normal time. It also increases maintainability, as you need to fix the defect at only one place. qooxdoo provides a set of containers too, to carry widgets, and provides public methods to manage. Let's start with the framework's class hierarchy: Base classes for widgets qooxdoo framework abstracts the common functionalities required by all the widgets into a few base classes, so that it can be reused by any class through object inheritance. Let's start with these base classes. qx.core.Object Object is the base class for all other qooxdoo classes either directly or indirectly. The qx.core.Object class has the implementation for most of the functionalities, such as, object management, logging, event handling, object-oriented features, and so on. A class can extend the qx.core.Object class to get all the functionalities defined in the this class. When you want to add any functionality to your class, just inherit the Object class and add the extra functionalities in the subclass. The major functionalities of the Object class are explained in the sections that follow. Object management   The Object class provides the following methods for object management, such as, creation, destruction, and so on: base(): This method calls base class method dispose(): This method disposes or destroys the object isDisposed(): This method returns a true value if the object is disposed toString(): This method returns the object in string format toHashCode(): This method returns hash code of the object Event handling The Object class provides the following methods for event creation, event firing, event listener, and so on: addListener(): This method adds the listener on the event target and returns the ID of the listener addListenerOnce(): This method adds the listener and listens only to the first occurrence of the event dispatchEvent(): This method dispatches the event fireDataEvent(): This method fires the data event fireEvent(): This method fires the event removeListener(): This method removes the listener removeListenerById(): This method removes the listener by its ID, given by addListener() Logging The Object class provides the following methods to log the message at different levels: warn(): Logs the message at warning level info(): Logs the message at information level error(): Logs the message at error level debug(): Logs the message at the debugging level trace(): Logs the message at the tracing level Also, the Object class provides the methods for setters and getters for properties, and so on. qx.core.LayoutItem LayoutItem is the super most class in the hierarchy. You can place only the layout items in the layout manager. LayoutItem is an abstract class. The LayoutItem class mainly provides properties, such as, height, width, margins, shrinking, growing, and many more, for the item to be drawn on the screen. It also provides a set of public methods to alter these properties. Check the API documentation for a full set of class information. qx.core.Widget Next in the class hierarchy is the Widget class, which is the base class for all the GUI components. Widget is the super class for all the individual GUI components, such as, button, text field, combobox, container, and so on, as shown in the class hierarchy diagram. There are different kinds of widgets, such as, containers, menus, toolbars, form items, and so on; each kind of widgets are defined in different namespaces. We will see all the different namespaces or packages, one-by-one, in this article. A widget consists of at least three HTML elements. The container element, which is added to the parent widget, has two child elements—the decoration and the content element. The decoration element decorates the widget. It has a lower z-index and contains markup to render the widget's background and border styles, using an implementation of the qx.ui.decoration.IDecorator interface. The content element is positioned inside the container element, with the padding, and contains the real widget element. Widget properties Common widget properties include:   Visibility: This property controls the visibility of the widget. The possible values for this property are: visible: Makes the widget visible on screen. hidden: Hides the widget, but widget space will be occupied in the parent widget's layout. This is similar to the CSS style visibility:hidden. exclude: Hides the widget and removes from the parent widget's layout, but the widget is still a child of its parent's widget. This is similar to the CSS style display:none. The methods to modify this property are show(), hide(), and exclude(). The methods to check the status are isVisible(), isHidden(), and isExcluded(). Tooltip: This property displays the tooltip when the cursor is pointing at the widget. This tooltip information consists of toolTipText and toolTipIcon. The different methods available to alter this property are: setToolTip()/getToolTip(): Sets or returns the qx.ui.tooltip.ToolTip instance. The default value is null. setToolTipIcon()/getToolTipIcon(): Sets or returns the URL for the icon. The default value is null. setToolTipText()/getToolTipText(): Sets or returns the string text. It also supports the HTML markup. Default value is null. Text color: The textColor property sets the frontend text color of the widget. The possible values for this property are any color or null. Padding: This property is a shorthand group property for paddingTop, paddingRight, paddingBottom and paddingLeft of the widget. The available methods are setPadding() and resetPadding(), which sets values for top, right, bottom, and left padding, consecutively. If any values are missing, the opposite side values will be taken for that side. Also, set/get methods for each padding side are also available. Tab index: This property controls the traversal of widgets on the Tab key press. Possible values for this property are any integer or null. The traversal order is from lower value to higher value. By default, tab index for the widgets is set in the order in which they are added to the container. If you want to provide a custom traversal order, set the tab index accordingly. The available methods are setTabIndex() and getTabIndex(). These methods, respectively set and return the integer value (0 to 32000) or null. Font: The Font property defines the font for the widget. The possible value is either a font name defined in the theme, or an instance of qx.bom.Font, or null. The available methods are: setFont(): Sets the font getFont(): Retrieves the font initFont(): Initializes the font resetFont(): Resets the font Enabled: This property enables or disables the widget for user input. Possible values are true or false (Boolean value). The default value is true. The widget invokes all the input events only if it is in the enabled state. In the disabled state, the widget will be grayed out and no user input is allowed. The only events invoked in the disabled state are mouseOver and mouseOut. In the disabled state, tab index and widget focus are ignored. The tab traversal focus will go to the next enabled widget. setEnabled()/getEnabled() are the methods to set or get a Boolean value, respectively. Selectable: This property says whether the widget contents are selectable. When a widget contains text data and the property is true, native browser selection can be used to select the contents. Possible values are true or false. The default value is false. setSelectable(), getSelectable(), initSelectable(), resetSelectable(), and toggleSelectable() are the methods available to modify the Selectable property. Appearance: This property controls style of the element and identifies the theme for the widget. Possible values are any string defined in the theme; the default value is widget. setAppearence(), getAppearence(), initAppearence(), and resetAppearence() are the methods to alter the appearance. Cursor: This property specifies which type of cursor to display on mouse over the widget. The possible values are any valid CSS2 cursor name defined by W3C (any string) and null. The default value is null. Some of the W3C-defined cursor names are default, wait, text, help, pointer, crosshair, move, n-resize, ne-resize, e-resize, se-resize, s-resize, sw-resize, w-resize, and nw-resize. setCursor(), getCursor(), resetCursor(), and initCursor() are the methods available to alter the cursor property. qx.application The starting point for a qooxdoo application is to write a custom application class by inheriting one of the qooxdoo application classes in the qx.application namespace or package. Similar to the main method in Java, the qooxdoo application also starts from the main method in the custom application class. qooxdoo supports three different kinds of applications: Standalone: Uses the application root to build full-blown, standalone qooxdoo applications. Inline: Uses the page root to build traditional web page-based applications, which are embedded into isles in the classic HTML page. Native: This class is for applications that do not involve qooxdoo's GUI toolkit. Typically, they only make use of the IO (AJAX) and BOM functionality (for example, to manipulate the existing DOM). Whenever a user creates an application with the Python script, a custom application class gets generated with a default main method. Let's see the custom application class generated for our Team Twitter application. After generation, the main function code is edited to add functionality to communicate to the RPC server and say "hello" to the qooxdoo world. The following code is the content of the Application.js class file with an RPC call to communicate with the server: /** * This is the main application class of your custom application "teamtwitter" */ qx.Class.define("teamtwitter.Application", { extend : qx.application.Standalone, members : { /** * This method contains the initial application code and gets called during startup of the application * @lint ignoreDeprecated(alert) */ main : function() { // Call super class this.base(arguments); // Enable logging in debug variant if (qx.core.Variant.isSet("qx.debug", "on")) { // support native logging capabilities, e.g. Firebug for Firefox qx.log.appender.Native; // support additional cross-browser console. Press F7 to toggle visibility qx.log.appender.Console; } /* Below is your actual application code... */ // Create a button var button1 = new qx.ui.form.Button("First Button", "teamtwitter/test.png"); // Document is the application root var doc = this.getRoot(); // Add button to document at fixed coordinates doc.add(button1, {left: 100, top: 50}); // Add an event listener button1.addListener("execute", function(e) { var rpc = new qx.io.remote.Rpc(); rpc.setCrossDomain( false ); rpc.setTimeout(1000); var host = window.location.host; var proto = window.location.protocol; var webURL = proto + "//" + host + "/teamtwitter/.qxrpc"; rpc.setUrl(webURL); rpc.setServiceName("qooxdoo.test"); rpc.callAsync(function(result, ex, id){ if (ex == null) { alert(result); } else { alert("Async(" + id + ") exception: " + ex); } }, "echo", "Hello to qooxdoo World!"); }); } } }); We've had an overview of the class hierarchy of the qooxdoo framework and got to know the base classes for the widgets. Now, we have an idea of the core functionalities available for the widgets, the core properties of the widgets, and the methods to manage those properties. We've received more information on the application in the qooxdoo framework. Now, it is time to learn about the containers. Containers A container is a kind of widget. It holds multiple widgets and exposes public methods to manage their child widgets. One can configure a layout manager for the container to position all the child widgets in the container. qooxdoo provides different containers for different purposes. Let's check different containers provided by the qooxdoo framework and understand the purpose of each container. Once you understand the purpose of each container, you can select the right container when you design your application. Scroll Whenever the content widget size (width and height) is larger than the container size (width and height), the Scroll container provides vertical, or horizontal, or both scroll bars automatically. You have to set the Scroll container's size carefully to make it work properly. The Scroll container is used most commonly if the application screen size is large. The Scroll container has a fixed layout and it can hold a single child. So, there is no need to configure the layout for this container. The following code snippet demonstrates how to use the Scroll container: // create scroll containervar scroll = new qx.ui.container.Scroll().set({width: 300,height: 200});// adding a widget with larger widget and height of the scrollscroll.add(new qx.ui.core.Widget().set({width: 600,minWidth: 600,height: 400,minHeight: 400})); // add to the root widget.this.getRoot().add(scroll); The GUI look for the preceding code is as follows: Stack The Stack container puts a widget on top of an old widget. This container displays only the topmost widget. The Stack container is used if there are set of tasks to be carried out in a flow. An application user can work on each user interface one-by-one in order. The following code snippet demonstrates how to use the Stack container: // create stack containervar stack = new qx.ui.container.Stack();// add some childrenstack.add(new qx.ui.core.Widget().set({backgroundColor: "red"}));stack.add(new qx.ui.core.Widget().set({backgroundColor: "green"}));stack.add(new qx.ui.core.Widget().set({backgroundColor: "blue"}));this.getRoot().add(stack); The GUI look for the preceding code is as follows: Resizer Resizer is a container that gives flexibility for resizing at runtime. This container should be used only if you want to allow the application user to dynamically resize the container. The following code snippet demonstrates how to use the Resizer container: var resizer = new qx.ui.container.Resizer().set({marginTop : 50,marginLeft : 50,width: 200,height: 100});resizer.setLayout(new qx.ui.layout.HBox());var label = new qx.ui.basic.Label("Resize me <br>I'm resizable");label.setRich(true);resizer.add(label);this.getRoot().add(resizer); The GUI look for the preceding code is as follows: Composite This is a generic container. If you do not want any of the specific features, such as, resize on runtime, stack, scroll, and so on, but just want a container, you can use this container. This is one of the mostly used containers. The following code snippet demonstrates the Composite container usage. A horizontal layout is configured to the Composite container. A label and a text field are added to the container. The horizontal layout manager places them horizontally: // create the compositevar composite = new qx.ui.container.Composite()// configure a layout.composite.setLayout(new qx.ui.layout.HBox());// add some child widgetscomposite.add(new qx.ui.basic.Label("Enter Text: "));composite.add(new qx.ui.form.TextField());// add to the root widget.this.getRoot().add(composite); The GUI look for the preceding code is as follows: Window Window is a container that has all features, such as, minimize, maximize, restore, and close. The icons for these operations will appear on the top-right corner. Different themes can be set to get the look and feel of a native window within a browser. This window is best used when an application requires Multiple Document Interface (MDI) or Single Document Interface (SDI). The following code snippet demonstrates a window creation and display: var win = new qx.ui.window.Window("First Window");win.setWidth(300);win.setHeight(200);// neglecting minimize buttonwin.setShowMinimize(false);this.getRoot().add(win, {left:20, top:20});win.open(); The GUI look for the preceding code is as follows: TabView The TabView container allows you to display multiple tabs, but only one tab is active at a time. The TabView container simplifies the GUI by avoiding the expansive content spreading to multiple pages, with a scroll. Instead, the TabView container provides the tab title buttons to navigate to other tabs. You can group the related fields into each tab and try to avoid the scroll by keeping the most-used tab as the first tab and making it active. Application users can move to other tabs, if required. TabView is the best example for the stack container usage. It stacks all pages one over the other and displays one page at a time. Each page will have a button at the top, in a button bar, to allow switching the page. Tabview allows positioning the button bar on top, bottom, left, or right. TabView also allows adding pages dynamically; a scroll appears when the page buttons exceed the size. The following code snippet demonstrates the usage of TabView: var tabView = new qx.ui.tabview.TabView();// create a pagevar page1 = new qx.ui.tabview.Page("Layout", "icon/16/apps/utilitiesterminal.png");// add page to tabviewtabView.add(page1);var page2 = new qx.ui.tabview.Page("Notes", "icon/16/apps/utilitiesnotes.png");page2.setLayout(new qx.ui.layout.VBox());page2.add(new qx.ui.basic.Label("Notes..."));tabView.add(page2);var page3 = new qx.ui.tabview.Page("Calculator", "icon/16/apps/utilities-calculator.png");tabView.add(page3);this.getRoot().add(tabView, {edge : 0}); The GUI look for the preceding code is as follows: GroupBox GroupBox groups a set of form widgets and shows an effective visualization with the use of a legend, which supports text and icons to describe the group. As with the container, you can configure any layout manager and allow adding a number of form widgets to the GroupBox. Additionally, it is possible to use checkboxes or radio buttons within the legend. This allows you to provide group functionalities such as selecting or unselecting all the options in the group. This feature is most important for complex forms with multiple choices. The following code snippet demonstrates the usage of GroupBox: // group boxvar grpBox = new qx.ui.groupbox.GroupBox("I am a box");this.getRoot().add(grpBox, {left: 20, top: 70});// radio group boxvar rGrpBox = new qx.ui.groupbox.RadioGroupBox("I am a box");rGrpBox.setLayout(new qx.ui.layout.VBox(4));rGrpBox.add(new qx.ui.form.RadioButton("Option1"));rGrpBox.add(new qx.ui.form.RadioButton("Option2"));this.getRoot().add(rGrpBox, {left: 160, top: 70});// check group boxvar cGrpBox = new qx.ui.groupbox.CheckGroupBox("I am a box");this.getRoot().add(cGrpBox, {left: 300, top: 70}); The GUI look for the preceding code is as follows: We got to know the different containers available in the qooxdoo framework. Each container provides a particular functionality. Based on the information displayed on the GUI, you should choose the right container to have better usability of the application. Containers are the outer-most widgets in the GUI. Once you decide on the containers for your user interface, the next thing to do is to configure the layout manager for the container. Layout manager places the child widgets in the container, on the basis of the configured layout manager's policies. Now, it's time to learn how to place and arrange widgets inside the container, that is, how to lay out the container.
Read more
  • 0
  • 0
  • 2924

article-image-setting-online-shopping-cart-drupal-and-ubercart
Packt
19 Dec 2011
7 min read
Save for later

Setting up an online shopping cart with Drupal and Ubercart

Packt
19 Dec 2011
7 min read
(For more resources on Drupal, see here.) Setting up the e-commerce system Ubercart has existed since Drupal 6 so those users who have used Ubercart with Drupal 6 will have some experience setting up and configuring this module for Drupal 7. In this section we'll install and set up the basic Ubercart configuration. Goal Set up the system that will allow visitors to purchase take-out from the website. Additional modules needed Ubercart, Token, Views, CTools, Entity, Token, Rules (http://drupal.org/project/ubercart). Configuring Ubercart In order to utilize an e-commerce solution within a website, you must either build a solution from scratch or use a ready-made solution. Because building a professional e-commerce solution from scratch would take an entire book and weeks or months to build, we are fortunate to have Ubercart, which is a professional quality e-commerce solution tailor-made for Drupal. To begin using Ubercart: Download and install the module from its project page. The current stable release for Drupal 7 is 7.x-3.0-rc3. To use Ubercart, you will also need to install some dependency modules in order to get the best functionality and performance from Ubercart. These dependencies are listed on the Ubercart Website: Token, Views, Rules, CTools, Entity API, Entity Token and Token. Go ahead and install and enable the dependency modules and Ubercart. Once installed, we will begin by enabling the following Ubercart modules: All of the modules in the Ubercart—Core section including Cart, Order, Product, and Store. Then enable the following Core (Optional) modules: Catalog, File downloads, Payment, Product Attributes, Reports, Roles, and Taxes. Then in the Extra section enable the following: Product Kit and Stock. For our Payment method and module enable the Credit card, PayPal, and Test Gateway modules. We will not be shipping any items so we do not need to enable shipping modules at this point. There are a variety of other modules that can be optionally enabled. We will explore some of these in future topics. If you are planning to use the PayPal Express Checkout payment method with Ubercart you should make sure you have enabled the CURL PHP extension for use in your PHP configuration. To do this you can ask your hosting company to enable the CURL extension in your php.ini file. Otherwise if you have access to the php.ini file you can open the file and uncomment the CURL extension to enable it. Then save your php.ini file and restart the Web server. When you check your PHP info via the Drupal status report you should see the following section showing you that the PHP CURL extension is enabled.     Now, you should see the following Ubercart modules that you have enabled on your main modules configuration page:   Ubercart installs a new menu item called Store next to the menu item called Dashboard in the Administer menu bar, which includes the options shown in the following screenshot:   The first thing you'll notice is a warning message telling you that one or more problems exist with your Drupal install. Click on the Status report link. On the Status report page you'll see a warning telling you to enable credit card encryption. In order to use Ubercart for payment processing for your online store transactions you first need to set up an encryption location for your credit card data.   To do this click on the credit card security settings link. That will load the Credit card settings screen. Under Basic Settings, for now let's enable the Test Gateway. Later we'll discuss integrating PayPal but for testing purposes we can use the Test Gateway configuration.   Click on the Security Settings tab. Here we need to set up our card number encryption settings. We can first create a folder outside of our document root (outside of our Drupal directory) but on our web server to hold our encrypted data. We'll create a folder at the root level of our MAMP install called "keys". Go ahead and do this then type in /Applications/MAMP/keys in your Card number encryption key file path field. Also make sure the folder allows for write permissions.   Now click on the PayPal Website Payments Pro tab and disable the gateway for use. Click on the Test Gateway tab and leave this enabled for use. Click on Credit card settings and leave the defaults selected. Under Customer messages you can specify any custom messages you want to show the user if their credit card fails during the transaction process. Click Save configuration. When you save your configuration you should get the following success message: Credit card encryption key file generated. Card data will now be encrypted. The configuration options have been saved. Now, we have successfully set up our payment processing with the Test gateway enabled. We're ready to start using Ubercart. To begin using Ubercart, we will need to: Edit the Configuration settings, which are shown in the following screenshot: Clicking on the Store link allows you to configure several options that control how information on the site is displayed, as well as specify some basic contact information for the site To edit the settings for a section, click on the tab for that section. On the Store settings page, we simply need to update the Store name, Store owner, e-mail address, phone and fax numbers for the store. You can also enter store address information. If your store is not located in the United States, you will also need to modify the Currency Format settings. If you are shipping items you may need to tweak the Weight and Length formats. You can also specify a store help page where you'll provide help information. You can simply create a new page in Drupal and alias it, and then type the alias in here. Once you finish entering your Store settings click the Save configuration button Configuring Ubercart user permissions You should also create a role for store administration, by clicking on User management and then Roles. We will call our role Store Administrator. Click Add role to finish building the role. After the role has been added, click the edit permissions link for the role to define the permissions for the new role. Ubercart includes several sections of permissions including: Catalog Credit Card File Downloads Store Payment Product Product attributes Product kit Order Taxes Since this is an administrative role you may just want to give this staff person all permissions for an admin level role on the site. Go ahead and check off the permissions you need to grant and then save your role's permissions.If your site has employees, you may also want to create a separate role (or several roles) that do not give full control over the store for your employees. For example, you may not want an employee to be able to create or delete products, but you would like them to be able to take new orders. Ubercart provided blocks The Ubercart module ships with a core block that you can enable to make it easier for visitors to your site to see what they have ordered and to check out. Go to your blocks administrative page and you can enable the Shopping cart block to show in one of your block regions. I'll put it in the Sidebar second region. These are the basic configuration options which need to be done after you enable the block. Click on the configure link and then you can title your block, select whether to display the shopping cart icon, make the cart block collapsible, add cart help text ,and more. I'll leave the defaults selected for now. You should see a block admin screen similar to the following:  
Read more
  • 0
  • 0
  • 3258
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 $15.99/month. Cancel anytime
article-image-wordpress-3-designing-your-blog
Packt
12 Dec 2011
19 min read
Save for later

WordPress 3: Designing your Blog

Packt
12 Dec 2011
19 min read
(For more resources on WordPress, see here.) Blog design principles Blogs tend to have a fairly simple, minimalist layout and design. This has always been one of their key characteristics. Blogs are all about frequently updated content, so the main purpose of their design is to present that content as efficiently and conveniently as possible. The vast majority of blogs present their most recent content on the page that visitors arrive at; hence, the front page contains the latest posts. There's no home page with a verbose welcome message and a long navigation menu to click through to the important stuff. The visitor gets straight into the meat of the blog. By default, this is the structure that WordPress provides. It is possible to set a static page as your blog's front page, but, in the vast majority of cases, I wouldn't recommend it. So when considering the architecture of a blog, unlike other types of website, we don't have to worry too much about a complex navigation structure. There is a convention that we can follow. Yes, we may want to add some extra static pages, but probably only a few of these. What we are most concerned with in blog design is not a complicated navigation structure and how all the pages link together, but how the actual blog page should look and feel. This can be broken down into four key components, which we will examine, one by one: Layout Color Typography Usability and accessibility Layout Good design is all about making something easy for people to use. Designers achieve this by employing standards and conventions. For example, cars have a standard design: four wheels, a chassis, a steering wheel, gas pedal, brake, gear shift, and so on. Car designers have stuck to this convention for many years. First, because it works well and second, because it enables us to drive any car we choose. When you sit down in any standard road car, you know how it works. You turn the key in the ignition, select a gear, hit the gas, and off you go. It's certainly not beyond the ken of car designers to come up with new ways for getting a car in motion (a joystick maybe, or a hand-operated brake) but this would make it more difficult for people to drive. Cars work reasonably safely and efficiently because we are all familiar with these conventions. The layout of blog pages also tends to follow certain conventions. As with cars, this helps people to use blogs efficiently. They know how they work, because they're familiar with the conventions. Most blogs have a header and a footer with the main content arranged into columns. This columnar layout works very well for the type of chronological content presented in blogs. Because of these conventions, the decisions about our blog layout are fairly simple. It's basically a case of deciding where we want to place all our page elements and content within this standard columnar layout. The set of page elements we have to choose from is also based on fairly well entrenched blogging conventions. The list of things we may want on our page includes: Header Posts Comments Static content (for example, the About page) Links to static pages (simple navigation) RSS feeds Search Categories Archives Blogroll Widgets and plugins Footer If we look at this list in more detail, we can see that these page elements can be grouped in a sensible way. For example: Group 1 Header Links to static pages Group 2 Posts Comments Static content Group 3 RSS Feeds Search Categories Group 4 Archives Blogroll Widgets and plugins Group 5 Footer This isn't the only possible grouping scheme we might come up with. For example, we may place the items in Groups 3 and 4 into a single larger group, or we may have widgets and plugins in a group on their own. From this grouping, we can see that the type of items in Group 2 are likely to be the main content on our page, with Groups 3 and 4 being placed in sidebars . Sidebars are areas on the page where we place ancillary content. Having considered the elements we want on the page and how they might be grouped, we can think about possible layouts. Within the conventional columnar structure of blogs there are quite a few possible layout variations. We'll look at four of the most common. The first is a three-column layout. Here, we have two sidebars, one on either side of the main content. Using this type of layout, we would probably place the items in Groups 3 and 4 in the sidebars and Group 2 in the main content area. A variation on the three-column layout is to have the two sidebars next to each other on one side of the page (usually the right), as shown in the following diagram. This is a popular layout for blogs, not just for aesthetics, but because the search engine spiders encounter the post column first as that content is at the top of the template. Using two sidebars is useful if you anticipate having a lot of ancillary content on your blog. The list of page elements given earlier is really the bare minimum you would want on your page. However, if you decide to use lots of widgets or have a long blogroll, it's a good idea to spread them across two sidebars. This means that more of your content can be placed above the fold. The concept of above the fold in web design applies to content in a web page which is visible without having to scroll down, that is, the stuff in the top part of the page. It's a good idea to place the most important content above the fold so that readers can see it immediately. This is particularly true if you plan to monetize your blog by displaying adverts. Adverts that appear above the fold get the most exposure, and therefore, generate the most revenue Another popular layout amongst bloggers has just two columns. In this layout, we would place the items in Groups 3 and 4 together in the one sidebar. It doesn't really matter which side of the page the sidebar is placed, but it seems more common to have it on the right. Studies have shown that a web user's eyes are most often focused on the top-left region of a web page, when they first open any page. So it makes sense to place your main content there, with your sidebar on the right. Also, remember that the search engine spiders will find the leftmost content first. You want them to find your main content quickly, which is a good reason for placing your sidebar on the right, out of their way. An important benefit of a two-column layout is that it allows more room for your main content area. This may be important, if you intend to use a lot of video or images within your blog posts. The extra room allows you to display this visual content bigger. Many blogs place some of their ancillary content just above the footer, below the main content. This also has the advantage of leaving more space for the main content, as with the two-column layout. The following diagram shows this type of layout. Here, the content just above the footer isn't strictly speaking a sidebar, but I've labeled it this way because it's the terminology most often applied to this type of ancillary content. Wireframing The layout diagrams we've just seen are referred to as wireframes by web designers. They give a simple overview of where the elements of a page should be placed. It would be a good idea for you to create your own wireframe for your blog design. This can be done using most graphic software packages or something like Microsoft Visio , or a simple pen and paper does the job equally well! Color This is the next design principle we need to consider. It may be that you already have a corporate color scheme based on your company logo, stationery, or existing website. In this case, you'll probably want to continue that theme through your blog design. Even if you already have your corporate color scheme, this section may still be useful in case you decide to change your blog colors in the future. The subject of color in design is a large one. Design students spend a great deal of time learning about the psychology and science of colors and techniques for achieving the best color schemes. Obviously, we don't have enough space to go into that kind of detail, but I will try to give you a few pointers. The first thing to think about is the psychology of color, in particular, color associations. This is the idea that different colors evoke different feelings and emotions in the eye of the beholder. To a certain extent this can be rather subjective and it can also depend on cultural influences, but there are some generalities that can be applied. For example, red is often perceived as being exciting, passionate, or dramatic. Yellow is an active and highly visible color, which is why it is used in warning signs. It is also associated with energy and happiness. Blue is sometimes thought of as being cold. It can also be a calming color and may sometimes be seen as corporate or conservative. White, for many people, gives the idea of cleanliness, purity, and perfection. Black can be seen as strong, elegant, and chic. Obviously, these color associations can vary from person to person, so designers don't rely on them solely in their color decisions, but they are certainly worth bearing in mind. There are more practical considerations regarding color that are probably more relevant than color psychology. For example, we all know that some color combinations don't work well together. There is a great deal of design theory aimed at devising good color combinations, but unless you're a professional designer, it's not really worth going into. Probably the best method for working out good color combinations is trial and error. If you're trying to figure out a background color and text color for your blog, simply test a few out. You could use a graphics package such as Photoshop or Microsoft Paint , or one of the many online color tools such as, http://colorschemedesigner.com/ or Adobe's Kuler at http://kuler.adobe.com. When choosing background and text colors you need to think about contrast. For example, yellow text on a white background can be very difficult to read. Some people also find light text on a black background a strain on their eyes. It's also important not to use too many colors in your design. Try to limit your palette to a maximum of three or four. Sometimes you may only need two colors to make an attractive design. One method for devising color combinations is to look for examples all around you, particularly in nature. Maybe look at a photograph of a landscape and pick out color combinations you like. Also consider the work of professional designers. Think about websites and blogs you like, and examine the color schemes they have used. You will also find good examples in offline design—pick up a book and see how colors have been used in the cover design. If you would like to base your blog's color scheme on your company logo, you could use lighter and darker versions of one color from the logo. Use the most vivid color in the logo for emphasis or headings. Web color theory At this point, it's worth looking at the technical theory behind colors on the Web. Web browsers use the Hexadecimal RGB color system to render colors in web pages. This is because computer monitors use an RGB color model, which means every pixel is colored using a combination of red, green, and blue light (hence RGB). There are 256 different levels of red light, 256 different levels of green light, and 256 different levels of blue light. These can be combined to create 16,277,216 different colors, which are all available for your web browser. The hexadecimal system gives us a way of counting from 0 to 255 using numbers and letters, which covers all 256 levels of RGB light. In the hexadecimal scale, 0 is 00 and 255 is FF. A six-character hexadecimal color code specifies the levels of red, green and blue, which form a particular color. For example, the color white combines red, green, and blue at their highest possible levels, that is 255. Remember that in hexadecimal 255 is FF, so the color code for white is FFFFFF (Red: FF, Green: FF, and Blue: FF). The color code for black is 000000 as the levels of red, green, and blue are set to their lowest, or 00 (in hexadecimal). The code for red is FF0000, blue is 0000FF, and yellow is FFFF00, and so on. We can use six-character Hexadecimal RGB codes to define all of the 16,277,216 web colors. So how do we know the hexadecimal code for a particular color? Well, there are many tools available that define the Hexadecimal RGB codes for the colors you choose. Some are standalone applications for PC or Mac, and others are online. Take a look at https://www.webpagefx.com/web-design/color-picker/ or do a quick search in Google on color picker . For more information on web colors , read the article at http://en.wikipedia.org/wiki/Web_colors. Typography Another important consideration for your blog design is the fonts you use. Your choice of font will have a big impact on the readability of your blog. It's important to bear in mind that although there are literally thousands of fonts to choose from, only a small number of them are practical for web design. This is because a web browser can only display fonts that are already installed on the user's computer. If you choose an obscure font for your blog, the chances are that most users won't have it installed on their computer. If this is the case the web browser will automatically select a substitute font. This may be smaller or far less readable than the font you had in mind. It's always safest to stick to the fonts that are commonly used in web design, which are known as web safe fonts. These include the following: Arial Verdana Times New Roman Georgia There are two types of font, serif and sans-serif. Serif fonts have little flourishes at the end of the strokes whereas sans-serif fonts don't have this extra decoration. Arial and Verdana are sans-serif fonts, whereas Times New Roman and Georgia are serif fonts. As you'll see later in the article, when we look at CSS, fonts are usually specified in groups or families. They are listed in the order of the designer's preference. For example, a designer may specify font-family:"Georgia, Times New Roman, serif". This means when the browser renders the page it will first look for the Georgia font; if it isn't installed, it will look for the Times New Roman font and if that isn't installed, it will look for the computer's default serif font. This method gives the designer more control over the font choices the browser will make. The size of your font is also an important factor. Generally speaking, the bigger it is, the easier it is to read. Computer displays are getting bigger and bigger but the default screen resolutions are tending to get smaller. In other words, the individual pixels on users' screens are getting smaller. This is a good reason for web designers to choose larger font sizes. This trend can be seen on many Web 2.0 sites, which tend to use large and clear fonts as part of their design, for example http://www.37signals.com. But be careful not to go too big as this can make your design look messy and a little childish. Remember that you're not limited to using just one font in your blog design. For example, you may decide to use a different font for your headings. This can be an effective design feature but don't go crazy by using too many fonts, as this will make your design look messy. Probably two, or at most three, fonts on a page are plenty. Font replacement Font replacement refers to a relatively new group of technologies that are pushing the envelope of web typography. In theory, they allow designers to use any font in their web page designs. In practice, things are a little more complicated. Issues around browser compatibility and font licensing make font replacement technologies a bit of a minefield for anyone who is new to web design. It's true that, thanks to font replacement technologies, professional designers are no longer constrained by the notion of web safe fonts. But, if you are a web design novice, I recommend you stick to web safe fonts until your skills improve and you are ready to learn a whole new technology. A full discussion on font replacement is way beyond the scope of this article; I mention it only to give you a better overview of the current state of web typography. But if you are interested in knowing more, three popular font replacement technologies are Cufón (http://cufon.shoqolate.com), Font Squirrel (http://www.fontsquirrel.com), and Google Fonts API (http://code.google.com/apis/webfonts/). There is also something known as @font-face, which is part of CSS3, the latest specification of CSS. Again, it offers the tantalizing possibility of giving designers free rein in their choice of fonts. Sadly, @font-face is also hindered by browser compatibility and font licensing issues. The Font Squirrel technology, mentioned previously, resolves these issues to a certain extent, so this is something to be aware of as your web design skills develop. But for the time being, I recommend you concentrate on the basics of web typography and don't worry about @font-face until you feel ready. Usability and accessibility This is another very important area to consider when designing your blog. Many people, who live with various disabilities, use a range of 'assistive' software to access the Web. For example, people with visual impairments use screen readers, which translate the text in a web browser into audible speech. There are also people who are unable to use a mouse, and instead rely on their keyboard to access web pages. It's the responsibility of web designers to ensure that their websites are accessible for these different methods of browsing. There's no sense in alienating this group of web surfers just because your blog is inaccessible to them. There are also many other circumstances when your blog might be accessed by means other than a standard web browser, for example, via mobile phones, PDAs, or tablets. Again, a good designer will ensure that these modes of browsing are catered for. The web design industry has been well aware of these accessibility issues for many years and has come up with guidelines and technologies to help conscientious designers build websites that are standards compliant . These web standards help ensure best practice and maximize accessibility and usability. Luckily, WordPress takes care of a lot of the accessibility issues simply by the way it's been developed and built. The code behind WordPress is valid XHTML and CSS, which means that it complies with web standards and is easily accessible. It's important, then, that you don't break the system by allowing bad practice to creep in. Some of the things to bear in mind relate to a couple of design principles we've already discussed, for example, using a color scheme and font size that makes your text easy to read. Other issues include keeping the number of navigation links on your page to a minimum—a whole load of useless links can be annoying for people who have to tab through them to get to your main content. You should also ensure that any third-party plugins you install are standards-compliant and don't throw up any accessibility problems. The same is true if you decide to use a ready-made theme for your blog design. Just make sure it's accessible and satisfies web standards. For more background reading on web standards, you could take a look at http://www.alistapart.com or the World Wide Web Consortium (W3C) website at http://www.w3.org. Implementing your blog design We've now considered the principles involved in designing our blog. The next thing to decide is how we actually carry out the design work. There are three main options available, each of which involves varying degrees of work. However, they all require knowledge of the design principles we just covered. The first approach is probably the easiest; it simply involves finding a readymade theme and installing it in WordPress. By working through the earlier design principles, you should have an idea of what you want your blog to look like and then you simply need to find a theme that matches your vision as closely as possible. A good place to start looking is the official WordPress Free Themes Directory at http://wordpress.org/extend/themes/. You'll also find many more theme resources by running a search through Google. There are hundreds of very attractive WordPress themes available for free and many others which you can pay for. However, if you adopt this approach to your blog design, you won't have a unique or original blog. The chances are the theme you choose will also be seen on many other blogs. At the other end of the scale, in terms of workload, is designing your own theme from scratch. This is a fairly complicated and technical process, and is well beyond the scope of this article. In fact, it's a subject that requires its own book. If you intend to build your own theme, I recommend WordPress 2.8 Theme Design by Tessa Blakeley Silver ISBN 978-1-849510-08-0 published by Packt Publishing. The third approach is to modify a readymade theme. You could do this with any theme you choose, even the default Twenty Ten theme that ships with WordPress. However, if you edit a fully developed theme, you spend a lot of time unpicking someone else's design work and you may still be left with elements that are not completely your own. A better method is to start with a theme framework, which has been specially designed to be a blank canvas for your own design. Over the last few years many WordPress theme frameworks have appeared, some free, some paid-for. Two of the most popular paid-for theme frameworks are Thesis (http://diythemes.com/) and Genesis (http://www.studiopress.com/themes/genesis), while popular free frameworks include Hybrid (http://themehybrid.com/), Carrington (http://carringtontheme.com/), and Thematic (see below).
Read more
  • 0
  • 0
  • 2014

article-image-interface-designing-games-ios
Packt
09 Dec 2011
9 min read
Save for later

Interface Designing for Games in iOS

Packt
09 Dec 2011
9 min read
  (For more resources on iPhone, see here.) Users have few expectations as to what a typical mobile application should feel like, there is often an expectation with regards to what a game should play like. Mobile gaming platforms have been popular since the Game Boy's rise to popularity in the early 90s, and users have an idea as to what games work well when on the go, and iOS games are expected to match or exceed these preconceived notions of what is possible. However, it isn't necessarily easy to produce a game on iOS, as the device presents one of the first touch screen mobile gaming experiences. There isn't much precedent as to what game genres and control styles work well. This can be beneficial for innovation, but can also lead to a great deal of heartache for any designer.   Planning your game around touch Unlike traditional mobile gaming platforms, we won't have physical buttons and a set interface blueprint to serve as a guide for our game. Mobile platforms such as the Game Boy or PlayStation Portable have a physical control pad and buttons that lend the user to an inherent understanding of the game on screen. The user can quickly pick up and play a game, because they know that there is a finite set of buttons that can control game mechanics. We're in a bit of a more difficult-to-manage scenario with iOS, as there is no control pad or face button to commonly dictate interaction on screen when in a game. Since we're on a touch screen device, we can create any interaction mechanic that we'd like, no matter how unorthodox the interface may be. This offers up an extraordinary opportunity for new gameplay experiences; however it does make our design work a bit more difficult to construct. In this recipe, we'll discuss how touch screens drastically alter the design and playability of our game. Designing a game around touch is never an easy task. Controls are difficult to implement, screen size is often limited, and we'll need to innovate on top of standard game play mechanics to provide a fun experience. While the operating system is only a few years old, there has been a significant evolution in gaming on the platform. Early games, such as Super Monkey Ball by Sega, were often ports of previous console games by big name publishers. Apple's affordable developer program allowed independent developers to step in and experiment on the platform, pushing forward intuitive new experiences like Doodle Jump, Mr. AahH!!, and Zen Bound. In recent years, the market has matured so that both traditional franchises and independent creative ventures can succeed. Getting ready To work on this recipe, it would be useful to have an iOS device along with a traditional gaming console in order to contrast the difference in mechanics between the two machines. How to do it... Depending on the type of game we plan on developing, there are a variety of strategies for success on the iPhone or iPad. However there are a few key attributes that will make any iOS game enjoyable: Remember that users will be using the iPhone or iPad as both a screen and a controller. Don't punish users for accidental interactions with the screen. Keep in mind that these are mobile devices. While a good portion of our interface will vary greatly depending upon the type of game we're looking to create, these three rules are universal and will benefit any iPhone or iPad game. With these guidelines in mind, we can move on and begin to draft up our controls and heads up display. How it works... The low level of entry and unique touch controls have helped iOS evolve into a platform where designers can reach outside of their comfort zone in an effort to release an innovative game on the platform. In step one, it's important to understand that traditionally, users and designers are trained toward expecting games to have an external controller that is used for manipulation of the game world. The screen is a separate device; either a television or portable LCD screen serves as a way to project the game. However on iOS, the screen and controller are one. Regardless as to whether users interact with our game through buttons on screen or by using a device hardware feature such as the accelerometer, it is a guarantee that the iPhone or iPad will be held in a hand while our game is being played. We should always keep this in mind when designing both our game and interface, as the user will need to comfortably hold the device while playing. If we use traditional controls through a software joystick or buttons, we should place these elements on screen in a manner that allows for the iPhone or iPad to be held comfortably while playing. Depending upon our game and orientation, we may find that specific parts of the play area are perfect for the placement of such controls while in other scenarios, we may want to give the user the ability to customize the placement of buttons to their preference. If we expect the user to tilt or shake the controller to interact with our game, we should take this into consideration as well. While it may sound somewhat clichéd, the game and its controls are one and the same. There is no separation and any design that assumes that we can quickly implement controls without taking this fact into consideration is destined to fail. Not being given a set control pad or buttons gives us the flexibility to be creative, but poor design can quickly confuse or frustrate users. In the next screenshot, we can see that Flight Control developer Firemint has used small exclamation point markers to offer up a hint as to where inbound aircraft will soon appear. This offers a quick heads up to the user who may have had their hands in a poor position. Flight Control - © 2009 Firemint Pty Inc. We expand upon this new type of game control with these new devices in step two in the previous section. Because the game controller and device screen are so intertwined, it's very likely that the user will come into accidental contact with the screen at some point. It's just too difficult to eliminate unintended taps, as the finger is an imprecise pointing device. We can assume that the user will make unintentional contact with the screen, and so we should do our best to design a play mechanic and interface that will not punish users for their mistake. For example, if we're building a racing game, it would be silly to place the pause button near the button used for acceleration, as misplaced fingers could often pause the game and frustrate users. How we go about verifying this in our application can vary based on the type of game we're looking to design, but we should be mindful to keep this philosophy salient in our work. The limited ability to include a help menu in our application will encourage users to pick up app controls through point and tap experimentation. If the user experiences frustration in their first few minutes of using the app, they'll be likely to give up on using our app. Finally in step three, we should focus on creating an interface that is mobile. While we're designing with a device that is nearly as powerful as home gaming consoles, we must keep in mind that our users will be using their iPhone or iPad when on the run. They may be playing our game on a train, or in the car, or when walking between classes, so it's important to remember that this is a slightly different game platform than what we've ever developed for before. Because users will be playing our app when on the go and users will be less likely to sit down and play our game for extended periods of time, we should prepare our gameplay and interface around this probability. Big buttons and forgiving controls are the best way to go about designing for a mobile interface. Larger targets on screen will make it easier for the user to perform an intended action, even when walking or riding around. If we'd like to take mobile usability a bit further, we could also implement modifiable controls into our app as well. Giving the user the ability to calibrate settings will enable our game to play well, regardless as to the situation they're currently in. In the next screenshot, we can see how Doodle Jump allows users to adjust the game's controls: Doodle Jump - © 2011 Lima Sky, LLC It's also important to note that we should design our interface for the rapid entry and exit that is common of iPhone users. People will be playing our game on buses, while waiting in line at a store, and in other scenarios where their time spent inside of the app may be no longer than one to two minutes. This will affect game play drastically, so it's important to test such game scenarios while we build our app. Because our first iOS game may be our first touch screen based game, or our first game in general, we should be cautious and conservative with our interface and game play mechanics. That's not to say that the creation of any game is easy; however these are significant pitfalls that could plague our work if we're not careful. There's more... While rare, there is the possibility that our iPhone can be used as a controller for a device other than itself. Using the iPhone as a controller…for the iPad Thanks to the Bluetooth integration that Apple has included in new iPhone, iPod touch, and iPad devices, it is possible to use our iPhone as a controller for iPad games, so long as the developer has produced games for both platforms and supports the feature. It isn't necessarily easy to design and develop a game that includes such a feature, but it is by no means impossible. If we're working on an expansive game, it is definitely possible to create an immersive experience where the iPhone is used to control action on the iPad.  
Read more
  • 0
  • 0
  • 2217

article-image-iphone-customizing-our-icon-navigation-bar-and-tab-bar
Packt
09 Dec 2011
7 min read
Save for later

iPhone: Customizing our Icon, Navigation Bar, and Tab Bar

Packt
09 Dec 2011
7 min read
  (For more resources on iPhone, see here.) The application icon and essential interaction elements such as the Navigation Bar and Tab Bar are crucial for the success of our work. The user will be tapping the icon every time they go to use our app, and interact with our navigation elements throughout their entire experience in our application. If we want success, we must focus on making these components attractive and functional. Attention to detail and the presentation of these pieces will be key, and we'll need to produce our best work if we want to stand out in a sea of apps. Designing an application icon and preparing it for the user home screen It's often said that a book shouldn't be judged by its cover, but the harsh reality of mobile development is that an app is often judged by its icon. This rounded rectangle will appear on the home screen of every user, and it's important that we create something that is attractive and also a good indication as to what the user should expect after downloading our application. In this recipe, we'll create a strategy for successful app icon design. Getting ready Adobe Photoshop will be our primary tool in the design of our app icon. It may also be helpful to grab some paper and a pencil so that we can sketch out any concepts we may have before we begin working on our computer. How to do it... The application icon is a primary component of any work. Appearing in the App Store, on a user's home screen, in Spotlight searches, and more, it's an important part of our job. Let's take a look at several steps that will be useful in the creation of our app icon: We should start by with either a rough sketch or Photoshop mockup of our intended design. We should create this mock up at several sizes to help represent the different resolutions at which our icon will be viewed. After we've developed an idea that we believe is going to scale well, its time to sit down in Photoshop or Illustrator and begin work on our icon. At this point, we need to determine what size canvas we want to design our icon on. Apple requires that our icon be available at a variety of sizes, with a 512 by 512 pixel square currently being the largest required format, but we should be prepared in case this requirement changes in the future and design our icon accordingly. There are two different ways we can go about making our icon "future proof". We can go about designing the icon in a vector format using an application like Adobe Illustrator. Vector drawings will always be the best way to ensure that our icon will scale to any size, but they can be a bit more difficult to create. If we're more comfortable using a raster image manipulation program like Photoshop, it's best to create our icon at a resolution well above what we'll ever need for the App Store, starting with a canvas of 4096 by 4096 pixels square or greater. Such a large raster size will give us a piece of art that will print comfortably on sizes as large as 13 inches when printed at 300 DPI, while also easily scaling down to whatever size we need for the App Store. Once we've decided which format we're most comfortable with, its time to go about creating our icon. Once we've completed our icon, it is time to prepare it for inclusion into our application. This icon should then be named apple-touch-icon.png and placed inside of our application bundle. iOS will then automatically add the glare effect to the top half of the icon, as seen throughout the interface. The Info.plist is a file that allows us to customize a bunch of different application attributes. We'll learn how to use it to remove the icon gloss effect in an upcoming recipe titled Removing the app icon's gloss effect. After finishing our icon, we may also want to run a small focus group, much like we would in order to gain feedback on our user interface design.We can quickly set up a simple website with a form asking for opinions on our design or even email an image of the icon to friends and family in order to facilitate feedback. When looking to gather opinion on our icon, we want to better understand a user's first impression of our icon. For a good portion of purchase decisions, the icon may be the only bit of insight into our app that the user has before tapping the buy button. We want to make sure that on first impression, the typical user associates our icon with quality, simplicity, and value. If our icon looks amateur, users probably won't consider our application for purchase. How it works... Icon design is tough, primarily because we're required to design a small square that represents our application's purpose, quality, and value. It's truly a challenge to design something that works well at 512 pixels and 27 pixels. Let's take a look at how the steps above work together to create a good icon. Resolution flexibility is arguably the difficult part of icon design, as our work needs to look great at 512 pixels by 512 pixels and at 27 by 27 pixels. Small details that look great at a high resolution can really make an icon indecipherable when scaled down to the lowest resolution required: In the above screenshot, we can quickly see how an icon becomes less legible as it decreases in size. It's necessary to provide the icon to Apple in several different sizes, which can vary depending upon the iOS device we're developing our application for and the current operating system requirements from Apple. These file sizes have varied significantly throughout the life of iOS, so we should verify the current requirements in the iOS Development Center before their creation. Sebastiaan De With keeps an excellent Photoshop file for iOS icon design, complete with resolution requirements, which he updates every time Apple changes the icon requirements. We can find the file here at http://blog.cocoia.com/2010/iphone-4-icon-psd-file/ and it should reference it while designing a new icon. When building our icon, we should really take time to think about what our icon should look like and what users will think when they first set eyes on it in the App Store. This set process works because it systematically creates a piece of work that will be optimized for the various needs of iOS. There's more... It may take a bit of practice to get a firm grasp on what makes a great or poor icon. Here are a few helpful ideas, just in case we're struggling to develop an icon that we're happy with. Dropping the text We should always refrain from including a great deal of text in our app icon. Text tends to become illegible when scaled down to small resolutions such as 27 x 27, so it is often best to keep text out of our icon. If we absolutely must include text in our icon, we should use short words that are large in size and in a bold typeface. Great gradients From an art design perspective, we'll probably be including an artistic gradient in our icon to offer the illusion of brushed metal or progressive lighting. But choosing a strong color palate for a gradient can be difficult. Dezigner Folio has created a large library of fresh, modern gradients that they've offered up for free use in any project. For the entire library, feel free to visit their website at http://www.dezinerfolio.com/2007/05/03/ultimate-web-20-gradients-v30-release. If all else fails.... If we're having a rough time with icon design and all else fails, we can always hire a freelance artist or design firm to help out with the production of our application icon. A quick search of Google can help us find a multitude of artists who have become specialists in the field of icon design. Finding a talented designer can actually be quite affordable, with many freelance artists charging a hundred dollars or less for a high quality icon. As icons can be produced in Photoshop, local graphic designers or students can help out at affordable rates as well.  
Read more
  • 0
  • 0
  • 1904

article-image-iphone-user-interface-starting-stopping-and-multitasking-applications
Packt
09 Dec 2011
16 min read
Save for later

iPhone User Interface: Starting, Stopping, and Multitasking Applications

Packt
09 Dec 2011
16 min read
  (For more resources on iPhone, see here.)   Starting the application with a proper Default.png When an application loads for the first time, the user is presented with a variable duration of loading time. This period can change depending on the device processor or RAM, memory requirements of the application, current free memory available on the device, and any number of other variables. Ideally, the user will only be required to sit through this period for a brief moment. However, this duration can last up to several seconds in length if we're loading an image intensive app on an older device. Apple has designed a loading screen method that is required by each app, through the inclusion of a PNG file in our app bundle. In this recipe, we'll discuss two interface strategies for this loading period. Getting ready For this recipe, we should have a computer with Photoshop or another image creation tool. We should also have knowledge of the devices and orientation types that our application will support. How to do it... Loading times are an inherent problem with all types of software, regardless of platform. As hardware has increased in speed, these times have diminished, but they haven't become non-existent. Apple created a simple design fix for this problem, offering up a quick and easy way to load an image during the loading period. Here are quick, simple steps in order to create an image that will display during the loading period: We should start by designing up an art image measuring either 320 x 480 pixels or 320 x 460 pixels (or the equivalent Retina display double resolution size), containing the art piece which we would like the user to see during the loading screen. Next, we should then save and name that file Default.png. Finally, we should include that image in the resource bundle of our application project in XCode. If we're creating a web application, we can also include the image in our HTML code so that the image is displayed when the user launches the web app. To do this, we should name our file startup.png and place the following code in our HTML header: <link rel="apple-touch-startup-image" href="/startup.png"> iOS is designed to search the bundle for a PNG with this name, and then display it on load if it's available. Once we finish these steps, we have accomplished everything we need to do to have the image load on startup. When it comes to design styles and technique on what we should include on the image, there are two different strategies that we can take: The right way Apple's documentation on the Default.png is fairly clear. According to their design documents, this image should serve as a clean visual of what the application would look like with no pre-populated data. In essence, this provides the perception that the application has already loaded, but the user is just waiting for the data to populate. It's a subtle way to trick the user into thinking our app loads quicker than it actually does. This trick works because it typically takes the brain about 2-4 seconds to see an image on screen, process the layout of what is before them, and then make a decision. Because the loading process for an application is relatively short, typically under three seconds, presenting an overlay of the interface as the Default.png loading image allows the brain to use this time to process what is about to be presented on screen. Phone - © 2007-2011 Apple Inc. As shown above, Phone, Messages, and Photos all load preview images with their Default.png displays, which offer the perception that the application loads very quickly. By preparing the user for the app during the Default.png load image period, the user will subconsciously perceive that our application loads faster than it actually does. The wrong, but possibly preferable way While we're supposed to use the loading image to prepare the user for our app, we may want this time to serve another purpose, such as a way to advertise our development team or Twitter account. It's an important and powerful moment for application branding, so we should feel free to use this moment as a way to build brand equity through use of a logo and appropriate styling. There is no set rule that says we can't use the Default.png as an advertisement of sorts, and many applications succeed using this strategy. We'll need to include a Default.png in the application package, to give our app something to display before loading has concluded. Depending on our application type and loading period, we should be able to include a screen that fits into one of these two methods with ease. How it works... Apple has designed iOS so that it is easy to present a loading screen to the user—we only need to create a PNG image, name it Default, and include it inside of our application bundle. The operating system will do the rest for us. Because this predetermined method works so well, we can instead focus on optimizing the image to best fit into our application. It's important to remember that the Default image is the first thing that the user will ever see in our app, and we should take considerable care in the creation of the art. Attention to detail with such seemingly minute application attributes is what sets outstanding applications apart. For some situations, creating an image that looks like similar to the first screen after launch will be ideal; as it will offer the perception that our application loads quicker than it actually does. This will increase user appreciation and enjoyment of our app. In other situations, it may be desirable to go with this splash screen approach instead of the prescribed approach of faking application load. For applications where loading takes a considerable period of time, usually anything over four seconds, it is difficult to use the load to ease users into our app like Apple does with Mail, Messages, or Phone. The pause becomes so long that the user instead believes that the application has broken. So in such situations, these banner loading Default.png images may provide a better alternative, offering up a way for the user to know that they have indeed loaded the correct application, but that it will still be several seconds before they're able to interact with the initial view. Regardless of what method we choose, it will be necessary to include a Default.png in with the project. With a bit of work and consideration, we can create something that will win the hearts of our user base. There's more... Now that we've learned more about different styles of Default images, we can put a bit of extra effort into going the extra mile with the image as well. Here are a few tips on how to produce a great Default.png. We can retina optimize our Default.png too Like any other art piece, we can include a Retina display specific graphic inside our application. By adding the standard @2x modifier to the end of the image, iOS will know to pull this image instead when running a higher resolution device. As the Default.png is the first image presented to the user, we should take extra effort to show that we're dedicated to a full retina optimized experience. Prepare for multiple orientations On the iPhone, we're limited to only one Default.png orientation requirement, as applications tend to be optimized for one orientation and we can create the Default image to account for the prominent orientation. However, on the iPad, each application should be designed for optimal use in either orientation. This requires us to create two Default images, one for the app launching in portrait and another for if the app launches in landscape. Apple has created an easy system for the simple creation of such different images. We only need to create the images and add a simple –Portrait or –Landscape modifier (for example, Default-Portrait.png) in order to launch the appropriate view.   Planning our application UI for a first impression In the real world, we spend a good deal of time preparing for first impressions. We tuck our shirts in, spend time making sure our hair looks perfect, and iron our shirts so that they're wrinkle free. We do this because it's a common understanding that others will greatly have their feelings toward us determined on the basis of how we look or talk during our first meeting. If we don't impress them off the bat, they'll never be willing to warm up to us. Mobile application development falls under the same sense of unspoken understanding. If our application isn't easy to manage or understand in the first 30 seconds, users will have no qualms over closing our work and deleting it off their device. Are the colors attractive? Is information easy to access? Do they seem to know what the correct next step is? These are all important questions that the user will subconsciously answer during their first several minutes inside our work. In this recipe, we'll discuss a couple of design decisions that we can make, in order to impress our users early. Getting ready Little is needed for this recipe. Ideally, the implementation of this recipe will take place throughout the course of development, as we fine tune along the way. How to do it... The Default.png image is the first visual that every user will see when they check out our app, but it isn't necessarily the first visual that their brain will take a good deal of time processing. That honor will fall on our actual application, once loaded in full glory for all eyes to behold. It's a somewhat magical moment, as our work is first presented to the audience. Like the opening line of a play, first chapter of a book, the front door to a house, the first few minutes of a game, this is an important moment in the user's determination of what they think about our app. So how do we present our application with its best foot forward? Here are a couple of simple tips, to help users quickly feel at home inside of our application: Use simple, clean In-App icons to help signify key features: When selecting icons to fall inside of Tab Bar cells or Navigation buttons, it's important to ensure that our icon use falls in line with expectations found in other applications. The magnifying glass represents search, a star presumes favorites or top performers, three dots represent that the tab contains multiple options, and a square with a pencil infers that the button composes a new email. Start by giving users a push in the right direction: Feel free to offer up a friendly push to the user from the get go. If we make the first step clear, the subsequent steps may become a bit more obvious, as shown in the following screenshot from Grades by Tapity: Grades - © Tapity Hold back sound, flashy animation, or bright colors until the user has had the chance to settle in. Offer content early, if only a little taste of what is to come. How it works... Creating an intuitive application interface from the first second a user opens our app is an art, which requires that we shape our app carefully overtime. As we add new features, create new art, or conceive new ways to present data on screen, we should always be thinking about what a new user will think upon first presentation of our app. For Step 1, Apple routinely updates the Mobile Human Interface Guidelines , https://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/MobileHIG/Introduction/Introduction.html, with suggestions on how to use icons that come built into the iOS SDK . These guidelines account for a limited quantity of icons and uses, which makes it a bit difficult to gain a good grasp of how we should truly utilize such pieces in our app. While it would be impossible to create an exhaustive list of general shapes and their associated meaning on iOS, the best we can do is make ourselves familiar with as many apps as we possibly can in order to best understand how others have paved the road of user expectations. In Step 2, we took a look at Grades by Jeremy Olsen. The application allows users to manage test scores and class grades, with an exceptional level of open-ended opportunity. No matter how complex or simple a class's grade scale may be, the application handles the data with ease. The application makes such scalability easy for the user by using a simple contextual clue on initial launch. By offering direction on how to start tracking information for a class, the user is essentially given a tutorial without even realizing that they're being taught. There is no confusion as to what the first step is, and the user can jump right in and start keeping track of their grades. For Step three, if we are in the mood, or feel as if it's necessary to make our application stand out through a good deal of noise, eccentric color, or excessive animation, that's perfectly fine. Each application has a different art strategy and depending on our target audience, these elements may very much make sense in our work. However, we should be hesitant to use such vivid visuals or loud sounds during the user's introduction to our app. While the user may be in our target audience and enjoy our app otherwise, such sudden extreme sense stimulation may be off-putting. Instead, we should slowly walk our users into the application and give them a chance to prepare for any noise or bright lights that we may throw their way. This way, the user is expecting whatever we decide to present. For example, if we offer loud noises right after the initial launch and our user is sitting in a quiet auditorium, the successive embarrassing situation may turn the user away from our application, just because we presented them with an unexpected bout of displeasure. By working the user into our loud, colorful, flashy application, we'll be less likely to scare away potential long-term users in the first five minute of using our app. With regards to Step 3, if our application is a content heavy application, such as a social network or application that features extensive listings of local sport scores, we may be inclined to encourage users to sign up for our service before we offer the meat and potatoes of our app. Most designers are confident that their content is so valuable, users will jump through whatever hoops necessary in order to gain access. However, the typical user is an impatient soul, unlikely to fill out forms in order to gain access to an app's walled garden. Instead they'll download our app, see the frictional barrier in front of the content, and decide that they're not that interested. By offering a quick glimpse, we hold some hope in convincing the user that our content is worth going through the sign up process. Service applications such as Instagram and Twitter do a great job at this, offering a handful of images or text entries before asking the user to sign up. These quick entries give an example of the wealth of content laying behind the apparent barrier of a sign up form. Through these quick previews, the user can gain an idea as to whether they'll enjoy the service or not. By using a preview method such as this, users are able to gauge interest before the sign up, saving everyone's valuable time. Finally, we know that every iOS device user is familiar with Apple's bundled applications, as they are the only applications that come pre-installed and as such, are the only applications that every user is likely to have used. We should look here for inspiration, as Apple offers a good deal of guidance with their work. When placing an icon on our Tab Bar, ask yourself if every user will instantly know the tabs function based on the imagery. If we have doubts, there is probably a better alternative icon. In many respects, this recipe isn't so much a one-time action like many others found throughout this book. Instead, it's a design philosophy which we will fine tune as we create more applications for the iPhone or iPad. There's more... Tutorials and help menus were a somewhat taboo topic during the early days of the App Store, with Apple holding a hard stance that apps requiring such a menu were too complex for the mobile platform. Times are changing a bit, with Apple themselves offering help menus in complex apps like Garageband or iMovie. Here's a tip on how to best offer support inside of our app. Lend a helping hand While most early apps were capable of success without a help menu, many new apps have become much more complex and require such a way to teach the user about app features. If we want to provide help for our users, we have two choices. One thing we could do is create a specific help view; we could do something like provide a table of topics that the user can tap upon in order to learn more about. This allows us to dive in-depth into a variety of topics, with as much detail as we feel is required. We could also provide a tutorial through on screen overlays, where tapping a help button presents short tips on screen with insight into different app features. This method works well because we can directly point at an interface element and tell the user what its purpose is. However, because we're overlaying such information on top of the interface, we must be brief when using this choice. Our app may be simple and self-explanatory enough, that we won't need one of these two methods in order to provide a help menu. However, if we think that we need to lend a hand, either of these two routes would work well.  
Read more
  • 0
  • 0
  • 903
article-image-article-html5-working-with-images-and-videos
Packt
02 Dec 2011
19 min read
Save for later

HTML5: Working with Images and Videos

Packt
02 Dec 2011
19 min read
(For more resources on this topic, see here.) Introduction This article focuses on yet another very exciting topic of the HTML5 canvas, images and videos. Along with providing basic functionality for positioning, sizing, and cropping images and videos, the HTML5 canvas API also allows us to access and modify the color and transparency of each pixel for both mediums. Let's get started! Drawing an image Let's jump right in by drawing a simple image. In this recipe, we'll learn how to load an image and draw it somewhere on the canvas. How to do it... Follow these steps to draw an image in the center of the canvas: Define the canvas context: window.onload = function(){    var canvas = document.getElementById("myCanvas");    var context = canvas.getContext("2d"); Create an image object, set the onload property to a function that draws the image, and then set the source of the image:     var imageObj = new Image();    imageObj.onload = function(){        var destX = canvas.width / 2 - this.width / 2;        var destY = canvas.height / 2 - this.height / 2;                context.drawImage(this, destX, destY);    };    imageObj.src = "jet_300x214.jpg";}; Embed the canvas tag inside the body of the HTML document: <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;"></canvas> How it works... To draw an image, we first need to create an image object using new Image(). Notice that we've set the onload property of the image object before defining the source of the image. It's good practice to define what we want to do with the image when it loads before setting its source. Theoretically, if we were to define the source of the image before we define the onload property; the image could possibly load before the definition is complete (although, it's very unlikely). The key method in this recipe is the drawImage() method: context.drawImage(imageObj,destX,destY); Where imageObj is the image object, and destX and destY is where we want to position the image. There's more... In addition to defining an image position with destX and destY, we can also add two additional parameters, destWidth and destHeight to define the size of our image: context.drawImage(imageObj,destX,destY,destWidth,destHeight); For the most part, it's a good idea to stay away from resizing an image with the drawImage() method, simply because the quality of the scaled image will be noticeably reduced, similar to the result when we resize an image with the width and height properties of an HTML image element. If image quality is something you're concerned about (why on earth wouldn't you be?), it's usually best to work with thumbnail images alongside bigger images if you're creating an application that needs scaled images. If, on the other hand, your application dynamically shrinks and expands images, using the drawImage() method with destWidth and destHeight to scale images is a perfectly acceptable approach. Cropping an image In this recipe, we'll crop out a section of an image and then draw the result onto the canvas. How to do it... Follow these steps to crop out a section of an image and draw the result onto the canvas. Define the canvas context: window.onload = function(){    var canvas = document.getElementById("myCanvas");    var context = canvas.getContext("2d"); Create an image object, set the onload property to a function that crops the image, and then set the source of the image:     var imageObj = new Image();    imageObj.onload = function(){    // source rectangular area        var sourceX = 550;        var sourceY = 300;        var sourceWidth = 300;        var sourceHeight = 214;            // destination image size and position        var destWidth = sourceWidth;        var destHeight = sourceHeight;        var destX = canvas.width / 2 - destWidth / 2;        var destY = canvas.height / 2 - destHeight / 2;                context.drawImage(this, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);    };    imageObj.src = "jet_1000x714.jpg";}; Embed the canvas tag inside the body of the HTML document: <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;"></canvas> How it works... In the last recipe, we discussed two different ways that we can use the drawImage() method to draw images on the canvas. In the first case, we can pass an image object and a position to simply draw an image at the given position. In the second case, we can pass an image object, a position, and a size to draw an image at the given position with the given size. Additionally, we can also add six more parameters to the drawImage() method if we wanted to crop an image: Context.drawImage(imageObj,sourceX,sourceY,sourceWidth, sourceHight, sourceHeight,sourceHeight, destX, destY, destWidth, destHeight); Take a look at the following diagram: As you can see, sourceX and sourceY refer to the top-left corner of the cropped region in the source image. sourceWidth and sourceHeight refer to the width and height of the cropped image from the source. destX and destY refer to the position of the cropped image on the canvas, and destWidth and destHeight refer to the width and height of the resulting cropped image. If you don't intend to scale a cropped image, then destWidth equals sourceWidth and destHeight equals sourceHeight. Copying and pasting sections of the canvas In this recipe, we'll cover yet another interesting usage of the drawImage() method—copying sections of the canvas. First, we'll draw a spade in the center of the canvas, then we'll copy the right side of the spade and then paste it to the left, and then we'll copy the left side of the spade and then paste it to the right. How to do it... Follow these steps to draw a spade in the center of the canvas and then copy-and-paste sections of the shape back onto the canvas: Define the canvas context: window.onload = function(){    // drawing canvas and context    var canvas = document.getElementById("myCanvas");    var context = canvas.getContext("2d"); Draw a spade in the center of the canvas using the drawSpade() function:     // draw spade    var spadeX = canvas.width / 2;    var spadeY = 20;    var spadeWidth = 140;    var spadeHeight = 200;        // draw spade in center of canvas    drawSpade(context, spadeX, spadeY, spadeWidth, spadeHeight); Copy the right half of the spade and then paste it on the canvas to the left of the spade using the drawImage() method:     context.drawImage(    canvas,             spadeX,         // source x    spadeY,         // source y    spadeWidth / 2,     // source width    spadeHeight,       // source height    spadeX - spadeWidth,  // dest x    spadeY,         // dest y    spadeWidth / 2,     // dest width    spadeHeight        // dest height  ); Copy the left half of the spade and then paste it on the canvas to the right of the spade using the drawImage() method:     context.drawImage(    canvas,     spadeX - spadeWidth / 2,  // source x       spadeY,           // source y    spadeWidth / 2,       // source width    spadeHeight,         // source height    spadeX + spadeWidth / 2,   // dest x    spadeY,           // dest y    spadeWidth / 2,       // dest width    spadeHeight          // dest height  );}; Embed the canvas inside the body of the HTML document: <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;"></canvas> How it works... To copy a section of the canvas, we can pass the canvas object to the drawImage() method instead of an image object: Context.drawImage(canvas,sourceX,sourceY,sourceWidth, sourceHight, sourceHeight,sourceHeight, destX, destY, destWidth, destHeight); As we'll see in the next recipe, not only can we copy sections of an image or a canvas with drawImage(), we can also copy sections of HTML5 video. Working with video Although the HTML5 canvas API doesn't provide a direct method for drawing videos on the canvas like it does for images, we can certainly work with videos by capturing frames from a hidden video tag and then copying them onto the canvas with a loop. Getting ready... Before we get started, let's talk about the supported HTML5 video formats for each browser. At the time of writing, the video format war continues to rage on, in which all of the major browsers—Chrome, Firefox, Opera, Safari, and IE—continue to drop and add support for different video formats. To make things worse, each time a major browser adds or drops support for a particular video format, developers have to once again re-formulate the minimal set of video formats that's required for their applications to work across all browsers. At the time of writing, the three major video formats are Ogg Theora, H.264, and WebM. For the video recipes in this article, we'll be using a combination of Ogg Theora and H.264. When working with video, it's strongly advised that you do a search online to see what the current status is for video support as it is a subject to change at any moment. There's more! Once you've decided which video formats to support, you'll probably need a video format converter to convert the video file that you have on hand to other video formats. One great option for converting video formats is the Miro Video Converter, which supports video format conversions for just about any video format including Ogg Theora, H.264, or WebM formats. Miro Video Converter is probably the most common video converter available at the time of writing, although you can certainly use any other video format converter of your liking. You can download Miro Video Converter from: http://www.mirovideoconverter.com/. How to do it... Follow these steps to draw a video onto the canvas: Create a cross-browser method that requests an animation frame: window.requestAnimFrame = (function(callback){    return window.requestAnimationFrame ||    window.webkitRequestAnimationFrame ||    window.mozRequestAnimationFrame ||    window.oRequestAnimationFrame ||    window.msRequestAnimationFrame ||    function(callback){        window.setTimeout(callback, 1000 / 60);    };})(); Define the drawFrame() function which copies the current video frame, pastes it onto the canvas using the drawImage() method, and then requests a new animation frame to draw the next frame: function drawFrame(context, video){    context.drawImage(video, 0, 0);    requestAnimFrame(function(){        drawFrame(context, video);    });} Define the canvas context, get the video tag, and draw the first video frame: window.onload = function(){    var canvas = document.getElementById("myCanvas");    var context = canvas.getContext("2d");    var video = document.getElementById("myVideo");    drawFrame(context, video);}; Embed the canvas and the video tag inside the body of the HTML document: <video id="myVideo" autoplay="true" loop="true" style="display:none;">    <source src="BigBuckBunny_640x360.ogv" type="video/ogg"/><source src="BigBuckBunny_640x360.mp4" type="video/mp4"/></video><canvas id="myCanvas" width="600" height="360" style="border:1px solid black;"></canvas> How it works... To draw a video on an HTML5 canvas, we first need to embed a hidden video tag in the HTML document. In this recipe, and in future video recipes, I've used the Ogg Theora and H.264 (mp4) video formats. Next, when the page loads, we can use our cross-browser requestAnimFrame() method to capture the video frames as fast as the browser will allow and then draw them onto the canvas. Getting image data Now that we know how to draw images and videos, let's try accessing the image data to see what kind of properties we can play with. WARNING: This recipe must run on a web server due to security constraints with the getImageData() method. Getting ready... Before we get started working with image data, it's important that we cover canvas security and the RGBA color space. So why is canvas security important with respect to accessing image data? Simply put, in order to access image data, we need to use the getImateData() method of the canvas context which will throw a SECURITY_ERR exception if we try accessing image data from an image residing on a non-web server file system, or if we try accessing image data from an image on a different domain. In other words, if you're going to try out these demos for yourself, they won't work if your files reside on your local file system. You'll need to run the rest of the recipes in this article on a web server.Next, since pixel manipulation is all about altering the RGB values of pixels, we should probably cover the RGB color model and the RGBA color space while we're at it. RGB represents the red, green, and blue components of a pixel's color. Each component is an integer between 0 and 255, where 0 represents no color and 255 represents full color. RGB values are often times represented as follows: rgb(red,green,blue) Here are some common color values represented with the RGB color model: rgb(0,0,0) = blackrgb(255,255,255) = whitergb(255,0,0) = redrgb(0,255,0) = greenrgb(0,0,255) = bluergb(255,255,0) = yellowrgb(255,0,255) = magentargb(0,255,255) = cyan In addition to RGB, pixels can also have an alpha channel which refers to its opacity. An alpha channel of 0 is a fully transparent pixel, and an alpha channel of 255 is a fully opaque pixel. RGBA color space simply refers to the RGB color model (RGB) plus the alpha channel (A). Be careful not to confuse the alpha channel range of HTML5 canvas pixels, which are integers 0 to 255, and the alpha channel range of CSS colors, which are decimals 0.0 to 1.0. How to do it... Follow these steps to write out the image data properties of an image: Define a canvas context: window.onload = function(){    var canvas = document.getElementById("myCanvas");    var context = canvas.getContext("2d"); Create an image object, set the onload property to a function which draws the image:     var imageObj = new Image();    imageObj.onload = function(){        var sourceWidth = this.width;        var sourceHeight = this.height;        var destX = canvas.width / 2 - sourceWidth / 2;        var destY = canvas.height / 2 - sourceHeight / 2;        var sourceX = destX;        var sourceY = destY;            // draw image on canvas        context.drawImage(this, destX, destY); Get the image data, write out its properties, and then set the source of the image object outside of the onload definition:     // get image data from the rectangular area     // iof the canvas containing the image        var imageData = context.getImageData(sourceX, sourceY, sourceWidth, sourceHeight);        var data = imageData.data;        // write out the image data properties        var str = "width=" + imageData.width + ", height=" + imageData.height + ", data length=" + data.length;        context.font = "12pt Calibri";        context.fillText(str, 4, 14);    };    imageObj.src = "jet_300x214.jpg";}; Embed the canvas tag into the body of the HTML document: <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;"></canvas> How it works... The idea behind this recipe is to draw an image, get its image data, and then write out the image data properties to the screen. As you can see from the preceding code, we can get the image data using the getImageData() method of the canvas context: context.getImageData(sourceX,sourceY,sourceWidth,sourceHeight); Notice that the getImageData() method only works with the canvas context and not the image object itself. As a result, in order to get image data, we must first draw an image onto the canvas and then use getImageData() method of the canvas context. The ImageData object contains three properties: width, height, and data. As you can see from the screenshot in the beginning of this recipe, our ImageData object contains a width property of 300, a height property of 214, and a data property which is an array of pixel information, which in this case has a length of 256,800 elements. The key to the ImageData object, in all honesty, is the data property. The data property contains the RGBA information for each pixel in our image. Since our image is made up of 300 * 214 = 64,200 pixels, the length of this array is 4 * 64,200 = 256,800 elements. Introduction to pixel manipulation: inverting image colors Now that we know how to access image data, including the RGBA for every pixel in an image or video, our next step is to explore the possibilities of pixel manipulation. In this recipe, we'll invert the colors of an image by inverting the color of each pixel. WARNING: This recipe must be run on a web server due to security constraints with the getImageData() method. How to do it... Follow these steps to invert the colors of an image: Define the canvas context: window.onload = function(){    var canvas = document.getElementById("myCanvas");    var context = canvas.getContext("2d"); Create an image object and set the onload property to a function that draws the image and gets the image data:     var imageObj = new Image();    imageObj.onload = function(){        var sourceWidth = this.width;        var sourceHeight = this.height;        var sourceX = canvas.width / 2 - sourceWidth / 2;        var sourceY = canvas.height / 2 - sourceHeight / 2;        var destX = sourceX;        var destY = sourceY;                context.drawImage(this, destX, destY);                var imageData = context.getImageData(sourceX, sourceY, sourceWidth, sourceHeight);        var data = imageData.data; Loop through all of the pixels in the image and invert the colors:         for (var i = 0; i < data.length; i += 4) {            data[i] = 255 - data[i]; // red            data[i + 1] = 255 - data[i + 1]; // green            data[i + 2] = 255 - data[i + 2]; // blue            // i+3 is alpha (the fourth element)        } Overwrite the original image with the manipulated image, and then set the source of the image outside of the onload definition:         // overwrite original image with        // new image data        context.putImageData(imageData, destX, destY);    };    imageObj.src = "jet_300x214.jpg";}; Embed the canvas tag into the body of the HTML document: <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;"></canvas> How it works... To invert the color of an image using HTML5 canvas, we can simply loop through all of the pixels in an image and then invert each pixel using a color inverting algorithm. Don't worry it's easier than it sounds. To invert a pixel's color, we can invert each of its RGB components by subtracting each value from 255 as follows: data[i  ] = 255 - data[i  ]; // reddata[i+1] = 255 - data[i+1]; // greendata[i+2] = 255 - data[i+2]; // blue Once the pixels have been updated, we can redraw the image using the putImageData() method of the canvas context: context.putImageData(imageData, destX, destY);  This method basically allows us to draw an image using image data instead of a source image with the drawImage() method.
Read more
  • 0
  • 0
  • 990

article-image-html5-getting-started-paths-and-text
Packt
30 Nov 2011
10 min read
Save for later

HTML5: Getting Started with Paths and Text

Packt
30 Nov 2011
10 min read
(For more resources on this topic, see here.) Introduction This article is designed to demonstrate the fundamental capabilities of the HTML5 canvas by providing a series of progressively complex tasks. The HTML5 canvas API provides the basic tools necessary to draw and style different types of sub paths including lines, arcs, Quadratic curves, and Bezier curves, as well as a means for creating paths by connecting sub paths. The API also provides great support for text drawing with several styling properties. Let's get started! Drawing a line When learning how to draw with the HTML5 canvas for the fi rst time, most people are interested in drawing the most basic and rudimentary element of the canvas. This recipe will show you how to do just that by drawing a simple straight line. How to do it... Follow these steps to draw a diagonal line: Define a 2D canvas context and set the line style: window.onload = function(){  // get the canvas DOM element by its ID     var canvas = document.getElementById("myCanvas");  // declare a 2-d context using the getContext() method of the     // canvas object     var context = canvas.getContext("2d");  // set the line width to 10 pixels     context.lineWidth = 10;  // set the line color to blue     context.strokeStyle = "blue"; Position the canvas context and draw the line:  // position the drawing cursor    context.moveTo(50, canvas.height - 50); // draw the line    context.lineTo(canvas.width - 50, 50); // make the line visible with the stroke color    context.stroke(); }; Embed the canvas tag inside the body of the HTML document: <canvas id="myCanvas" width="600" height="250" style="border:1pxsolid black;"></canvas> How it works... As you can see from the preceding code, we need to wait for the page to load before trying to access the canvas tag by its ID. We can accomplish this with the window.onload initializer. Once the page loads, we can access the canvas DOM element with document. getElementById() and we can define a 2D canvas context by passing 2d into the getContext() method of the canvas object. We can also define 3D contexts by passing in other contexts such as webgl, experimental-webgl, and others. When drawing a particular element, such as a path, sub path, or shape, it's important to understand that styles can be set at any time, either before or after the element is drawn, but that the style must be applied immediately after the element is drawn for it to take effect, We can set the width of our line with the lineWidth property, and we can set the line color with the strokeStyle property. Think of this behavior like the steps that we would take if we were to draw something onto a piece of paper. Before we started to draw, we would choose a colored marker (strokeStyle) with a certain tip thickness (lineWidth). Now that we have our marker in hand, so to speak, we can position it onto the canvas using the moveTo() method: context.moveTo(x,y); Think of the canvas context as a drawing cursor. The moveTo() method creates a new sub path for the given point. The coordinates in the top-left corner of the canvas are (0,0), and the coordinates in the bottom-right corner are (canvas width, canvas height). Once we have positioned our drawing cursor, we can draw the line using the lineTo() method by defi ning the coordinates of the line's end point: context.lineTo(x,y); Finally, to make the line visible, we can use the stroke() method. Unless, otherwise specified, the default stroke color is black.To summarize, here's the typical drawing procedure we should follow when drawing lines with the HTML5 canvas API: Style your line (like choosing a colored marker with a specific tip thickness). Position the canvas context using moveTo() (like placing the marker onto a piece of paper). Draw the line with lineTo(). Make the line visible using stroke(). There's more... HTML5 canvas lines can also have one of three varying line caps, including butt, round, and square. The line cap style can be set using the lineCap property of the canvas context. Unless otherwise specified, the line cap style is defaulted to butt. The following diagram shows three lines, each with varying line cap styles. The top line is using the default butt line cap, the middle line is using the round line cap, and the bottom line is using a square line cap: Notice that the middle and bottom lines are slightly longer than the top line, even though all of the line widths are equal. This is because the round line cap and the square line cap increase the length of a line by an amount equal to the width of the line. For example, if our line is 200 px long and 10 px wide, and we use a round or square line cap style, the resulting line will be 210 px long because each cap adds 5 px to the line length. Drawing an arc When drawing with the HTML5 canvas, it's sometimes necessary to draw perfect arcs. If you're interested in drawing happy rainbows, smiley faces, or diagrams, this recipe would be a good start for your endeavor. How to do it... Follow these steps to draw a simple arc: Define a 2D canvas context and set the arc style: window.onload = function(){    var canvas = document.getElementById("myCanvas");    var context = canvas.getContext("2d");    context.lineWidth = 15;    context.strokeStyle = "black"; // line color Draw the arc: context.arc(canvas.width / 2, canvas.height / 2 + 40, 80, 1.1 *Math.PI, 1.9 * Math.PI, false);context.stroke();}; Embed the canvas tag inside the body of the HTML document: <canvas id="myCanvas" width="600" height="250" style="border:1pxsolid black;"></canvas> How it works... We can create an HTML5 arc with the arc() method which is defined by a section of the circumference of an imaginary circle. Take a look at the following diagram: The imaginary circle is defi ned by a center point and a radius. The circumference section is defi ned by a starting angle, an ending angle, and whether or not the arc is drawn counter-clockwise: context.arc(centerX,centerY, radius, startingAngle,            endingAngle,counterclockwise); Notice that the angles start with 0p at the right of the circle and move clockwise to 3p/2, p, p/2, and then back to 0. For this recipe, we've used 1.1p as the starting angle and 1.9p as the ending angle. This means that the starting angle is just slightly above center on the left side of the imaginary circle, and the ending angle is just slightly above center on the right side of the imaginary circle. There's more... The values for the starting angle and the ending angle do not necessarily have to lie within 0p and 2p. In fact, the starting angle and ending angle can be any real number because the angles can overlap themselves as they travel around the circle. For example, let's say that we defi ne our starting angle as 3p. This is equivalent to one full revolution around the circle (2p) and another half revolution around the circle (1p). In other words, 3p is equivalent to 1p. As another example, - 3p is also equivalent to 1p because the angle travels one and a half revolutions counter-clockwise around the circle, ending up at 1p.Another method for creating arcs with the HTML5 canvas is to make use of the arcTo() method. The resulting arc from the arcTo() method is defi ned by the context point, a control point, an ending point, and a radius: context.arcTo(controlPointX1, controlPointY1, endingPointX,              endingPointY, radius); Unlike the arc() method, which positions an arc by its center point, the arcTo() method is dependent on the context point, similar to the lineTo() method. The arcTo() method is most commonly used when creating rounded corners for paths or shapes. Drawing a Quadratic curve In this recipe, we'll learn how to draw a Quadratic curve. Quadratic curves provide much more flexibility and natural curvatures compared to its cousin, the arc, and are an excellent tool for creating custom shapes. How to do it... Follow these steps to draw a Quadratic curve: Define a 2D canvas context and set the curve style: window.onload = function(){    var canvas = document.getElementById("myCanvas");    var context = canvas.getContext("2d");    context.lineWidth = 10;    context.strokeStyle = "black"; // line color Position the canvas context and draw the Quadratic curve: context.moveTo(100, canvas.height - 50);    context.quadraticCurveTo(canvas.width / 2, -50, canvas.width- 100, canvas.height - 50);    context.stroke();}; Embed the canvas tag inside the body of the HTML document: <canvas id="myCanvas" width="600" height="250" style="border:1pxsolid black;"></canvas> How it works... HTML5 Quadratic curves are defined by the context point, a control point, and an ending point: context.quadraticCurveTo(controlX, controlY, endingPointX,      endingPointY); Take a look at the following diagram: The curvature of a Quadratic curve is defined by three characteristic tangents. The first part of the curve is tangential to an imaginary line that starts with the context point and ends with the control point. The peak of the curve is tangential to an imaginary line that starts with midpoint 1 and ends with midpoint 2. Finally, the last part of the curve is tangential to an imaginary line that starts with the control point and ends with the ending point. Drawing a Bezier curve If Quadratic curves don't meet your needs, the Bezier curve might do the trick. Also known as cubic curves, the Bezier curve is the most advanced curvature available with the HTML5 canvas API. How to do it... Follow these steps to draw an arbitrary Bezier curve: Define a 2D canvas context and set the curve style: window.onload = function(){    var canvas = document.getElementById("myCanvas");    var context = canvas.getContext("2d");    context.lineWidth = 10;    context.strokeStyle = "black"; // line color    context.moveTo(180, 130); Position the canvas context and draw the Bezier curve: context.bezierCurveTo(150, 10, 420, 10, 420, 180);   context.stroke();}; Embed the canvas tag inside the body of the HTML document: <canvas id="myCanvas" width="600" height="250" style="border:1pxsolid black;"></canvas> How it works... HTML5 canvas Bezier curves are defined by the context point, two control points, and an ending point. The additional control point gives us much more control over its curvature compared to Quadratic curves: context.bezierCurveTo(controlPointX1, controlPointY1,    controlPointX2, controlPointY2,    endingPointX, endingPointY); Take a look at the following diagram: Unlike Quadratic curves, which are defined by three characteristic tangents, the Bezier curve is defined by five characteristic tangents. The first part of the curve is tangential to an imaginary line that starts with the context point and ends with the fi rst control point. The next part of the curve is tangential to the imaginary line that starts with midpoint 1 and ends with midpoint 3. The peak of the curve is tangential to the imaginary line that starts with midpoint 2 and ends with midpoint 4. The fourth part of the curve is tangential to the imaginary line that starts with midpoint 3 and ends with midpoint 5. Finally, the last part of the curve is tangential to the imaginary line that starts with the second control point and ends with the ending point.
Read more
  • 0
  • 0
  • 2558

article-image-attracting-traffic
Packt
23 Nov 2011
5 min read
Save for later

Attracting Traffic

Packt
23 Nov 2011
5 min read
(For more resources on WordPress, see here.) Making it easy for people to follow you Take a look at some of the most popular bloggers in the world, and compare their sites. You will notice that, without fail, they all make it really easy to follow them by RSS and Twitter and more often than not Facebook or LinkedIn. Look at the copyblogger home page in the following screenshot: (Move the mouse over the image to enlarge.) Notice how prominently displayed at the top right of the page is a list of large visually recognizable buttons that allow visitors to subscribe to their newsletter, RSS feed, follow them on Twitter, or like them on Facebook. Anyone who is interested in learning about online marketing can, at the click of a button, access all the latest content provided by copyblogger. While gaining a follower on Twitter doesn't necessarily bring revenue directly, each and every follower is a potential customer, or someone who will potentially recommend your blog to a potential customer. This meets the hugely important business objective of increasing reach for the site and its content—something you must also do if you are to have any hope of penetrating the market. WordPress.com has an RSS link widget that can add a nice orange RSS icon to any one of the widget areas in your theme. This is unfortunately not really suitable for our needs as we need a row of icons and links to a number of different things. In order to get a nice row of icons, we will need to write a bit of HTML code and add it to a custom Text widget. WordPress.org users can simply install something like the Subscribe/ Connect/Follow widget, available at http://wordpress.org/ extend/plugins/subscribe-connect-follow-widget. Creating a custom "Follow me" widget Before you begin adding the links, you will need to find and download a set of icons. A search on Google for "social network icons" should bring up some useable results. Remember to make sure that you do not infringe on any copyright conditions. Only use icons that are freely available. Once you have the icons you want (preferably large, instantly recognizable ones), upload them to your media folder on your site so that they can be referenced in the links. For example, the following screenshot shows the Upload New Media page being used to upload an RSS icon: Note in particular that the icon has been given a File URL. It is this URL you will use to reference this icon in the HTML that follows. Once all the requisite icon files are uploaded to your media library, you are ready to drag a new Text widget to the top right of your page and copy and paste the following HTML into it: <ul><li style="display:inline;"><a href="path_to_email"><img src="email_icon_file_url" alt="contact me via email"  /></a></li><li style="display:inline;"><a href="path_to_rss"><img src="rss_icon_file_url " alt="subscribe to my RSS feed"  /></a></li><li style="display:inline;"><a href="path_to_twitter "><img src="twitter_icon_file_url " alt="follow me on twitter"  /></a></li><li style="display:inline;"><a href="path_to_linkedin"><img src="linkedin_icon_file_url" alt="connect with me on  linked in" /></a></li></ul> Make sure that you change the paths in the code to suit your own setup. For example, this code used in my social marketing crash course home page on WordPress looks as shown in the following screenshot: With the icon files correctly referenced, the individual e-mail (you can add your own contact form using the Add New Post page and clicking on the Add a custom form icon), Twitter, RSS, and linked pages also correctly linked to, you can save the Text widget. You might decide to add Facebook or other icons, or you might not want to use LinkedIn. It is easy to add and remove new icons by copying and pasting additional link (<li></li>) elements into the unordered list parent tags (<ul></ul>). In this case, the resulting links are displayed on the live site as shown in the following screenshot: OK, so the icons here are possibly a bit too small. I could hunt around for bigger ones, but it is also easy to add a bit of text to the links (after the img tag), or use some HTML to modify the layout to suit. The goal is to make it very easy and clear for any visitor to convert into a follower. By prominently displaying the various ways in which visitors can convert to followers, you upgrade your blog from the old baseball paradigm to the new black hole paradigm. As time goes by, you will benefit by building up a large network of followers who double as potential customers, and an army of marketers who can spread the word about your content, products, and services. Summary By utilizing your quality content and making it very easy for people so stay within reach of it through RSS, Twitter, Facebook, LinkedIn, and any other appropriate services, you drastically improve your chances of converting visitors into followers. Further resources on this subject: Dynamic Menus in WordPress [Article] Getting Started with WordPress 3 [Article] Social Bookmarking with WordPress Plugin [Article] Tips and Tricks for Working with jQuery and WordPress [Article]
Read more
  • 0
  • 0
  • 1413
article-image-article-creating-our-first-module-using-drupal6-part1
Packt
12 Oct 2011
8 min read
Save for later

Creating Our First Module using Drupal 6 (Part1)

Packt
12 Oct 2011
8 min read
Starting Out Our first module is going to fetch XML data from Goodreads, a free social networking site for avid readers. There, users track the books they are reading and have read, rate books and write reviews, and share their reading lists with friends. Reading lists at Goodreads are stored in bookshelves. These bookshelves are accessible over a web-based XML/RSS API. We will use that API to display a reading list on the Philosopher Bios website(example website) To integrate the Goodreads information in Drupal, we will create a small module. Since this is our first module, we will get into greater details. A Place for the Module In Drupal, every module is contained in its own directory. This simplifies organization; all of the module's files are located in one place. To keep naming consistent throughout the module (a standard in Drupal), we will name our directory with the module name. Later, we will install this module in Drupal, but for development, the module directory can be wherever it is most convenient. Once we have created a directory named goodreads, we can start creating files for our module. The first file we need to create is the .info (dot-info) file. Creating a .info File Before we start coding our new module, we need to create a simple text file that will hold some basic information about our module. Various Drupal components use the information in this file for module management. The .info file is written as a PHP INI file, which is a simple configuration file format. If you are interested in the details of INI file processing, you can visit http://php.net/manual/en/function.parse-ini-file.php for a description of this format and how it can be parsed in PHP. Our .info file will only be five lines long, which is probably about average. The .info file must follow the standard naming conventions for modules. It must be named <modulename>.info, where <modulename> is the same as the directory name. Our file, then, will be called goodreads.info. Following are the contents of goodreads.info: ;$Id$name = "Goodreads Bookshelf"description = "Displays items from a Goodreads Bookshelf"core = 6.xphp = 5.1 This file isn't particularly daunting. The first line of the file is, at first glance, the most cryptic. However, its function is mundane: it is a placeholder for Drupal's CVS server. Drupal, along with its modules, is maintained on a central CVS (Concurrent Version System) server. CVS is a version control system. It tracks revisions to code over time. One of its features is its ability to dynamically insert version information into a file. However, it needs to know where to insert the information. The placeholder for this is the special string $Id$. But since this string isn't actually a directive in the .info file, it is commented out with the PHP INI comment character, ; (semi-colon). You can insert comments anywhere in your .info file by beginning a line with the ; character. The next four directives each provide module information to Drupal. The name directive provides a human-readable display name for the module. Here's an example: In this above screenshot, the names Aggregator and Blog are taken from the values of the name directives in these modules' .info files. While making the module's proper name short and concise is good (as we did when naming the module directory goodreads above), the display name should be helpful to the user. That usually means that it should be a little longer, and a little more descriptive. However, there is no need to jam all of the module information into the name directive. The description directive is a good place for providing a sentence or two describing the module's function and capabilities. The third directive is the core directive. The core and php directives are new in Drupal 6. This directive specifies what version of Drupal is required for this module to function properly. Our value, 6.x, indicates that this module will run on Drupal 6 (including its minor revisions). In many cases, the Drupal packager will be able to automatically set this (correctly). But Drupal developers are suggesting that this directive be set manually for those who work from CVS. Finally, the php directive makes it possible to specify a minimum version number requirement for PHP. PHP 5, for example, has many features that are missing in PHP 4 (and the modules in this book make use of such features). For that reason, we explicitly note that our modules require at least PHP version 5.1. That's all there is to our first module .info file. What we have here is sufficient for our Goodreads module. Now, we are ready to write some PHP code. A Basic .module File There are two files that every module must have (though many modules have more). The first, the .info file, we examined above. The second file is the .module (dot-module) file, which is a PHP script file. This file typically implements a handful of hook functions that Drupal will call at pre-determined times during a request.     Here, we will create a .module file that will display a small formatted section of information. Later in this article, we will configure Drupal to display this information to site visitors. Our Goal: A Block Hook For our very first module, we will implement the hook_block() function. In Drupal parlance, a block is a chunk of auxiliary information that is displayed on a page alongside the main page content. Sounds confusing? An example might help. Think of your favorite news website. On a typical article page, the text of the article is displayed in the middle of the page. But on the left and right sides of the page and perhaps at the top and bottom as well, there are other bits of information: a site menu, a list of links to related articles, links to comments or forums about this article, etc. In Drupal, these extra pieces are treated as blocks. The hook_block() function isn't just for displaying block contents, though. In fact, this function is responsible for displaying the block and providing all the administration and auxiliary functions related to this block. Don't worry... we'll start out simply and build up from there. Starting the .module Drupal follows rigorous coding and documentation standards (http://drupal.org/coding-standards). In this article, we will do our best to follow these standards. So as we start out our module, the first thing we are going to do is provide some API documentation. Just as with the .info file, the .module file should be named after the module. Following is the beginning of our goodreads.module file: <?php// $Id$/** * @file * Module for fetching data from Goodreads.com. * This module provides block content retrieved from a * Goodreads.com bookshelf. * @see http://www.goodreads.com */ The .module file is just a standard PHP file. So the first line is the opening of the PHP processing instruction: <?php. Throughout this article you may notice something. While all of our PHP libraries begin with the <?php opening, none of them end with the closing ?> characters. This is intentional, in fact, it is not just intentional, but conventional for Drupal. As much as it might offend your well-formed markup language sensibilities, it is good coding practice to omit the closing characters for a library. Why? Because it avoids printing whitespace characters in the script's output, and that can be very important in some cases. For example, if whitespace characters are output before HTTP headers are sent, the client will see ugly error messages at the top of the page. After the PHP tag is the keyword for the version control system: // $Id$ When the module is checked into the Drupal CVS, information about the current revision is placed here. The third part of this example is the API documentation. API documentation is contained in a special comment block, which begins /** and ends with a */. Everything between these is treated as documentation. Special extraction programs like Doxygen can pull out this information and create user-friendly programming information. The Drupal API reference is generated from the API comments located in Drupal's source code. The program, Doxygen, (http://www.stack.nl/~dimitri/doxygen/) is used to generate the API documents from the comments in the code. The majority of the content in these documentation blocks (docblocks, for short) is simply text. But there are a few additions to the text. First, there are special identifiers that provide the documentation generating program with additional information. These are typically prefixed with an @ sign. /** * @file * Module for fetching data from Goodreads.com. * This module provides block content retrieved from a * Goodreads.com bookshelf. * @see http://www.goodreads.com */ In the above example, there are two such identifiers. The @file identifier tells the documentation processor that this comment describes the entire file, not a particular function or variable inside the file. The first comment in every Drupal PHP file should, by convention, be a file-level comment. The other identifier in the above example is the @see keyword. This instructs the documentation processor to attempt to link this file to some other piece of information. In this case, that piece of information is a URL. Functions, constants, and variables can also be referents of a @see identifier. In these cases, the documentation processor will link this docblock to the API information for that function, constant, or variable. With these formalities out of the way, we're ready to start coding our module.
Read more
  • 0
  • 0
  • 760

article-image-customizing-menus-menu-joomla
Packt
12 Oct 2011
8 min read
Save for later

Customizing the Menus Menu in Joomla!

Packt
12 Oct 2011
8 min read
The Top Menu is a horizontal menu; the other menus are vertical. Each menu is coupled with a so-called module, which is administered in the module manager. Menus By clicking on this menu item, you get an overview of the available menus. You can also access the content of these menus by means of the menu bar—Menus | Main Menu, Top Menu, or by clicking the respective menu link in the overview. This Menu Manager serves as an overview and shows you the number of Published and Unpublished menu items, the number of menu items that are in the Trash can, and the respective menu ID. In this section you can, for instance, copy a menu or create a new one. Customizing an Existing Menu Experiment a little with the menus to get a feel for things. The following edit steps are same for all the menus. Go to the menu item Menus | Main Menu. You will see a listing of the menu items that turn up in the mainmenu. Several functions can be executed in the table with a simple mouse click. By clicking on the checkmark, you can enable or disable a menu link. You can change the order of the items by clicking on the triangles or by typing numbers into the fields under Order. If you use the numbers method, you have to click on the disk symbol in the header in order to make the change effective. In the Access Level column, via mouse click you can decide whether the menu is available to all users (Public), only to registered users (Registered), or only to a particular circle of users (Special). The menu items are then displayed or hidden, independent of the user's rights. Menus Icon If you click on this icon, you are taken to the menu overview screen. Default Icon The menu item that is marked as default here with a star is displayed as the start page when someone calls up the URL of your website. At the moment this is the menu item Home, but you can designate any element that you want as the start page. Just mark the checkbox and click on the Default icon. Publish/Unpublish Icon The status of a content element can either be published (activated) or unpublished (deactivated). You can toggle this status individually by clicking the green checkmark and/or the red cross, or marking the checkbox and subsequently clicking on the appropriate icon. If you follow the later method, you can toggle several menu items at the same time. Move Icon This entails the moving of menu entries. Let's move the text More about Joomla! into the top menu. Select the respective menu elements or even several menu elements and click the Move icon. This opens a form, listing the available menus. On the right you will see the elements that you want to move: Select the menu into which you would like to move the marked menu items. Here, we have moved More about Joomla! from Main Menu into the Top Menu. You can admire the results in the front end. Copy Icon You can also copy menu items. To do that, select one or more menu items and click on the Copy icon. Just as with moving, a form with the available menus opens. Select the menu into which you want to copy the marked menu entries. Trash Icon In order to protect you from inadvertently deleting items, when editing them you cannot delete them immediately; you can only throw them in the trash. To throw them into trash can, select one or several menu elements and click on the Trash icon. The marked menu items are then dumped into the trash can. You can display the content of the trash can by clicking on Menus | Menu Trash. Edit Icon (Edit Menu Items) Here you can modify an existing menu, for instance the Web Links. After clicking on the name Web Links you will see the edit form for menu elements: The form is divided into three parts.    Menu Item Type    Menu Item Details    Parameters Menu Item Type Every menu item is of a particular type. We will get into greater details when we create new menus. For instance, a menu item can refer to an installed Joomla! component, a content element, a link to an external website, or many other things. You can see what the type of the link is in this section; in our case it is a link to the Joomla! weblinks component, and you can also see a button with the label Change Type. If you click on that button, you get the following screen: This manager is new in Joomla! version 1.5 and really handy. In version 1.0.x there was no option to change the type of a menu item. You had to delete the old menu item and create a new one. Now you can change the display to a single category or to a link-suggestion menu item, with which you invite other users to suggest links. Now close this; we will get back to it when we create a new menu. Menu Item Details It contains the following options: ID: Everything in an administration requires an ID number and so does our menu item. In this case the menu item has the ID number 48. Joomla! assigns this number for internal administration purposes at the time the item is created. This number cannot be changed. Title: This is the name of the menu and it will be displayed that way on your website. Alias: This is the name of the search-engine friendly URL after the domain name. When this is enabled, the URL for this menu will look as follows: http://localhost/joomla150/web-links Link: This is the request for a component, in other words also the part of the URL after the domain name with which you call up your website. In this case it is  index.php?option=com_weblinks&view=categories Display in: With this you can change the place where the item is displayed; in other words you can move it to another menu. The options field presents you with a list of the available menus. Parent Item: Of course menus can also contain nested, tree-like items. Top means that the item is at the uppermost level. The rest of the items represent existing menu items. If, for instance, you classify and save Web Links under The News, the display on the item list and the display on your website are changed. The following figures show the change. The menu item Web Links has now moved into The News on your website. So you have to first click on The News in order to see the Web Links item. Your website can easily and effectively be structured like a database tree in this manner. Published: With this you can publish a menu item. Order: From the options list, you can select after which link you want to position this link. Access Level: You can restrict users that can see this list. On Click, Open in: A very handy option that influences the behavior of the link. The page is either opened in the existing window or in a new browser window after clicking. You can also define whether the new window will be displayed with or without browser navigation. Parameters The possible parameters of a menu item depend on the type of the item. A simple link, of course, has fewer parameters than a configurable list or for example the front page link. In this case we have a link to the categories. The number and type of parameters depend on the type of the menu item. You can open and collapse the parameter fields by clicking on the header. If the parameter fields are open, the arrow next to header points down. Parameters–Basic The basic parameters are the same for all menu links. Image: Here you can specify an image that must be in the root directory of the media manager (/images/stories/). Depending on the template, this picture is displayed on the left, next to the menu item. Image Align: You can decide if the image should be on the left or right. Show a Feed Link: It is possible to create an RSS feed for every list display in Joomla! 1.5. This could be desirable or undesirable depending on the content of the list. In this case, with list displays, RSS feed links that contain the list items are enabled in the browser.
Read more
  • 0
  • 0
  • 3699