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

How-To Tutorials - Web Development

1802 Articles
article-image-joomla-flash-flashy-templates-headers-banners-and-tickers-part-1
Packt
18 Nov 2009
4 min read
Save for later

Joomla! with Flash: Flashy Templates, Headers, Banners, and Tickers: Part 1

Packt
18 Nov 2009
4 min read
In this article, we will mainly focus on the visual design of our site. To acquire the information presented here, it is assumed that you have some basic understanding of Joomla!'s visual design including templates, components, module position, and so on. Adding Flash in templates If you are familiar with Joomla! templates, then you will understand that there are two ways to display Flash in a template: By hardcoded embedding of Flash items By dynamically loading Flash objects at module positions We have seen many modules that can display Flash objects. Therefore, in this section, we will be looking into the embedding of Flash objects within templates. It will also be helpful if we understand the structure of Joomla! templates. Generally templates for Joomla! include headers in Flash. Flash animations are included in the header area of a Joomla! template. Some templates include the mechanism to show images from a specific directory. For example, the template shown in the following screenshot, available for download at http://joomlatp.com/joomla-1.5-templates/Templates-has-flash-header.html, is designed to show a Flash header comprised of the images kept in a directory: The following sections briefly describe the structure of a Joomla! template and the ways to embed a Flash object in this template. Structure of a Joomla! template The look and feel of Joomla! is determined by templates. You can apply a template to the frontend as well as to the backend. Templates for the Joomla! frontend reside in the /templates directory of the Joomla! webroot, while those for the administration panel are found in the /administrator/templates directory. You can install multiple templates and apply one or more templates to the different sections. However, you must designate one default template for the site. To designate a default template, go to Extensions | Template Manager. Select the desired template and click on the Default button on the toolbar. For assigning a template to a specific section of the site, click on a template, except the default template, and then select the section or the menu item for which you want to assign the template from the Menu Assignment section. If you examine the directory structure of a Joomla! template, you will find at least the following subdirectories in the templates directory: Directory Description mx_joofree2 This is the main template directory. It contains some subdirectories and at least the following files under its root: index.php: This is the main file for a template. The basic structure of a Joomla! template is defined in this file. We will examine this file later. templateDetails.xml: This XML file defines the template by mentioning its designer, the different files bundled with it, the positions and parameters available, and so on. params.ini: This file contains the parameters and their default values. For example, a template may use several colors for theming, but users can select a preferred color as a parameter for this template, and that information is stored in this file. mx_joofree2/css This directory contains all the cascading stylesheets to be used for a Joomla! site. This directory will contain at least one stylesheet named template_css.css. It may also contain a stylesheet named template_ie6.css and other stylesheets. mx_joofree2/html This folder may contain some definitions for the custom rendering of certain parts of the site. For example, the mx_joofree2 template contains two files-module.php and pagination.php. These two files define custom module rendering and pagination for Joomla!. For more information on using HTML overrides, refer to http://docs.joomla.org/How_to_override_the_content_from_the_Joomla!_core. mx_joofree2/images This folder contains the images for the template. It may contain a logo image, a background image, and so on. It may also contain some subdirectories, for example, the mx_joofree2 template contains a subdirectory images/headers, where the header images for the template are stored.
Read more
  • 0
  • 0
  • 3098

article-image-building-reusable-components
Packt
26 May 2015
11 min read
Save for later

Building Reusable Components

Packt
26 May 2015
11 min read
In this article by Suchit Puri, author of the book Ember.js Web Development with Ember CLI, we will focus on building reusable view components using Ember.js views and component classes. (For more resources related to this topic, see here.) In this article, we shall cover: Introducing Ember views and components: Custom tags with Ember.Component Defining your own components Passing data to your component Providing custom HTML to your components Extending Ember.Component: Changing your component's tag Adding custom CSS classes to your component Adding custom attributes to your component's DOM element Handling actions for your component Mapping component actions to the rest of your application Extending Ember.Component Till now, we have been using Ember components in their default form. Ember.js lets you programmatically customize the component you are building by backing them with your own component JavaScript class. Changing your component's tag One of the most common use case for backing your component with custom JavaScript code is to wrap your component in a tag, other than the default <div> tag. When you include a component in your template, the component is by default rendered inside a div tag. For instance, we included the copyright footer component in our application template using {{copyright-footer}}. This resulted in the following HTML code: <div id="ember391" class="ember-view"> <footer>    <div>        © 20014-2015 Ember.js Essentials by Packt Publishing    </div>    <div>        Content is available under MIT license    </div> </footer> </div> The copyright footer component HTML enclosed within a <div> tag. You can see that the copyright component's content is enclosed inside a div that has an ID ember391 and class ember-view. This works for most of the cases, but sometimes you may want to change this behavior to enclose the component in the enclosing tag of your choice. To do that, let's back our component with a matching component JavaScript class. Let's take an instance in which we need to wrap the text in a <p> tag, rather than a <div> tag for the about us page of our application. All the components of the JavaScript classes go inside the app/components folder. The file name of the JavaScript component class should be the same as the file name of the component's template that goes inside the app/templates/components/ folder. For the above use case, first let's create a component JavaScript class, whose contents should be wrapped inside a <p> tag. Let us create a new file inside the app/components folder named about-us-intro.js, with the following contents: import Ember from 'ember'; export default Ember.Component.extend({ tagName: "p" }); As you can see, we extended the Ember.Component class and overrode the tagName property to use a p tag instead of the div tag. Now, let us create the template for this component. The Ember.js framework will look for the matching template for the above component at app/templates/components/about-us-intro.hbs. As we are enclosing the contents of the about-us-intro component in the <p> tag, we can simply write the about us introduction in the template as follows: This is the about us introduction.Everything that is present here   will be enclosed within a &lt;p&gt; tag. We can now include the {{about-us-intro}} in our templates, and it will wrap the above text inside the <p> tag. Now, if you visit the http://localhost:4200/about-us page, you should see the preceding text wrapped inside the <p> tag. In the preceding example, we used a fixed tagName property in our component's class. But, in reality, the tagName property of our component could be a computed property in your controller or model class that uses your own custom logic to derive the tagName of the component: import Ember from "ember"; export default Ember.ObjectController.extend({ tagName: function(){    //do some computation logic here    return "p"; }.property() }); Then, you can override the default tagName property, with your own computed tagName from the controller: {{about-us-intro tagName=tagName}} For very simple cases, you don't even need to define your custom component's JavaScript class. You can override the properties such as tagName and others of your component when you use the component tag: {{about-us-intro tagName="p"}} Here, since you did not create a custom component class, the Ember.js framework generates one for you in the background, and then overrides the tagName property to use p, instead of div. Adding custom CSS classes to your component Similar to the tagName property of your component, you can also add additional CSS classes and customize the attributes of your HTML tags by using custom component classes. To provide static class names that should be applied to your components, you can override the classNames property of your component. The classNames property if of type array should be assigned properties accordingly. Let's continue with the above example, and add two additional classes to our component: import Ember from 'ember'; export default Ember.Component.extend({    tagName: "p",    classNames: ["intro","text"] }); This will add two additional classes, intro and text, to the generated <p> tag. If you want to bind your class names to other component properties, you can use the classNameBinding property of the component as follows: export default Ember.Component.extend({ tagName: "p", classNameBindings: ["intro","text"], intro: "intro-css-class", text: "text-css-class" }); This will produce the following HTML for your component: <p id="ember401" class="ember-view intro-css-class   text-css-class">This is the about us introduction.Everything   that is present here will be enclosed within a &lt;p&gt;   tag.</p> As you can see, the <p> tag now has additional intro-css-class and text-css-class classes added. The classNameBindings property of the component tells the framework to bind the class attribute of the HTML tag of the component with the provided properties of the component. In case the property provided inside the classNameBindings returns a boolean value, the class names are computed differently. If the bound property returns a true boolean value, then the name of the property is used as the class name and is applied to the component. On the other hand, if the bound property returns to false, then no class is applied to the component. Let us see this in an example: import Ember from 'ember'; export default Ember.Component.extend({ tagName: "p", classNames: ["static-class","another-static-class"], classNameBindings: ["intro","text","trueClass","falseClass"], intro: "intro-css-class", text: "text-css-class", trueClass: function(){    //Do Some logic    return true; }.property(), falseClass: false }); Continuing with the above about-us-intro component, you can see that we have added two additional strings in the classNameBindings array, namely, trueClass and falseClass. Now, when the framework tries to bind the trueClass to the corresponding component's property, it sees that the property is returning a boolean value and not a string, and then computes the class names accordingly. The above component shall produce the following HTML content: <p id="ember401" class="ember-view static-class   another-static-class intro-css-class text-css-class true-class"> This is the about us introduction.Everything that is present   here will be enclosed within a &lt;p&gt; tag. </p> Notice that in the given example, true-class was added instead of trueClass. The Ember.js framework is intelligent enough to understand the conventions used in CSS class names, and automatically converts our trueClass to a valid true-class. Adding custom attributes to your component's DOM element Till now, we have seen how we can change the default tag and CSS classes for your component. Ember.js frameworks let you specify and customize HTML attributes for your component's DOM (Document Object Model) element. Many JavaScript libraries also use HTML attributes to provide additional details about the DOM element. Ember.js framework provides us with attributeBindings to bind different HTML attributes with component's properties. The attributeBindings which is similar to classNameBindings, is also of array type and works very similarly to it. Let's create a new component, called as {{ember-image}}, by creating a file at app/component/ember-image.js, and use attributes bindings to bind the src, width, and height attributes of the <img> tag. import Ember from 'ember'; export default Ember.Component.extend({ tagName: "img", attributeBindings: ["src","height","width"], src: "http://emberjs.com/images/logos/ember-logo.png", height:"80px", width:"200px" }); This will result in the following HTML: <img id="ember401" class="ember-view" src="http://emberjs.com/images/logos/ember-logo.png" height="80px" width="200px"> There could be cases in which you would want to use a different component's property name and a different HTML attribute name. For those cases, you can use the following notation: attributeBindings: ["componentProperty:HTML-DOM-property] import Ember from 'ember'; export default Ember.Component.extend({ tagName: "img", attributeBindings: ["componentProperty:HTML-DOM-property], componentProperty: "value" }); This will result in the the following HTML code: <img id="ember402" HTML-DOM-property="value"> Handling actions for your component Now that we have learned to create and customize Ember.js components, let's see how we can make our components interactive and handle different user interactions with our component. Components are unique in the way they handle user interactions or the action events that are defined in the templates. The only difference is that the events from a component's template are sent directly to the component, and they don't bubble up to controllers or routes. If the event that is emitted from a component's template is not handled in Ember.Component instance, then that event will be ignored and will do nothing. Let's create a component that has a lot of text inside it, but the full text is only visible if you click on the Show More button: For that, we will have to first create the component's template. So let us create a new file, long-text.hbs, in the app/templates/components/ folder. The contents of the template should have a Show More and Show Less button, which show the full text and hide the additional text, respectively. <p> This is a long text and we intend to show only this much unlessthe user presses the show more button below. </p> {{#if showMoreText}} This is the remaining text that should be visible when we pressthe show more button. Ideally this should contain a lot moretext, but for example's sake this should be enough. <br> <br> <button {{action "toggleMore"}}> Show Less </button> {{else}} <button {{action "toggleMore"}}> Show More </button> {{/if}} As you can see, we use the {{action}} helper method in our component's template to trigger actions on the component. In order for the above template to work properly, we need to handle the toggleMore in our component class. So, let's create long-text.js at app/components/ folder. import Ember from 'ember'; export default Ember.Component.extend({    showMoreText: false,    actions:{    toggleMore: function(){        this.toggleProperty("showMoreText");    }    } }); All action handlers should go inside the actions object, which is present in the component definition. As you can see, we have added a toggleMore action handler inside the actions object in the component's definition. The toggleMore just toggles the boolean property showMoreText that we use in the template to show or hide text. When the above component is included in about-us template, it should present a brief text, followed by the Show More button. When you click the Show More button, the rest of text appears and the Show Less button appears, which, when clicked on, should hide the text. The long-text component being used at the about-us page showing only limited text, followed by the Show More button Clicking Show More shows more text on the screen along with the Show Less button to rollback Summary In this article, we learned how easy it is to define your own components and use them in your templates. We then delved into the detail of ember components, and learned how we can pass in data from our template's context to our component. This was followed by how can we programmatically extend the Ember.Component class, and customize our component's attributes, including the tag type, HTML attributes, and CSS classes. Finally, we learned how we send the component's actions to respective controllers. Resources for Article: Further resources on this subject: Routing [Article] Introducing the Ember.JS framework [Article] Angular Zen [Article]
Read more
  • 0
  • 0
  • 3096

article-image-tips-tricks-ext-js-3x
Packt
30 Nov 2010
3 min read
Save for later

Tips & Tricks for Ext JS 3.x

Packt
30 Nov 2010
3 min read
  Learning Ext JS 3.2 Build dynamic, desktop-style user interfaces for your data-driven web applications using Ext JS Learn to build consistent, attractive web interfaces with the framework components Integrate your existing data and web services with Ext JS data support Enhance your JavaScript skills by using Ext's DOM and AJAX helpers Extend Ext JS through custom components An interactive tutorial packed with loads of example code and illustrative screenshots           Read more about this book       (For more resources on Ext JS, see here.) Objective: Button focus and tab orders are built in. Tip: Button focus and tab orders are built into Ext JS Components. For the MessageBox Component, the OK or Yes button will be the default action, so pressing Enter on our keyboard when a MessageBox appears will trigger that button, and pressing Tab will move us through the buttons and other items in the MessageBox. Windows have the ESC key mapped to the Close tool. When using button bars in other Componenets, tabbing through the buttons is enabled by default and in Toolbars like the PagingToolbar tabbing is also built in. Objective: Duplicate Component ID's must be avoided. Tip: Having duplicate IDs in our document can lead to strange behavior, such as a widgets always showing up in the upper-left corner of the browser, and must therefore be avoided. Objective: Other uses of Button config on a MessageBox. Tip: The buttons config for a MessageBox can also specify the text to display on the button. Instead of passing a Boolean value, just pass it the desired text to display, for example, {yes: 'Maybe'}. Objective: Ext does not require any pre-existing markup. Tip: Ext does not require any pre-existing markup for it to function, this is because it generates everything it needs on its own. This let's us start with a very simple HTML document containing an empty body. Objective: Avoid using the built in JavaScript alert messages. Tip: Standard JavaScript alert messages pause code execution, which can cause unexpected results. You should not be using the built in JavaScript alert messages, and instead use Ext's MessageBox widget or console messages (when available), which does not pause that code execution. Objective: Creating form Field validation types (vType). Tip: A search of the Ext JS forum is likely to come back with a vType that someone else has created with exactly what you need, or close enough to use as a starting point for your own requirements, so search the Ext JS Forums before trying to write your own. Objective: Simple and quick static options for a ComboBox. Tip:; A quick way to specify a few static options for a ComboBox is to pass an array to the store config, which will auto-create the store for you. So if we wanted a ComboBox that had 'Yes' and 'No' as options, we would provide ['Yes','No'] as the store config value.
Read more
  • 0
  • 0
  • 3093

article-image-apache-ofbiz-service-engine-part-2
Packt
20 Oct 2009
16 min read
Save for later

Apache OFBiz Service Engine: Part 2

Packt
20 Oct 2009
16 min read
Calling Services from Java Code So far, we have explored services invoked as events from the controller (example <event type="service" invoke="learningFirstService"/>). We now look at calling services explicitly from code. To invoke services from code, we use the dispatcher object, which is an object of type org.ofbiz.service.ServiceDispatcher. Since this is obtainable from the DispatchContext we can invoke services from other services. To demonstrate this we are going to create one simple service that calls another. In our services.xml file in ${component:learning}servicedef add two new service definitions: <service name="learningCallingServiceOne" engine="java" location="org.ofbiz.learning.learning.LearningServices" invoke="callingServiceOne"> <description>First Service Called From The Controller</description> <attribute name="firstName" type="String" mode="IN" optional="false"/> <attribute name="lastName" type="String" mode="IN" optional="false"/> <attribute name="planetId" type="String" mode="IN" optional="false"/> <attribute name="fullName" type="String" mode="OUT" optional="true"/> </service> <service name="learningCallingServiceTwo" engine="java" location="org.ofbiz.learning.learning.LearningServices" invoke="callingServiceTwo"> <description>Second Service Called From Service One</description> <attribute name="planetId" type="String" mode="IN" optional="false"/> </service> In this simple example it is going to be the job of learningCallingServiceOne to prepare the parameter map and pass in the planetId parameter to learningCallingServiceTwo. The second service will determine if the input is EARTH, and return an error if not. In the class org.ofbiz.learning.learning.LearningEvents, add the static method that is invoked by learningCallingServiceOne: public static Map callingServiceOne(DispatchContext dctx, Map context){ LocalDispatcher dispatcher = dctx.getDispatcher(); Map resultMap = null; String firstName = (String)context.get("firstName"); String lastName = (String)context.get("lastName"); String planetId = (String)context.get("planetId"); GenericValue userLogin = (GenericValue)context.get("userLogin"); Locale locale = (Locale)context.get("locale"); Map serviceTwoCtx = UtilMisc.toMap("planetId", planetId, "userLogin", userLogin, "locale", locale); try{ resultMap = dispatcher.runSync("learningCallingServiceTwo", serviceTwoCtx); }catch(GenericServiceException e){ Debug.logError(e, module); } resultMap.put("fullName", firstName + " " + lastName); return resultMap; } and also the method invoked by learningServiceTwo: public static Map callingServiceTwo(DispatchContext dctx, Map context){ String planetId = (String)context.get("planetId"); Map resultMap = null; if(planetId.equals("EARTH")){ resultMap = ServiceUtil.returnSuccess("This planet is Earth"); }else{ resultMap = ServiceUtil.returnError("This planet is NOT Earth"); } return resultMap; } To LearningScreens.xml add: <screen name="TestCallingServices"> <section> <actions><set field="formTarget" value="TestCallingServices"/></actions> <widgets> <include-screen name="TestFirstService"/> </widgets> </section></screen> Finally add the request-map to the controller.xml file: <request-map uri="TestCallingServices"> <security auth="false" https="false"/> <event type="service" invoke="learningCallingServiceOne"/> <response name="success" type="view" value="TestCallingServices"/> <response name="error" type="view" value="TestCallingServices"/> </request-map> and also the view-map: <view-map name="TestCallingServices" type="screen" page="component://learning/widget/learning/LearningScreens.xml#TestCallingServices"/> Stop, rebuild, and restart, then fire an OFBiz http request TestCallingServices to webapp learning. Do not be alarmed if straight away you see error messages informing us that the required parameters are missing. By sending this request we have effectively called our service with none of our compulsory parameters present. Enter your name and in the Planet Id, enter EARTH. You should see: Try entering MARS as the Planet Id. Notice how in the Java code for the static method callingServiceOne the line resultMap = dispatcher.runSync("learningCallingServiceTwo", serviceTwoCtx); is wrapped in a try/catch block. Similar to how the methods on the GenericDelegator object that accessed the database threw a GenericEntityException, methods on our dispatcher object throw a GenericServiceException which must be handled. There are three main ways of invoking a service: runSync—which runs a service synchronously and returns the result as a map. runSyncIgnore—which runs a service synchronously and ignores the result. Nothing is passed back. runAsync—which runs a service asynchronously. Again, nothing is passed back. The difference between synchronously and asynchronously run services is discussed in more detail in the section called Synchronous and Asynchronous Services. Implementing Interfaces Open up the services.xml file in ${component:learning}servicedef and take a look at the service definitions for both learningFirstService and learningCallingServiceOne. Do you notice that the <attribute> elements (parameters) are the same? To cut down on the duplication of XML code, services with similar parameters can implement an interface. As the first service element in this file enter the following: <service name="learningInterface" engine="interface"> <description>Interface to describe base parameters for Learning Services</description> <attribute name="firstName" type="String" mode="IN" optional="false"/> <attribute name="lastName" type="String" mode="IN" optional="false" /> <attribute name="planetId" type="String" mode="IN" optional="false"/> <attribute name="fullName" type="String" mode="OUT" optional="true"/></service> Notice that the engine attribute is set to interface. Replace all of the <attribute> elements in the learningFirstService and learningCallingServiceOne service definitions with: <implements service="learningInterface"/> So the service definition for learningServiceOne becomes: <service name="learningCallingServiceOne" engine="java" location="org.ofbiz.learning.learning.LearningServices" invoke="callingServiceOne"> <description>First Service Called From The Controller</description> <implements service="learningInterface"/></service> Restart OFBiz and then fire an OFBiz http request TestCallingServices to webapp learning. Nothing should have changed—the services should run exactly as before, however our code is now somewhat tidier. Overriding Implemented Attributes It may be the case that the interface specifies an attribute as optional="false", however, our service does not need this parameter. We can simply override the interface and add the <attribute> element with whatever settings we wish. For example, if we wish to make the planetId optional in the above example, the <implements> element could remain, but a new <attribute> element would be added like this: <service name="learningCallingServiceOne" engine="java" location="org.ofbiz.learning.learning.LearningServices" invoke="callingServiceOne"> <description>First Service Called From The Controller</description> <implements service="learningInterface"/> <attribute name="planetId" type="String" mode="IN" optional="false"/></service> Synchronous and Asynchronous Services The service engine allows us to invoke services synchronously or asynchronously. A synchronous service will be invoked in the same thread, and the thread will "wait" for the invoked service to complete before continuing. The calling service can obtain information from the synchronously run service, meaning its OUT parameters are accessible. Asynchronous services run in a separate thread and the current thread will continue without waiting. The invoked service will effectively start to run in parallel to the service or event from which it was called. The current thread can therefore gain no information from a service that is run asynchronously. An error that occurs in an asynchronous service will not cause a failure or error in the service or event from which it is called. A good example of an asynchronously called service is the sendOrderConfirmation service that creates and sends an order confirmation email. Once a customer has placed an order, there is no need to wait while the mail service is called and the mail sent. The mail server may be down, or busy, which may result in an error that would otherwise stop our customer form placing the order. It is much more preferable to allow the customer to continue to the Order Confirmation page and have our business receive the valuable order. By calling this service asynchronously, there is no delay to the customer in the checkout process, and while we log and fix any errors with the mail server, we still take the order. Behind the scenes, an asynchronous service is actually added to the Job Scheduler. It is the Job Scheduler's task to invoke services that are waiting in the queue. Using the Job Scheduler Asynchronous services are added to the Job Scheduler automatically. However, we can see which services are waiting to run and which have already been invoked through the Webtools console. We can even schedule services to run once only or recur as often as we like. Open up the Webtools console at https://localhost:8443/webtools/control/main and take a look under the Service Engine Tools heading. Select Job List to view a full list of jobs. Jobs without a Start Date/Time have not started yet. Those with an End Date/Time have completed. The Run Time is the time they are scheduled to run. All of the outstanding jobs in this list were added to the JobSandbox Entity when the initial seed data load was performed, along with the RecurrenceRule (also an Entity) information specifying how often they should be run. They are all maintenance jobs that are performed "offline". The Pool these jobs are run from by default is set to pool. In an architecture where there may be multiple OFBiz instances connecting to the same database, this can be important. One OFBiz instance can be dedicated to performing certain jobs, and even though job schedulers may be running on each instance, this setting can be changed so we know only one of our instances will run this job. The Service Engine settings can be configured in frameworkserviceconfigserviceengine.xml. By changing both the send-to-pool attribute and the name attribute on the <run-from-pool element>, we can ensure that only jobs created on an OFBiz instance are run by this OFBiz instance. Click on the Schedule Job button and in the Service field enter learningCallingServiceOne, leave the Pool as pool and enter today's date/time by selecting the calendar icon and clicking on today's date. We will need to add 5 minutes onto this once it appears in the box. In the below example the Date appeared as 2008-06-18 14:11:24.265. This job is only going to be scheduled to run once, although we could specify any recurrence information we wish. Select Submit and notice that scheduler is already aware of the parameters that can (or must, in this case) be entered. This information has been taken from the service definition in our services.xml file. Press Submit to schedule the job and find the entry in the list. This list is ordered by Run Time so it may not be the first. Recurring maintenance jobs are imported in the seed data and are scheduled to run overnight. These will more than likely be above the job we have just scheduled since their run-time is further in the future. The entered parameters are converted to a map and then serialized to the database. They are then fed to the service at run time. Quickly Running a Service Using the Webtools console it is also possible to run a service synchronously. This is quicker than going through the scheduler should you need to test a service or debug through a service. Select the Run Service button from the menu and enter the same service name, submit then enter the same parameters again. This time the service is run straight away and the OUT parameters and messages are passed back to the screen: Naming a Service and the Service Reference Service names must be unique throughout the entire application. Because we do not need to specify a location when we invoke a service, if service names were duplicated we can not guarantee that the service we want to invoke is the one that is actually invoked. OFBiz comes complete with a full service reference, which is in fact a dictionary of services that we can use to check if a service exists with the name we are about to choose, or even if there is a service already written that we are about to duplicate. From https://localhost:8443/webtools/control/main select the Service Reference and select "l" for learning. Here we can see all of our learning services, what engine they use and what method they invoke. By selecting the service learningCallingServiceOne, we can obtain complete information about this service as was defined in the service definition file services.xml. It even includes information about the parameters that are passed in and out automatically. Careful selection of intuitive service names and use of the description tags in the service definition files are good practice since this allows other developers to reuse services that already exists, rather than duplicate work unnecessarily. Event Condition Actions (ECA) ECA refers to the structure of rules of a process. The Event is the trigger or the reason why the rule is being invoked. The condition is a check to see if we should continue and invoke the action, and the action is the final resulting change or modification. A real life example of an ECA could be "If you are leaving the house, check to see if it is raining. If so, fetch an umbrella". In this case the event is "leaving the house". The condition is "if it is raining" and the action is "fetch an umbrella". There are two types of ECA rules in OFBiz: Service Event Condition Actions (SECAs) and Entity Event Condition Actions (EECAs). Service Event Condition Actions (SECAs) For SECAs the trigger (Event) is a service being invoked. A condition could be if a parameter equalled something (conditions are optional), and the action is to invoke another service. SECAs are defined in the same directory as service definitions (servicedef). Inside files named secas.xml Take a look at the existing SECAs in applicationsorderservicedefsecas.xml and we can see a simple ECA: <eca service="changeOrderStatus" event="commit" run-on-error="false"> <condition field-name="statusId" operator="equals" value="ORDER_CANCELLED"/> <action service="releaseOrderPayments" mode="sync"/></eca> When the changeOrderStatus transaction is just about to be committed, a lookup is performed by the framework to see if there are any ECAs for this event. If there are, and the parameter statusId is ORDER_CANCELLED then the releaseOrderPayments service is run synchronously. Most commonly, SECAs are triggered on commit or return; however, it is possible for the event to be in any of the following stages in the service's lifecycle: auth—Before Authentication in-validate—Before IN parameter validation out-validate—Before OUT parameter validation invoke—Before service invocation commit—Just before the transaction is committed return—Before the service returns global-commit global-rollback The variables global-commit and i are a little bit different. If the service is part of a transaction, they will only run after a rollback or between the two phases (JTA implementation) of a commit. There are also two specific attributes whose values are false by default: run-on-failure run-on-error You can set them to true if you want the SECA to run in spite of a failure or error. A failure is the same thing as an error, except it doesn't represent a case where a rollback is required. It should be noted that parameters passed into the trigger service are available, if need be, to the action service. The trigger services OUT parameters are also available to the action service. Before using SECAs in a component, the component must be informed of the location of the ECA service-resources: <service-resource type="eca" loader="main" location="servicedef/secas.xml"/> This line must be added under the existing <service-resource> elements in the component's ofbiz-component.xml file. Entity Event Condition Actions (EECAs) For EECAs, the event is an operation on an entity and the action is a service being invoked. EECAs are defined in the same directory as entity definitions (entitydef): inside files named eecas.xml. They are used when it may not necessarily be a service that has initiated an operation on the entity, or you may wish that no matter what service operates on this entity, a certain course of action to be taken. Open the eecas.xml file in the applicationsproductentitydef directory and take a look at the first <eca> element: <eca entity="Product" operation="create-store" event="return"> <condition field-name="autoCreateKeywords" operator="not-equals" value="N"/> <action service="indexProductKeywords" mode="sync" value-attr="productInstance"/></eca> This ECA ensures that once any creation or update operation on a Product record has been committed, so long as the autoCreateKeywords field of this record is not N, then the indexProductKeywords service will be automatically invoked synchronously. The operation can be any of the following self-explanatory operations: create store remove find create-store (create or store/update) create-remove store-remove create-store-remove any The return event is by far the most commonly used event in an EECA. But there are also validate, run, cache-check, cache-put, and cache-clear events. There is also the run-on-error attribute. Before using EECAs in a component, the component must be informed of the location of the eca entity-resource: <entity-resource type="eca" loader="main" location="entitydef/eecas.xml"/> must be added under the existing <entity-resource> elements in the component's ofbiz-component.xml file. ECAs can often catch people out! Since there is no apparent flow from the trigger to the service in the code they can be difficult to debug. When debugging always keep an eye on the logs. When an ECA is triggered, an entry is placed into the logs to inform us of the trigger and the action. Summary This brings us to the end of our investigation into the OFBiz Service Engine. We have discovered how useful the Service Oriented Architecture in OFBiz can be and we have learnt how the use of some of the built in Service Engine tools, like the Service Reference, can help us when we are creating new services. In this article we have looked at: Calling services from code (using dispatcher). IN/OUT parameter mismatch when calling services Sending feedback; standard return codes success, error and fail. Implementing Service Interfaces Synchronous and asynchronous services Using the Service Engine tools ECAs: Event Condition Actions
Read more
  • 0
  • 0
  • 3087

article-image-joomla-15-installing-creating-and-managing-modules
Packt
10 Nov 2010
2 min read
Save for later

Joomla! 1.5: Installing, Creating, and Managing Modules

Packt
10 Nov 2010
2 min read
Joomla! 1.5 Cookbook Over 60 quick and direct recipes to help you overcome common Joomla! queries. Find quick solutions to common Joomla! problems Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible Look at recipes that cover the portions of Joomla! 1.6 that are brand new Over 60 practical recipes covering a range of site management and core Joomla! activities         In this recipe, we'll look at all aspects of a module. How to do it... Installing a Module Login to your Administrator Console. Click Extensions | Install/Uninstall. Once you are in here, you'll have a few options to choose from: There are three methods to install a module, in this section we'll focus on the first method. We'll examine the other two in a moment. Click Browse... and find the file. Click Upload File & Install.Once you successfully installed the module, Joomla! will indicate this with this message: How it works... Module installation is a very similar process to components. The Joomla! universal installer has made it very simple. The installer will write the appropriate settings to the database and will copy the files down to their respective locations. There's more... There comes a time when you no longer need a module. Or you may wish to disable it or even create a new one that didn't exist before. As modules are essentially very lightweight in nature, creating them and placing them is easy. The next few recipes cover these items. Deleting modules There are two methods to delete a module. METHOD 1: Click Extensions | Install/Uninstall. Click Modules. Check the module you wish to delete. Once you check the module(s) you wish to delete, click Uninstall in the upper right-hand side: Once you successfully uninstall the module, Joomla! will indicate this with this message: METHOD 2: Click Extensions | Module Manager. Check the module you wish to delete. Click Delete in the upper right-hand side, the key difference is the message:
Read more
  • 0
  • 0
  • 3083

article-image-drupal-6-content-construction-kit-cck
Packt
09 Oct 2009
6 min read
Save for later

Drupal 6 Content Construction Kit (CCK)

Packt
09 Oct 2009
6 min read
Views module provide administrators with the means to modify how Drupal displays lists of content, and CCK exposes its fields to the Views module, making them perfect partners when it comes to creating custom content and then displaying that content in a highly configurable manner. At the time of writing, Views is not available for Drupal 6 (although the module is being actively developed and should hopefully be ready by the time you read this) so it is left as an exercise to download and install it, and create at least one new View, utilizing fields created in the following sections. Installing CCK CCK is available, so go ahead and download the latest version and extract the file to your modules folder. CCK adds its own section to the Modules page under Site building: There are a number of interdependent sections for this module, but all of them rely on the first option, Content, so go ahead and enable this first. We are going to look over all the features provided by CCK, by default, in this section. So go ahead and enable those modules that rely only on Content. With that done, enable the remaining options so that you end up with everything working, like this: Notice that some of the options are disabled to prevent us from inadvertently disabling an option that is required by something else. If, for example, you wish to disable Text, then disable Node Reference and User Reference first. Working with CCK With all the options enabled, we can now go ahead and create a new content type. Actually, it is possible to create new content types without the use of CCK, it's just that the new content types will look pretty much like the standard content types already available, because there are no really interesting fields to add. Head over to Content types under Content management and select the Add content type field to bring up the following page: The identification section is pretty straightforward. You can go ahead and fill in whatever new content settings are appropriate. Of special interest is the Submission form settings below this that allows you to decide whether the default Title and Body fields should be changed or even retained (in the case of the Body field): In the case of the Endangered Species content type, it doesn't really make sense to have a species Title, rather a Common name makes more sense. Leaving the Body field label blank will cause this field to be omitted completely in the event that it is not suitable for the type of content you have in mind. You may have noticed that there are several additional tabs to the right of Add content type tab that provide additional functionality. These options are discussed a little later on in this section. So for now, go ahead and fill out the Name, Type, and Description fields and click Save content type to add this to the default list: We are now ready to begin customizing this new type utilizing whatever options are available—depending on what is or is not enabled. It is possible to customize any type that is available on Drupal, including the default ones like Blog entry or Poll, but to begin with it is best to leave these alone. To begin working on the new content type, click on edit in the Endangered Species row. We can now look at the various aspects of working with content types, beginning with… Adding Fields Select the Add field tab to bring up the following page: This dialog allows you to specify the new field's machine readable name and then select what type of input it is going to be. Presently, only the Create new field section is displayed on this page, because we have yet to add new fields. Once there is at least one custom field available, this page will have an additional section allowing existing fields to be added directly from any content type (you can come back here once there are a few saved fields): Regardless, the Create new field list presently comprises of the following options: Node Reference – Allows the poster to reference another node using its ID value Integer, Decimal, Float – Allows posters to store numbers in various formats Text – Allows posters to enter content User Reference – Allows posters to reference other users. Remember that this list is subject to change, depending on whether you disable various components of the default package, for example, Node Reference or User Reference, or include additional modules that add field types such as Date or Fivestar. Each value type comes with a set of options for how that data should be entered. Looking at the Integer type, we can see that users can be prompted for an integer with a Text Field, Select list, Check boxes, and radio buttons—in this case, the Select list is going to be used. Be careful about how information is stored—it is important to be efficient. For example, don't store information as text when there is only a certain number of options available, instead, store them as a number and provide the right input type to display the various options appropriately. To demonstrate this point, consider that at the moment, the numbers_in_wild field is set as an integer with the Select list input type. We are not going to provide a select list of every possible integer, but we are going to represent a range of numbers with an integer. For example, the value 1 will correspond to the range 1-10, 2 will correspond to 11-100, and so on. With the new field created, the configuration page for this field (Click on configure in the Operations column of the Manage fields page) now displays the current settings available. To begin with, the options in the Endangered Species settings are not of much interest as we have not specified what data this field will hold. To do this, scroll down the page to the Global settings section. From here, you can decide on how the data will be presented to the user and whether or not the field itself will be compulsory or not: Along with the Allowed values list used to input key-value pairs, there are a few other settings that may be of use, depending on what data the field should capture. Minimum and Maximum values along with Suffix and Prefix values allow for some minor input validation, as well as some useful display properties like currency denominations or physical units of measurement.
Read more
  • 0
  • 0
  • 3081
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-developing-application-symfony-13-part-1
Packt
10 Nov 2009
5 min read
Save for later

Developing an Application in Symfony 1.3 (Part 1)

Packt
10 Nov 2009
5 min read
The milkshake shop Our application will be designed for a fictitious milkshake shop. The functional requirements for our shop are: Display of the menu, job vacancies, and locations; these details will be updated from the back office Sign up to a newsletter, where users can submit their details Search facility for the menu Secure backend for staff to update the site The site must be responsive Option for the users to view our vacancies in three languages Creating the skeleton folder structure Symfony has many ways in which it can help the developer create applications with less efforts—one way is by using the Symfony tasks available on the Command Line Interface (CLI). These Symfony tasks do the following: Generate the folder structure for your project, modules, applications, and tasks Clear the generated cache and rotate log files Create controllers to enable and disable an application and set permissions Interact with the ORM layer to build models and forms Interact with SQL to insert data into the database Generate initial tests and execute them Search for text in your templates that need i18N dictionaries and create them If you'd like to see all the tasks that are available with Symfony, just type the following on your command line:symfony Let's begin with using one of the Symfony tasks to generate the file structure for our project. Our project will reside in the milkshake folder. In your terminal window, change your folder path to the path that will hold your project and create this milkshake folder. My folder will reside in workspace folder. Therefore, I would type this: $mkdir ~/workspace/milkshake && cd ~/workspace/milkshake Now that I have the project folder and have changed the path to within the milkshake folder, let's use a Symfony task to generate the project file structure. In your terminal window, type the following: $/home/timmy/workspace/milkshake>symfony generate:project -orm=Propel milkshake We can generate our project we can also specify which ORM we would like to use. Our application is going to use the Propel ORM, but you can also opt for Doctrine ORM. By default, Doctrine ORM is enabled. After pressing the Enter key, the task goes into action. Now you will see output like the one in the following screenshot on your terminal window. This screenshot shows the folder structure being created: Let's have a look at the top-level folders that have been created in our project folder: Folders Description apps This folder contains our frontend application and any other applications that we will create batch If there are any batch scripts, they are placed here cache This folder is the location for cached files and/or scaffolded modules config This folder holds all the main configuration files and the database schema definitions data This folder holds data files such as test or fixture data doc All our documentation should be stored in this folder; this includes briefs, PhpDoc for API, Entity Relationship Diagrams, and so on lib Our models and classes are located in this folder so that all applications can access them log This folder holds the development controllers log files and our Apache log plugins All installed plugins are located in this folder test All unit and functional tests should be placed in this folder; Symfony will create and place stubs in this folder when we create our modules web This is the web root folder that contains all web resources such as images, CSS, JavaScript, and so on There are three folders that must be writable by the web server. These are the cache, log, and web/uploads/. If these are not writable to your web server, then the server itself will either produce warnings at startup or fail to start. The files permissions are usually set during the generation process, but sometimes this can fail. You can use the following task to set the permissions:$/home/timmy/workspace/milkshake>symfony project:permissions With the initial project skeleton built, next we must create an application. Symfony defines an application as operations that are grouped logically and that can run independent of one another. For example, many sites have a frontend and back office/admin area. The admin area is where a user logs in and updates areas on the frontend. Of course, our application will also provide this functionality. We will call these areas frontend and backend. Our first application is going to be the frontend. Again, let's use a Symfony task to generate the frontend application folder structure. Enter the following task in your terminal window: $/home/timmy/workspace/milkshake>symfony generate:app frontend Again, after executing this task, you will see the following in your terminal window: Let's have a look at the top-level folders that have just been created in the apps folder: Directory Description config This folder will have all configuration files for our application i18N This folder will contain all Internationalization files lib This folder will hold all application-specific classes modules All our modules will be built in this folder templates The default layout template is created in this folder, and any other global templates that will be created will also be placed in this folder These steps will generate our project and frontend application folder structure, and we can now view our project in a web browser. Open your web browser and go to http://milkshake/frontend_dev.php and you will see the following default Symfony page: Now we can see the default project page along with the instructions on what to do next. The frontend_dev.php file is our index file while developing the frontend application, and adheres to the naming convention of <application>_<environment>.php. This controller is the development controller and is rather helpful while developing. Before we continue though, I urge you to also have a look at the web debug toolbar.
Read more
  • 0
  • 0
  • 3081

article-image-moodle-19-exploring-design-portfolios
Packt
27 May 2010
9 min read
Save for later

Moodle 1.9: Exploring Design Portfolios

Packt
27 May 2010
9 min read
(For more resources on Moodle 1.9, see here.) Exploring the Exabis portfolio The Exabis portfolio is a third-party add-on that can be placed in your courses to allow students to store and organize their work and allow them to share it with others, for example, external verifiers. The code can be downloaded from the Modules and plugins section at the Moodle website (http://moodle.org/mod/data/view.php?d=13&rid=1142&filter=1). Once the code has been installed, the site administrator will need to check the settings of the block for all users. Site-wide settings The first job, for an administrator, is to make sure the settings meet the institution's needs. These settings are available on the administration panel. You may need your site administrator to adjust these for you if you do not have these permissions. The following screenshot shows the two options available: The settings will be determined by what version you have installed on your system, and in this case, the options relate to how the portfolio looks. The key feature of recent portfolios is the ability to create views that are customized web pages. Most students will be familiar with this activity through social networking sites. Installing the Exabis block into a course To use the Exabis block, you first need to enable editing within the course you are responsible for. To do this, you need to click on the Turn editing on button, as shown in the following screenshot: This will change the view of your course, and a block will now be visible on the right-hand column to add further blocks to your course. The Add button, as shown in the previous screenshot, is a drop-down list and will list all available blocks in alphabetical order. You need to scroll down until you find the Exabis E-Portfolio listing and then click to add this block. Once the block has been added to your course area, you can make some more localized adjustments. In the staff view, there are three options. However, the two lower options merely point to different tabs on the same menu as the MyPortfolio link. Once you open the portfolio, you can see the layout of the block and the functions that it supports, as shown in the following screenshot: The personal information tab The first tab allows students to build up some personal information so that they have a sort of limited resume or CV. Once students click on the Information tab, they will see one button (Edit), which will open an edit window to allow them to add some notes and details. The Categories tab After students have entered some basic information about themselves, they need to organize their material. This is achieved initially by establishing some categories under which the information they gather can be structured. In this example, using the Product Design course, the student may need to create categories for each section they are working with. In the UK, for example, this would be: Materials and Components, Design and Market Influence, and Process and Manufacture. By clicking on the Categories tab, there will, as with the Information tab, be an edit button visible. Clicking on this button will open a window to create the required categories, as shown in the following screenshot: By clicking on the New button, as shown in the previous screenshot, the category will be created and you will then have the choice to add sub-categories or new categories as required. The layout of this edit window is as shown in the following screenshot: These can be further broken down into sub-categories that match the course specification. The process is the same as creating categories, and with each new category created, an additional field appears to add sub-categories, as seen in the previous screenshot. The resulting structure could look similar to the following screenshot, where each part of the specification has a corresponding category and sub-category. These categories will now be available in drop-down menus for the students to add various resources, such as files and notes, as shown in the following screenshot: In the previous screenshot, you can see that students have a drop-down box under Categories, which lists categories and sub-categories for them to link their resources too. Building up the portfolio content Students can now build up their portfolio of evidence and can share this information, if they need to, with staff, other students, or external examiners. The information is organized through the main My Portfolio tab, as shown in the following screenshot: Under this tab, there are sub-tabs that allow the students to link to websites, upload files, and also make notes about some of the material they have gathered. Each of these can now be associated with a category or sub-category to give some clear definition to their research work. The following screenshot shows a student adding some files to a sub-category related to design: In the previous screenshot, students could attach a file which may be some notes they made on a factory visit that they have scanned. Gradually, they can start building up a detailed folder of information and links to other useful resources. The following screenshot shows the MyPortfolio view as a student builds up some of their reference material and notes. Each of the resources is clearly categorized and time stamped and the type of resources is easy to see. Creating views In the release under discussion here (version 3.2.3 release 168) there is a tab to create views. This is still under development and not fully functional, but may well be functional by the time you install it. Clicking on the Views tab will show a button to add a view. Clicking on the Add View button will open an edit window to allow the student to organize their views, as shown in the following screenshot: The views are quite basic at present, but will allow students to build up a portfolio of evidence in an easy and organized way. Sharing their work and thoughts If students would like to share some of their work with each other, then they can via the Views tab. This tab, on the latest version, has a link to allow sharing. Once students enable the sharing function by clicking on the Change link, they can then choose what type of sharing they require and with whom. In the case shown here, the student can elect to share his/her work externally by creating a link to his/her folder from an external or an internal link. The Internal Access option allows them to further specify who can see their portfolio. In this case, they can share it with all of the staff who teach them in the design and technology faculty, or just some of the staff. In this case, when the product design teacher logs in and checks for shared portfolios, they will see this student's work. Importing and exporting portfolios Increasingly with e-portfolios there is the need to be able to take the entire portfolio with the students to other places of study or work. With the Exabis system, there is the ability to export the student's work in a number of formats. The two formats, currently available are Shareable Content Object Reference Module (SCORM) and Extensible Markup Language (XML). Both of these are file structures used to import and export groups of files from web-based systems such as Moodle. The import facility in Exabis will import a SCORM file, which is usually in a zipped format. The options shown for Export/Import are shown in the following screenshot: In both cases shown here, the export will allow students to save their work as a ZIP file, and depending on how they have structured their portfolio, they will have a range of choices regarding what to include in the export. The following screenshot shows the options for a SCORM export. The student, as shown in the previous screenshot, has chosen to save his/her Product Development material in a SCORM file. Clicking on the Create SCORM-File button will open a download dialog window where the student can chose where on his/her computer to save the zipped file. An additional feature shown in the previous Export your portfolio screenshot is the ability to include Moodle assignments in the portfolio of evidence. This would be useful if students take the portfolio to a new job. Clicking on the Import from Moodle-Assignments link results in a screen where students can add their assignments, as shown in the following screenshot: Under the Action column shown in this screenshot, the student can click on the add this file link. Clicking this link will open the MyPortfolio:Add window and the student can link this assignment to a category. The resulting link will then appear in their MyPortfolio: Files view. The assignment itself will be a hyperlink, which will open the word-processed assignment when clicked. Opening the assignment link will create a full URL to where the assignment can be located so that external examiners or employers can also view the work. It allows additional notes to be added by the student, such as follow up comments, as shown in the following screenshot: The additional commentary shows how the student has used the portfolio to track their learning process and to reflect on their earlier work. The whole process is therefore contained in an organized structure that the student controls and can be modified as their greater understanding dictates. Future developments in Exabis As mentioned, the views in this portfolio are not yet fully developed, but the current version is very usable. In order to have more flexibility and functionality, it is necessary to install a more fully featured e-portfolio such as MyStuff, which we will investigate in the next section.
Read more
  • 0
  • 0
  • 3081

article-image-so-what-ext-js
Packt
12 Sep 2013
8 min read
Save for later

So, what is Ext JS?

Packt
12 Sep 2013
8 min read
(For more resources related to this topic, see here.) JavaScript is a classless, prototype-oriented language but Ext JS follows a class-based approach to make the code extensible and scalable over time. Class names can be grouped into packages with namespaces using the object property dot-notation (.). Namespaces allow developers to write structured and maintainable code, use libraries without the risk of overwriting functions, avoid cluttering the global namespace, and provide an ability to encapsulate the code. The strength of the framework lies in its component design. The bundled, basic default components can be easily extended as per your needs and the extended components can be re-used. A new component can also be created by combining one or more default components. The framework includes many default components such as windows, panels, toolbars, drop-down menus, menu bars, dialog boxes, grids, trees, and much more, each with their own configuration properties (configs), component properties, methods, events, and CSS classes. The configs are user-configurable at runtime while instantiating, whereas component properties are references to objects used internally by class. Component properties belong to the prototype of the class and affect all the instances of the class. The properties of the individual components determine the look and feel. The methods help in achieving a certain action. The user interaction triggers the equivalent Ext JS events apart from triggering the DOM events. A cross-browser web application with header, footer, left column section with links, a content with a CSS grid/table (with add, edit, and delete actions for each row of the grid), and a form with few text fields and a submit button can be created with ease using Ext JS's layout mechanism, few default components, and the CSS theme. For the preceding application, the border layout can be used with the north region for the header, south region for the footer, west region for the left column links, and center region for the content. The content area can have a horizontal layout, with the grid and form panel components with text fields and buttons. Creating the preceding application from scratch without using the framework will take a lot more time than it would take by using it. Moreover, this is just one screen, and as the development progresses with more and more features, incorporating new layouts and creating new components will be a tedious process. All the components or a group of components with their layout can be made a custom component and re-used with different data (that is, the grid data can be modified with new data and re-used in a different page). Developers need not worry about the cross-platform compatibility issues, since the framework takes care of this, and they can concentrate on the core logic. The helper functions of the Ext.DomQuery class can be used for querying the DOM. The error handling can be done by using the Ext.Error class, which is a wrapper for the native JavaScript Error object. A simple webpage with a minimal UI too can make use of this framework in many ways. Native JavaScript offers utility classes such as Array, Number, Date, Object, Function, and String, but is limited in what can be done with it across different browsers. Ext JS provides its own version of these classes that works in all the browsers along with offering extra functionality. Any Ext JS component can be added to an existing web page by creating an instance of it. For example, a tab feature can be added to an existing web page by creating a new Ext JS Ext.tab tab component and adding it to an existing div container, by referring the div elements id attribute to the renderTo config property of the tab. The backend communication with your server-side code can be done by using simplified cross-browser Ext.Ajax class methods. Ext JS 4 supports all major web browsers, from Internet Explorer 6 to the latest version of Google Chrome. The recommended browsers for development and debugging are Google Chrome 10+, Apple Safari 5+, and Mozilla Firefox 4+. Both commercial and open source licenses are available for Ext JS. Installation and environment setup In five easy steps, you can be ready with Ext JS and start the development. Step 1 – What do you need? You need the following components for the installation and environment setup: Web browser : Any of the leading browsers mentioned in previous section. For this book, we will consider Mozilla Firebug with the Firebug debugger plugin installed. Web server : To start with, a local web server is not required, but it will be required if communication with a server is required to make AJAX calls. Ext JS 4 SDK : Download the Ext JS bundle from http://www.sencha.com/products/extjs/download/. Click on the Download button on the left side of the page. Step 2 – Installing the browser and debugger Any supported browser mentioned in the previous section can be used for the tutorial. For simplicity and debugging options, we will use the latest Firefox and Firebug debugger plugin. Download the latest Firefox plugin from http://www.mozilla.org/en-US/firefox/fx/#desktop and Firebug from https://getfirebug.com/. Other browser debugging options are as follows: Google Chrome : Chrome Developer Tools ( Tools | Developer tools ) Safari : Go to Settings | Preferences | Advanced , select Show Develop menu in menu bar ; navigate to Develop | Show Web Inspector . Internet Explorer : Go to Tools | Developer Tools   Step 3 – Installing the web server Install the web server and unpack Ext JS. The URLs that provide information for installing the Apache web server on various operating systems are provided as follows: The instructions for installing Apache on Windows can be found at http://httpd.apache.org/docs/current/platform/windows.html The instructions for installing Apache on Linux can be found at http://httpd.apache.org/docs/current/install.html Mac OS X comes with a built-in Apache installation, which you can enable by navigating to System Preferences | Sharing , and selecting the Web Sharing checkbox Install Apache or any other web server in your system. Browse to http://yourwebserver.com or http://localhost, and check that the installation is successful. The http://yourwebserver.com link will show something similar to the the following screenshot, which confirms that Apache is installed successfully: Step 4 – Unpacking Ext JS In this tutorial, we will use Apache for Windows. Unpack the Ext JS bundle into the web server's root directory (htdocs). Rename the Ext JS folder with long version numbers to extjs4 for simplicity. The root directory varies, depending upon your operating system and web server. The Apache root directory path for various operating system are as follows: Windows : C:Program FilesApache Software FoundationApache2.2htdocs Linux : /var/www/ Mac OS X : /Library/WebServer/Documents/ The downloaded EXT JS bundle is packed with examples along with required sources. Browse to http://yourwebserver.com/extjs4, and make sure that it loads the Ext JS index page. This page provides access to all the examples to play around with the API. The API Docs link at bottom-right of the page lists the API information with a search text field at the top-right side of the page. As we progress through the tutorial, please refer to the API as and when required: Step 5 –Testing Ext JS library. A basic Ext JS application page will have a link tag with an Ext JS CSS file (ext-all.css), a script tag for the Ext JS library, and scripts related to your own application. In this example, we don't have any application-specific JavaScripts. Create an HTML file named check.html with the code that follows beneath the httpd folder. Ext.onReady is a method, which is executed when all the scripts are fully loaded. Ext.Msg.alert is a message box that shows a message to the user. The first parameter is the title and the second parameter is the message: <html> <head> <meta http-equiv="Content-Type" content = "text/html; charset=utf-8"> <title>Ext JS started Setup Test</title> <link rel="stylesheet" type="text/css" href = "../extjs4/resources/css/ext-all.css"></link> <script type="text/javascript" src = "../extjs4/ext-all-dev.js"></script> <script type="text/javascript"> Ext.onReady(function() { Ext.Msg.alert("Ext JS 4 Starter","Welcome to Ext 4 Starter!"); }); </script> </head> <body> </body> </html> The following screenshot shows check.html in action: And that's it By now, you should have a working installation of Ext JS, and should be able to play around and discover more about it. Summary Thus we have discussed about having a working environment of EXT JS. Resources for Article : Further resources on this subject: Tips & Tricks for Ext JS 3.x [Article] Ext JS 4: Working with the Grid Component [Article] Building a Ext JS Theme into Oracle APEX [Article]
Read more
  • 0
  • 0
  • 3081

article-image-development-iphone-applications
Packt
06 Oct 2009
6 min read
Save for later

Development of iPhone Applications

Packt
06 Oct 2009
6 min read
Introduction to iPhone It has been quite some time since Apple launched iPhone mobile and made a big wave across the world. Initially it got introduced in US market and within a year's time it was available all over the world. Though there are many who use iPhone mobile, I feel it is important to have an introduction to the device in general, its capabilities and what potential it has for programmers to get the full value for the money. If you have not held an iPhone, I suggest you should do that first. This will motivate you to know more about the device like how Apple implemented it. Some may like the curves, many would like the way it functions, but for me, its sleek, big yet compact form, touch technology and the biggest screen are some of the really cool things. Everyone knows about the "touch technology” of the device, especially the multi-touch which takes care of two fingers touching the screen at the same time at different places. But there is more to iPhone than touch. Other important features are: Location finding: using GPS it figures out where it is at that point of time in the world Accelerometer and Orientation: which give it the ability to detect motion in three dimensions Programmable Vibrator, Camera, address book Such features make iPhone more than a just a phone. Technically, the iPhone exists in two largely similar versions: the 2007 original release and the 2008 3G release. It is a 4.7- or 4.8-ounce computing device. Each device contains a 620 MHz ARM CPU that has been under clocked to improve battery performance and reduce heat. Both devices include 128 MB of dynamic RAM (DRAM), and from 4 to 16 GB of Flash memory. The primary difference between the two devices centers on the global positioning system (GPS) and networking. Some technical specifications: iPhone is built on Apple’s OS X, which itself is built on Unix. iPhone has 480 x 320 touch screen Supports a mobile version of Safari browser Supports LAN and WAN networking using Wi-Fi Uses GPS over Wi-Fi Programming Basics In 2008, Apple released the iPhone SDK, a developer toolkit that allows programmers to develop iPhone application. iPhone SDK lets you develop two type of applications—Web development and Native iPhone Application development. Web applications primarily run on a browser using HTML, CSS and some programming language that can generate dynamic content (Java, ASP, .NET, JSP, Ruby….). Native applications run on iPhone like any other application on the device. They use iPhone software development kit (SDK) released by Apple with the inbuilt frameworks and other frameworks that it support. Ignoring for a while that web and native applications have vast difference in the way they are build and they look, the fact is, they both can produce similar result and for some users it may not be easy to differentiate between them. Interesting isn’t it? Later in this article we will discuss about native application development using the tools and programming language iPhone supports. iPhone SDK uses the Objective-C language, which is an extension to the C language. Like any other mobile, iPhone too has a different programming platform; Windows Mobile (VB.NET/C#) and Android (Java) use object-oriented languages and are identical in syntax. However, Objective-C takes a totally different approach. Being different it creates a learning barrier especially for beginners dealing with Mac OS for the first time. Objective-C as implemented by Apple is built entirely around Objects. It is used throughout the iPhone OS’s frameworks. Windows, views, buttons, sliders and controllers exchange information with each other in the form of events and actions in order to make the program run. A header file (.h) and a source code (.m) file together represent each object in Objective-C. iPhone OS frameworks provide many standard classes that come with the framework, but sometimes you may have to write your own subclasses. When you do this, you’ll need a new header and source code class together to represent the new subclass in your project. The iPhone OS is divided in to four layers (Cocoa touch, Media, Core Services, Core OS), as represented in the diagram. Each layer contains variety of frameworks that you can use in your application/program. Initially, you would be dealing with the top layer. Cocoa touch - the base framework, that you will deal most of the time. It contains the UI-Kit framework which includes window support, event support and user-interface management. Media – the framework that provide the protocols to deal with audio and video build in iPhone. Core Services – the frameworks used in all applications, data types. Core Operating System – the kernel level software. Dealing with threading, networking, I/O, memory etc… What you need for iPhone Development To get started with iPhone programming, you would need the following: An Intel Mac running Mac OS X Leopard v10.5.4 or higher The iPhone SDK for iPhone OS, which you can download from http://developer.apple.com/iphone. The iPhone SDK contains all the tools and utilities you need to develop iPhone applications. In particular, it comes with Xcode 3.1(the development IDE) and the iPhone Simulator that allows you to test your application without needing a real device. Though, you can test the applications on the simulator, it is a good idea to register yourself on the iPhone developer program with a nominal fee. This registration gets you a secured certificate issued by Apple and can be used to test developed applications on the device itself. Hence, two more things are essential if the application has to be tested on the device iPhone mobile device iPhone develop program registration If you are serious about taking up iPhone development, I suggest that you to go for the registration process first before anything else. The registration process in itself is free, but to get the certificate you may have to pay a nominal fee ($100 for individuals). All this process could take up quite some time and meanwhile, you can gear up with all the skills and know-how to proceed with the first application. For more information, see "Accessing the iPhone Developer Program Portal.” The best way to learn iPhone programming is to get your hands dirty and start coding. To start coding, you’ll need iPhone SDK and XCode IDE that comes along with the SDK. Assuming, you are already done with the installation, you can find XCode application icon in the /developer/applications folder. Before starting with the application, take a second and think what you would like to name the first application, I will call it "FirstApp". This point is important to keep in mind as the name of the application, subsequent to installation on device, appears on the home screen. The purpose of the application could be anything, but what you want to call it and what you want it to appear as on the home screen starts by naming the application.
Read more
  • 0
  • 0
  • 3076
article-image-kohas-web-installer-crontab-and-other-server-configurations
Packt
15 Nov 2010
6 min read
Save for later

Koha's Web Installer, Crontab, and other server configurations

Packt
15 Nov 2010
6 min read
Executing Koha's web installer In this section of the article, we will learn how to execute Koha's web installer. The web installer performs several important functions such as creating Koha's database structure or populating mandatory administrative settings. It can also populate optional settings and sample data such as MARC frameworks or patron categories. The installer is launched from the staff client interface using Koha's MySQL user and is a series of interactive steps. At the end of the process we will be able to launch Koha's staff interface and its OPAC. Understanding the web installer's functions Koha's web installer performs the following functions: Checks for the existence of Koha's database, the connectivity to the database, and if the database user has the required privilege on the Koha database. Creates Koha's database structure—its tables, relationships between tables, database constraints, and other rules. Accepts user input on important configuration questions such as Language or MARC flavor. Populates the Koha database with several mandatory administrative settings such as the default system preferences. Populates the Koha database with several optional administrative settings and sample data such as MARC bibliographic frameworks, sample libraries, or sample patron categories. Configures Koha catalog search to use Zebra or to use database indexing. Understanding how to execute the web installer Here are some important points to note about executing Koha's web installer: The web installer is launched from the staff interface. We use a MySQL database user and password to login into the installer; this user must have privileges over Koha's database. Choosing the correct MARC flavor—MARC21 or UNIMARC is very important; it is not possible to change this configuration once the database is created. If you are evaluating or testing Koha, you should choose to import most or all of the optional settings and sample data. This way you can start using Koha right away. The optional settings and sample data can be deleted or edited from Koha's staff client at any time, but this can be significant amount of work. If you have made a mistake in the configuration settings and want to start over, simply drop and recreate Koha's database from the MySQL prompt; you will be able to launch the web installer once again. Understanding optional data available for import Let us understand some of the optional setting and sample data that we can choose to install using the web installer. Settings for MARC frameworks MARC frameworks define how data is captured for different types of material. The frameworks control things such as, which MARC fields are used, which of these fields is mandatory, or which fields are under authority control. The installer has three sets of optional settings that we can import: Matching rules: Matching rules are used during import of catalog records to match incoming records to those already in the database. Further action can be taken on matched records such as overwriting old records or adding holdings records. Two matching rules are available: one matches on ISBN and other on ISSN. Fast Add framework: This framework is designed for quickly adding catalog records; it has fewer fields when compared to other frameworks. Simple MARC 21 Bibliographic frameworks: A set of bibliographic frameworks for common types of material such as books, CDs, or serials. Other data Here is a listing of data we can import under the Other data section: Authorized values: Authorized values are lists of values that control data entry into catalog fields. Here we can import lists along with sample values for fields such as collections, shelving locations, or item statuses. Currencies: A set of currencies with sample exchange rates for use in Koha's Acquisitions module. Sample patron types and categories: A set of sample patron categories such as Student, Teacher, or Staff. Patron categories are used to define rules such as membership duration; the categories are also used to define circulation policy such as loan period. Sample Label and Patron Card Data: A set of sample layouts and templates for use in Koha's label and patron card generation, and printing tool. Sample Holidays: A sample set of holidays for use in Koha's calendar. The calendar is used in Koha's circulation module to calculate due dates and fines. Default Item Types: A sample set of item types. Item types are used to define circulation policy such as loan period or fine amount. Sample Libraries: A sample set of libraries, patrons, catalog items, circulation rules are linked to libraries. Sample News Items: A set of sample news items, for display on the OPAC and the staff interface. Default messages or notices: A set of sample notices. These are used in various Koha modules, for instance the Overdue notice can be configured to be sent to patrons with overdue items. Sample Patrons: A set of patron records. Sample Z3950 servers: A sample set of Z39.50 servers such as that of the Library of Congress. These servers are used in Koha's cataloging module for copy catalog records into Koha. Executing the web installer Here are step-by-step instructions on executing the web installer: Log in using the MySQL user and password; in this article we have used the user kohaadmin. In Step 1, choose your language; you should see just one option here—en for English or fr for French. In Step 2, the installer checks the database connectivity and user privileges. In Step 3, the installer populates the database with tables before prompting the user to install basic configuration settings. Select your MARC flavor—Unimarc or MARC 21. It is important to make the right choice here. Consult with your library staff if you are unsure of what to choose. Choose to import optional data related to MARC frameworks. Choose to import other optional data such as authorized values, currencies, or patron categories. Click on Import to install the settings and sample data. Choose to use Zebra or the regular database indexing. Click on Finish to complete the execution of the web installer. Launching Koha Once the installer finishes it should automatically redirect to the staff interface: Log in using the MySQL user and you should see Koha's staff interface home page: To launch the OPAC navigate to the OPAC url and you should see a screen such as this:  
Read more
  • 0
  • 0
  • 3074

article-image-creating-administration-interface-django
Packt
16 Oct 2009
5 min read
Save for later

Creating an Administration Interface in Django

Packt
16 Oct 2009
5 min read
Activating the Administration Interface The administration interface comes as a Django application. To activate it, we will follow a simple procedure that is similar to how we enabled the user authentication system. The admininistration application is located in the django.contrib.admin package. So the first step is adding the path of this package to the INSTALLED_APPS variable. Open settings.py, locate INSTALLED_APPS and edit it as follows: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.comments', 'django_bookmarks.bookmarks',) Next, run the following command to create the necessary tables for the administration application: $ python manage.py syncdb Now we need to make the administration interface accessible from within our site by adding URL entries for it. The administration application defines many views, so manually adding a separate entry for each view can become a tedious task. Therefore, Django provides a shortcut for this. The administration interface defines all of its URL entries in a module located at django.contrib.admin.urls, and we can include these entries in our project under a particular path by using a function called include(). Open urls.py and add the following URL entry to it: urlpatterns = ( # Admin interface (r'^admin/', include('django.contrib.admin.urls')),) This looks different from how we usually define URL entries. We are basically telling Django to retrieve all of the URL entries in the django.contrib.admin.urls module, and to include them in our application under the path ^admin/. This will make the views of the administration interface accessible from within our project. One last thing remains before we see the administration page in action. We need to tell Django what models can be managed in the administration interface. This is done by defining a class called Admin inside each model. Open bookmarks/models.py and add the highlighted section to the Link model: class Link(models.Model): url = models.URLField(unique=True) def __str__(self): return self.url class Admin: pass The Admin class defined inside the model effectively tells Django to enable the Link model in the administration interface. The keyword pass means that the class is empty. Later, we will use this class to customize the administration page, so it won't remain empty. Do the same to the Bookmark, Tag and SharedBookmark models; append an empty class called Admin to each of them. The User model is provided by Django and therefore we don't have control over it. Fortunately however, it already contains an Admin class so it's available in the administration interface by default. Next, launch the development server and direct your browser to http://127.0.0.1:8000/admin/. You will be greeted by a login page. Remember we need to create a superuser account after writing the database model. This is the account that you have to use in order to log in: Next, you will see a list of the models that are available to the administration interface. As discussed earlier, only models with a class named Admin inside them will appear on this page: If you click on a model name, you will get a list of the objects that are stored in the database under this model. You can use this page to view or edit a particular object, or to add a new one. The figure below shows the listing page for the Link model. The edit form is generated according to the fields that exist in the model. The Link form, for example, contains a single text field called Url. You can use this form to view and change the URL of a Link object. In addition, the form performs proper validation of fields before saving the object. So if you try to save a Link object with an invalid URL, you will receive an error message asking you to correct the field. The figure below shows a validation error when trying to save an invalid link: Fields are mapped to form widgets according to their type. Date fields are edited using a calendar widget for example, whereas foreign key fields are edited using a list widget, and so on. The figure below shows a calendar widget from the user edit page. Django uses it for date and time fields: As you may have noticed, the administration interface represents models by using the string returned by the __str__ method. It was indeed a good idea to replace the generic strings returned by the default __str__ method with more helpful ones. This greatly helps when working with the administration page, as well as with debugging. Experiment with the administration pages; try to create, edit and delete objects. Notice how changes made in the administration interface are immediately reflected on the live site. Also, the administration interface keeps track of the actions that you make, and lets you review the history of changes for each object. This section has covered most of what you need to know in order to use the administration interface provided by Django. This feature is actually one of the main advantages of using Django; you get a fully featured administration interface from writing only a few lines of code! Next, we will see how to tweak and customize the administration pages. And as a bonus, we will learn more about the permissions system offered by Django.
Read more
  • 0
  • 0
  • 3073

article-image-creating-basic-vaadin-project
Packt
13 Dec 2011
10 min read
Save for later

Creating a Basic Vaadin Project

Packt
13 Dec 2011
10 min read
  (For more resources on this topic, see here.)   Understanding Vaadin In order to understand Vaadin, we should first understand what is its goal regarding the development of web applications. Vaadin's philosophy Classical HTML over HTTP application frameworks are coupled to the inherent request/response nature of the HTTP protocol. This simple process translates as follows: The client makes a request to access an URL. The code located on the server parses request parameters (optional). The server writes the response stream accordingly. The response is sent to the client. All major frameworks (and most minor ones, by the way) do not question this model: Struts, Spring MVC, Ruby on Rails, and others, completely adhere to this approach and are built upon this request/response way of looking at things. It is no mystery that HTML/HTTP application developers tend to comprehend applications through a page-flow filter. On the contrary, traditional client-server application developers think in components and data binding because it is the most natural way for them to design applications (for example, a select-box of countries or a name text field). A few recent web frameworks, such as JSF, tried to cross the bridge between components and page-flow, with limited success. The developer handles components, but they are displayed on a page, not a window, and he/she still has to manage the flow from one page to another. The Play Framework (http://www.playframework.org/) takes a radical stance on the page-flow subject, stating that the Servlet API is a useless abstraction on the request/response model and sticks even more to it. Vaadin's philosophy is two-fold: It lets developers design applications through components and data bindings It isolates developers as much as possible from the request/response model in order to think in screens and not in windows This philosophy lets developers design their applications the way it was before the web revolution. In fact, fat client developers can learn Vaadin in a few hours and start creating applications in no time. The downside is that developers, who learned their craft with the thin client and have no prior experience of fat client development, will have a hard time understanding Vaadin as they are inclined to think in page-flow. However, they will be more productive in the long run. Vaadin's architecture In order to achieve its goal, Vaadin uses an original architecture. The first fact of interest is that it is comprised of both a server and a client side. The client side manages thin rendering and user interactions in the browser The server side handles events coming from the client and sends changes made to the user interface to the client Communication between both tiers is done over the HTTP protocol. We will have a look at each of these tiers.   Client server communication Messages in Vaadin use three layers: HTTP, JSON, and UIDL. The former two are completely un-related to the Vaadin framework and are supported by independent third parties; UIDL is internal. HTTP protocol Using the HTTP protocol with Vaadin has the following two main advantages: There is no need to install anything on the client, as browsers handle HTTP (and HTTPS for that matter) natively. Firewalls that let pass the HTTP traffic (a likely occurrence) will let Vaadin applications function normally. JSON message format Vaadin messages between the client and the server use JavaScript Objects Notation (JSON). JSON is an alternative to XML that has the following several differences: First of all, the JSON syntax is lighter than the XML syntax. XML has both a start and an end tag, whereas JSON has a tag coupled with starting brace and ending brace. For example, the following two code snippets convey the same information, but the first requires 78 characters and the second only 63. For a more in depth comparison of JSON and XML, refer to the following URL: http://json.org/xml.html <person> <firstName>John</firstName> <lastName>Doe</lastName> </person> {"person" { {"firstName": "John"}, {"lastName": "Doe"} } The difference varies from message to message, but on an average, it is about 40%. It is a real asset only for big messages, and if you add server GZIP compression, size difference starts to disappear. The reduced size is no disadvantage though. Finally, XML designers go to great length to differentiate between child tags and attributes, the former being more readable to humans and the latter to machines. JSON messages design is much simpler as JSON has no attributes. UIDL "schema" The last stack that is added to JSON and HTTP is the User Interface Definition Language (UIDL). UIDL describes complex user interfaces with JSON syntax. The good news about these technologies is that Vaadin developers won't be exposed to them. The client part The client tier is a very important tier in web applications as it is the one with which the end user directly interacts. In this endeavor, Vaadin uses the excellent Google Web Toolkit (GWT) framework. In the GWT development, there are the following mandatory steps: The code is developed in Java. Then, the GWT compiler transforms the Java code in JavaScript. Finally, the generated JavaScript is bundled with the default HTML and CSS files, which can be modified as a web application. Although novel and unique, this approach provides interesting key features that catch the interest of end users, developers, and system administrators alike: Disconnected capability, in conjunction with HTML 5 client-side data stores Displaying applications on small form factors, such as those of handheld devices Development only with the Java language Excellent scalability, as most of the code is executed on the client side, thus freeing the server side from additional computation On the other hand, there is no such thing as a free lunch! There are definitely disadvantages in using GWT, such as the following: The whole coding/compilation/deployment process adds a degree of complexity to the standard Java web application development. Although a Google GWT plugin is available for Eclipse and NetBeans, IDEs do not provide standard GWT development support. Using GWT development mode directly or through one such plugin is really necessary, because without it, developing is much slower and debugging almost impossible. For more information about GWT dev mode, please refer to the following URL: http://code.google.com/intl/en/webtoolkit/doc/latest/DevGuideCompilingAndDebugging.html There is a consensus in the community that GWT has a higher learning curve than most classic web application frameworks; although the same can be said for others, such as JSF. If the custom JavaScript is necessary, then you have to bind it in Java with the help of a stack named JavaScript Native Interface (JSNI), which is both counter-intuitive and complex. With pure GWT, developers have to write the server-side code themselves (if there is any). Finally, if ever everything is done on the client side, it poses a great security risk. Even with obfuscated code, the business logic is still completely open for inspection from hackers. Vaadin uses GWT features extensively and tries to downplay its disadvantages as much as possible. This is all possible because of the Vaadin server part. The server part Vaadin's server-side code plays a crucial role in the framework. The biggest difference in Vaadin compared to GWT is that developers do not code the client side, but instead code the server side that generates the former. In particular, in GWT applications, the browser loads static resources (the HTML and associated JavaScript), whereas in Vaadin, the browser accesses the servlet that serves those same resources from a JAR (or the WEB-INF folder). The good thing is that it completely shields the developer from the client-code, so he/she cannot make unwanted changes. It may be also seen as a disadvantage, as it makes the developer unable to change the generated JavaScript before deployment. It is possible to add custom JavaScript, although it is rarely necessary. In Vaadin, you code only the server part! There are two important tradeoffs that Vaadin makes in order achieve this: As opposed to GWT, the user interface related code runs on the server, meaning Vaadin applications are not as scalable as pure GWT ones. This should not be a problem in most applications, but if you need to, you should probably leave Vaadin for some less intensive part of the application; stick to GWT or change an entirely new technology. While Vaadin applications are not as scalable as applications architecture around a pure JavaScript frontend and a SOA backend, a study found that a single Amazon EC2 instance could handle more than 10,000 concurrent users per minute, which is much more than your average application. The complete results can be found at the following URL: http://vaadin.com/blog/-/blogs/vaadin-scalabilitystudy-quicktickets Second, each user interaction creates an event from the browser to the server. This can lead to changes in the user interface's model in memory and in turn, propagate modifications to the JavaScript UI on the client. The consequence is that Vaadin applications simply cannot run while being disconnected from the server! If your requirements include the offline mode, then forget Vaadin. Terminal and adapter As in any low-coupled architecture, not all Vaadin framework server classes converse with the client side. In fact, this is the responsibility of one simple interface: com.vaadin.terminal.Terminal. In turn, this interface is used by a part of the framework aptly named as the Terminal Adapter, for it is designed around the Gang of Four Adapter (http://www.vincehuston.org/dp/adapter.html) pattern. This design allows for the client and server code to be completely independent of each other, so that one can be changed without changing the other. Another benefit of the Terminal Adapter is that you could have, for example, other implementations for things such as Swing applications. Yet, the only terminal implementation provided by the current Vaadin implementation is the web browser, namely com.vaadin.terminal.gwt.server.WebBrowser. However, this does not mean that it will always be the case in the future. If you are interested, then browse the Vaadin add-ons directory regularly to check for other implementations, or as an alternative, create your own! Client server synchronization The biggest challenge when representing the same model on two heterogeneous tiers is synchronization between each tier. An update on one tier should be reflected on the other or at least fail gracefully if this synchronization is not possible (an unlikely occurrence considering the modern day infrastructure). Vaadin's answer to this problem is a synchronization key generated by the server and passed on to the client on each request. The next request should send it back to the server or else the latter will restart the current session's application. This may be the cause of the infamous and sometimes frustrating "Out of Sync" error, so keep that in mind.  
Read more
  • 0
  • 0
  • 3062
article-image-adding-worksheets-and-resources-moodle
Packt
27 Oct 2009
12 min read
Save for later

Adding Worksheets and Resources with Moodle

Packt
27 Oct 2009
12 min read
We're teaching the topic of Rivers and Flooding; so to start with, we'll need to introduce our class to some basic facts about rivers and how they work. We aren't going to generate any new stuff yet; we're just going to upload to Moodle what we have already produced in previous years. Putting a worksheet on Moodle The way Moodle works is that we must first upload our worksheet into the course file storage area. Then, in that central section of our course page, we make a link to the worksheet from some appropriately chosen words. Our students click on these words to get to the worksheet. We've got an introductory factsheet (done in Word) about the River Thames. Let's get it into Moodle: Time for action-uploading a factsheet on to Moodle We need to get the worksheet uploaded into Moodle. To get this done, we have to follow a few simple steps. Go to your course page and click on the Turn editing on button, as shown in the following screenshot: Don't worry about all of the new symbols (icons) that appear. In the section you want the worksheet to be displayed, so look for these two boxes: Click on the Add a resource box (I'll go through all its options when we have a recap, later). Select a link to a file or web site. In Name, type the text that you want the students to click on, and in Summary (if you want) add a short description. The following screenshot gives an example of this: Once you're done with the above steps, click on Choose or upload a file. This takes you to the course files storage area. Click on Make a folder, and in the dialog box that is displayed, choose a suitable name for the folder all your worksheets will be stored in (we'll use Worksheets). Click on Create. Click on the folder that you just created (It will be empty except for Parent Folder, which takes you back to the main course files). Click on Upload a file. You'll be prompted to browse your computer's hard drive for the worksheet. Find the worksheet, select it with your cursor and click Open. It will appear as shown in the following screenshot: Click Upload this file. Once the file has been uploaded, it will appear as shown in the following screenshot: What just happened? We just uploaded our first ever worksheet to Moodle. It's now in the course files. Next, we need to make a link on the page that students can click on to get to that worksheet. I know what you're thinking! Thirteen steps, and there's still no sign of our River Thames worksheet on the course page in Moodle. Is it going to be this long-winded every time? Don't worry! There are only two—at worst three—steps left . And although it seems to be a lot of effort the first time, it gets much quicker, as we move on. We are also trying to be organized from the start by putting our worksheets neatly into a folder, so we took a couple of extra steps that we won't have to do next time. The folder will already be there for us. Ofcourse, you can just click on Upload a file and get your worksheets straight into the course files without any sort of order, and they will display for your students just as well. But when you have a lot of worksheets loaded, it will become harder and harder to locate them unless you have a system. Time for action-displaying our factsheet on our course page To get the Moodle course started, we need to create a link that—when clicked, will get the course started, carrying on from where we left off : Click on the word Choose to the right of your worksheet. (We are choosing to put this on Moodle.) The River Thames worksheet now shows in the Location box, under Link to a file or web site. We are almost there! Scroll down and make sure that you have selected the New window option in theWindow box, as shown in the following screenshot: At the bottom of the screen, click on Save and return to course. Done! The option Search for web page would take you to Google or another search engine to find a web site. You could put that web site into the location box instead, and it would make a clickable link for your students to follow. What just happened? Congratulations! You’ve now made a link to the factsheet about the River Thames that will get our Rivers and Flooding course started! By doing the final step above, we will get taken back to the course page where we'll see the words that we wrote in the Name box. They'll be in blue with a line underneath. This tells us it's a clickable link that will take us to the factsheet. If you can do that once, you can do it many times. Have a go hero-putting a slideshow onto Moodle It's important to go through the steps again, pretty quickly, so that you become familiar with them and are able to speed the process up. So why not take one of your slide shows (maybe done in PowerPoint) and upload that to Moodle? Start by creating a folder called Slideshows, so that in future, it will be available for any slideshows that you upload. Or, if you're too tired, just upload another sheet into our Worksheets folder and display that.   Putting a week's worth of slideshows into Moodle Now let's suppose that we have already prepared a week's worth of slideshows. Actually, I could say, a month's worth of worksheets, or a year's worth of exam papers. Basically, what we're going to do is upload several items, all at once. This is very useful because once you get used to uploading and displaying worksheets, you will very quickly start thinking about how tedious it would be, to put them on Moodle one at a time. Especially if you are studying ten major world rivers, and you have to go through all of those steps ten times. Well, you don't! Let's use my River Processes slideshows as our example. I have them saved in a folder on My Computer (as opposed to being shoved at random in a drawer, obviously!). Under normal circumstances, Moodle won't let you upload whole folders just like that. You have to either compress or zip them first (that basically means squeeze it up a bit, so it slides into cyberspace more smoothly). We first need to leave Moodle for a while and go to our own computer. I'm using Windows; for Macs, it will be slightly different. Time for action-getting a whole folder of work into Moodle in one go To view the slideshows, we need to upload the folder containing them from the hard drive of our computer into Moodle. Find the folder that you want to upload, right-click on it, and select Compressed (zipped) Folder within the Send To option. You'll get another folder with the same name, but in ZIP format. Go to your Moodle course page, and in the Administration box, click Files. We're in the course files storage area—this is another way in, if you ever need one! You can upload anything straight into here, and then provide a link to a file or web site. As we have done before, click on Upload and upload the zipped folder (it ends in .zip). Now click on Unzip, which is displayed to the right of your folder name (as shown in the following screenshot), and the folder will be restored to its normal size. What just happened? We put a bunch of slideshows about how rivers work into a folder on our computer. We then zipped the folder to make it slide into Moodle, and then when it was uploaded, we unzipped it to get it back to normal. If you want to be organized, select the checkbox displayed to the left of the zipped folder, and select delete completely. We don't need the zipped folder now, as we have got the original folder back. We now have two choices. Using the Link to a file or web site option in the Add a resource block, we can display each slideshow, in an orderly manner, in the list. We did this with our Thames factsheet, so we know how to do this. Alternatively, we can simply display the folder and let the students open it to get to the slideshows. We're going to opt for the second choice. Why? Bearing in mind about appearances being vital, it would look much neater on our course page if we had a dinky little briefcase icon. The student can click on the briefcase icon to see the list of slideshows, rather than scrolling down a long list on the page. Let us see how this is done: Time for action-displaying a whole folder on Moodle Let us upload the entire folder, which contains the related slideshows, onto Moodle. This will require us to perform only four steps: With editing turned on, click on Add a resource and choose Display a directory. In the Name field, type something meaningful for the students to click on and add a description in the Summary field, if you wish. Click on Display a directory and find the one that you want—for us, RiverProcesses. Scroll down, and click on Save and return to course. What just happened? We made a link to a week's worth of slideshows on our course page, instead of displaying them one at a time. If we looked at the outcome, instead of the icon of a slideshow, such as the PowerPoint icon, we get a folder icon. When the text next to it is clicked, the folder opens, and all of the slideshows inside can be viewed. It is much easier on the eye, when you go directly to the course page, than going through a long list of stuff . Making a 'click here' type link to the River Thames web site Let's learn how to create a link that will lead us to the River Thames web site, or in fact to any web site. However, we're investigating the Thames at the moment, so this would be really helpful. Just imagine, how much simpler it would be for our students to be able to get to a site in one click, rather than type it by hand, spell it wrong, and have it not work. The way we will learn now is easy. In fact, it's so easy that you could do it yourself with only one hint from me. Have a go hero-linking to a web site Do you recollect that we uploaded our worksheet and used Link to a file or web site? We linked it to a file (our worksheet). Here, you just need to link to a web site, and everything else is just the same. When you get to the Link to a file or web site box, instead of clicking Choose or upload a file…, just type in, or copy and paste, the web site that you want to link to (making sure you include only one http://). Remember that we saw earlier, that if you click on Search for web page…, it will take you to Google or some other Search Engine web page to find you a web site that you'd like to link to. The following screenshot shows how to link a file or web site into our Moodle course : That's it! Try it! Go back to your course page; click on the words that you specified as the Name for the web page link, and check whether it works. It should open the web page in a new window, so that once finished, our students can click on the X to close the site and will still have Moodle running in the background. Recap—where do we stand now? We have learnt a lot of interesting things so far. Lets just have a recap of the things that we have learned so far. We have learnt to: Upload and display individual worksheets (as we've worked on the River Thames) Upload and display whole folders of worksheets (as we did with the River Processes slideshows folder) Make a click here type link to any web site that we want, so that our students will just need to click on this link to get to that web site We're now going to have a break from filling up our course for a while, and take a step to another side. Our first venture into Moodle's features was the Link to a file or web site option, but there are many more yet to be investigated. Let's have a closer look at those Add a resource… options in the following screenshot, so that we know, where we are heading: The table below shows all of the Add a Resource… options. What are they, which is the one we need, and what can we safely ignore? You might recognize one or two already. We shall meet the others in a moment.
Read more
  • 0
  • 0
  • 3055

article-image-html5-developing-rich-media-applications-using-canvas
Packt
19 May 2011
10 min read
Save for later

HTML5: Developing Rich Media Applications using Canvas

Packt
19 May 2011
10 min read
HTML5 Multimedia Development Cookbook Recipes for practical, real-world HTML5 multimedia driven development. The cool thing with the new open-source canvas element is that not only can you create dynamic images on the fly, but the users' actions can create new images in real time as well—all without requiring a plugin. Sounds great, right? In many ways it is, but it also leaves our friends using assistive technologies out in the cold. What will happen if you're using a browser that doesn't support the new canvas element? Pretty much nothing. The browser just won't display it. That's why you'll need to be especially careful with this technology and not place anything inside the new canvas element on which your site or application absolutely depends. You must also consider fallback content. Browsers that support canvas include: Before proceeding with developing with the new canvas element, make sure you have a good foundation of skills with HTML and JavaScript. Being comfortable with object-oriented programming sure wouldn't hurt either. Now, let's get cooking! Setting up the canvas environment Creating the new canvas element is easy. How to do it... Check out how simple this is: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> </head> <body> <canvas id="FirstCanvas" width="800" height="600"> <!-- Fallback code goes here --> </canvas> </body> </html> How it works... Of course, we can use whatever height and width dimensions we need, but that simple set of tags is what we need to start. You're probably thinking we could use CSS to control the height and width, but resist that temptation. Because the new canvas element contains a 2d rendering context, that approach can cause unpredictable behavior. There's more... Next, we'll call the new canvas element JavaScript API while calling jQuery: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/ jquery.min.js"></script> <script> $(document).ready(function() { var canvas = document.getElementById("FirstCanvas"); var ctx = canvas.getContext("2d"); }); </script> </head> <body> <canvas id="FirstCanvas" width="800" height="600"> <!-- Fallback code goes here --> </canvas> </body> </html> He's smart "Let me make one thing completely clear: When you use canvas, you're not drawing on the canvas element itself. Instead, you're actually drawing on the 2d rendering context, which you're accessing through the canvas element via the JavaScript API." – Rob Hawkes What am I sayin'? Apple first introduced the new canvas element for the OSX Dashboard years ago. It was later implemented in web browsers Safari and then Chrome, with other browsers following suit. Since then it's become an official part of the HTML5 specification. What's next for <canvas>? Right now, we're barely scratching the surface of what the new canvas element can do. Now and in the future we'll use it to create animations, charts, diagrams, drawing apps, graphs, and user interfaces. What will you dream up? See also Developer Martin Angelov penned a great how-to guide titled, "An HTML5 Slideshow w/Canvas & jQuery" for Tutorial Zine at: http://tutorialzine.com/2010/09/html5-canvas-slideshow-jquery. In it, Martin demonstrates how to combine the new canvas element with jQuery, the most popular JavaScript framework, to create an intensely interactive image slideshow. Understanding the 2d rendering context It's important to understand that the new canvas element is really a "surface" on which to draw bitmapped images in the browser. How to do it... Defining a canvas tag like this only tells half the story: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> </head> <body> <canvas id="FirstCanvas" width="800" height="600"> <!-- Fallback code goes here --> </canvas> </body> </html> How it works... By itself that HTML5 code does nothing. We have to use JavaScript to make the Document Object Model retrieve the 2d rendering context in order to get something to happen: <script> $(document).ready(function() { var canvas = document.getElementById("FirstCanvas"); var ctx = canvas.getContext("2d"); }); </script> To be fair, that bit of JavaScript won't do anything without the canvas tag in the HTML either. There's more... You may be wondering about the name. If there's a 2d rendering context, isn't there probably a 3d rendering context too? The short answer is yes. But the more detailed answer isn't so simple. While a 3d rendering context does exist in theory, at the time of this publication no browser supports it. So if the new canvas element renders in 3d but nobody sees it, did it really do anything? You can master <canvas> The 2d context uses a number of different drawing contexts for the new canvas element that use syntaxes that should look quite familiar if you're experienced with CSS and JavaScript. X, meet Y When drawing, remember the X and Y axis in the top left corner of your browser window. Values increase going down the page. Respect my authority! The World Wide Web Consortium's HTML5 Canvas 2d Context specification is online at: http://dev.w3.org/html5/2dcontext. There we can dig even deeper into information like conformance requirements, the canvas state, transformations, compositing, colors and styles, line styles, shadows, simple shapes, complex shapes, focus management, text, images, pixel manipulation, drawing model, examples, and more. Processing shapes dynamically Let's look at the JavaScript functions that allow the new canvas element to draw rectangles. How to do it... fillRect(x,y,width,height) strokeRect(x,y,width,height) In order: fillRect(x,y,width,height) draws a filled rectangle. Next, strokeRect(x,y,width,height) draws an outline around the rectangle. Now, let's draw some shapes. How it works... We'll start with our basic canvas code and incorporate our new functions: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/ jquery.min.js"></script> <script> $(document).ready(function() { var canvas = document.getElementById("FirstCanvas"); var ctx = canvas.getContext("2d"); ctx.strokeRect(10, 10, 396, 236); ctx.fillStyle = "red"; ctx.fillRect(11, 11, 100, 100); ctx.fillStyle = "white"; ctx.fillRect(111, 11, 34, 100); ctx.fillStyle = "red"; ctx.fillRect(156, 11, 249, 100); ctx.fillStyle = "white"; ctx.fillRect(11, 111, 394, 34); ctx.fillStyle = "red"; ctx.fillRect(11, 145, 100, 100); ctx.fillStyle = "white"; ctx.fillRect(111, 145, 34, 100); ctx.fillStyle = "red"; ctx.fillRect(156, 145, 249, 100); }); </script> </head> <body> <canvas id="FirstCanvas" width="416" height="256"> <p>Flag of Denmark</p> </canvas> </body> </html> What we've created resembles the flag of Denmark! There's more... This example may not seem overwhelming at first, but when you remember that we've created an image with hardly any HTML and no CSS whatsoever, the new canvas element starts to look pretty impressive. Any way you want it Note that while we used color names ("white" and "red") we could also use hexadecimal values or RGB or even HSL! Use whatever makes the most sense for you and your interactive project. Similar to tables? Think of the color and size specifications for this example almost as the old-school tables we used to build back in the day for layout. While certainly not the same, there are definitely similarities to that technique in this case. Be a square first Mastering rectangles is the first canvas technique that's important to have under your belt after the ability to set up the element itself. Understanding the basics of this approach will help you grasp the fundamentals of the next few recipes. Drawing borders for images using canvas Let's take a closer look at the super simple method of drawing borders around images using the new canvas element. How to do it... First, we'll start with our basic canvas code and add one new line to draw a border: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/ jquery.min.js"></script> <script> $(document).ready(function() { var canvas = document.getElementById("FirstCanvas"); var ctx = canvas.getContext("2d"); ctx.strokeRect(10, 20, 100, 100); }); </script> </head> <body> <canvas id="FirstCanvas" width="800" height="600"> <!-- Fallback code goes here --> </canvas> </body> </html> How it works... That one line of JavaScript tells the browser to create a rectangle starting at 10 pixels from the left and 20 pixels from the top of the new canvas element. It draws the box 100 pixels square. There's more... That's nice, but if we want the border to be any other color than the default, we'll need to specify that: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/ jquery.min.js"></script> <script> $(document).ready(function() { var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.strokeStyle = "rgb(0, 128, 0)"; ctx.strokeRect(10, 20, 100, 100); }); </script> </head> <body> <canvas id="myCanvas" width="600" height="600"> <!-- Fallback code goes here --> </canvas> </body> </html> In this case we've used strokeStyle to specify an RGB color of pure green. Style first If you plan to style a border, you'll need to specify that before the border is drawn by the browser. If you specify that style afterward, the browser will simply ignore it. Many color values work The style attribute we just used was RGB, but the method also works with colors ("green", for example), hexadecimal values, HSL, and RGBA. I like big borders and I cannot lie If no border width is specified, the browser will automatically draw a one-pixel border. Here's how to change that: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/ jquery.min.js"></script> <script> $(document).ready(function() { var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.lineWidth = 10; ctx.strokeStyle = "rgb(0, 128, 0)"; ctx.strokeRect(10, 20, 100, 100); }); </script> </head> <body> <canvas id="myCanvas" width="600" height="600"> <!-- Fallback code goes here --> </canvas> </body> </html> It's just this easy:  
Read more
  • 0
  • 0
  • 3048
Modal Close icon
Modal Close icon