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

How-To Tutorials - CMS and E-Commerce

830 Articles
article-image-wordpress-3-security-risks-and-threats
Packt
04 Jul 2011
11 min read
Save for later

WordPress 3 Security: Risks and Threats

Packt
04 Jul 2011
11 min read
  WordPress 3 Ultimate Security Protect your WordPress site and its network         Read more about this book       (For more resources on WordPress, see here.) You may think that most of this is irrelevant to WordPress security. Sadly, you'd be wrong. Your site is only as safe as the weakest link: of the devices that assist in administering it or its server; of your physical security; or of your computing and online discipline. To sharpen the point with a simple example, whether you have an Automattic-managed wordpress.com blog or unmanaged dedicated site hosting, if a hacker grabs a password on your local PC, then all bets are off. If a hacker can borrow your phone, then all bets are off. If a hacker can coerce you to a malicious site, then all bets are off. And so on. Let's get one thing clear. There is no such thing as total security and anyone who says any different is selling something. Then again, what we can achieve, given ongoing attention, is to boost our understanding, to lock our locations, to harden our devices, to consolidate our networks, to screen our sites and, certainly not least of all, to discipline our computing practice. Even this carries no guarantee. Tell you what though, it's pretty darned tight. Let's jump in and, who knows, maybe even have a laugh here and there to keep us awake. Calculated risk So what is the risk? Here's one way to look at the problem: RISK = VULNERABILITY x THREAT A vulnerability is a weakness, a crack in your armour. That could be a dodgy wireless setup or a poorly coded plugin, a password-bearing sticky note, or an unencrypted e-mail. It could just be the tired security guy. It could be 1001 things, and then more besides. The bottom line vulnerability though, respectfully, is our ignorance. A threat, on the other hand, is an exploit, some means of hacking the flaw, in turn compromising an asset such as a PC, a router, a phone, your site. That's the sniffer tool that intercepts your wireless, the code that manipulates the plugin, a colleague that reads the sticky, whoever reads your mail, or the social engineer who tiptoes around security. The risk is the likelihood of getting hacked. If you update the flawed plugin, for instance, then the threat is redundant, reducing the risk. Some risk remains because, when a further vulnerability is found there will be someone, somewhere, who will tailor an exploit to threaten it. This ongoing struggle to minimize risk is the cat and mouse that is security. To minimize risk, we defend vulnerabilities against threats. You may be wondering, why bother calculating risk? After all, any vulnerability requires attention. You'd not be wrong but, such is the myriad complexity of securing multiple assets, any of which can add risk to our site, and given that budgets or our time are at issue, we need to prioritize. Risk factoring helps by initially flagging glaring concerns and, ideally assisted by a security policy, ensuring sensible ongoing maintenance. Securing a site isn't a one-time deal. Such is the threatscape, it's an ongoing discipline.   An overview of our risk Let's take a WordPress site, highlight potential vulnerabilities, and chew over the threats. WordPress is an interactive blogging application written in PHP and working in conjunction with a SQL database to store data and content. The size and complexity of this content manager is extended with third party code such as plugins and themes. The framework and WordPress sites are installed on a web server and that, the platform, and its file system are administered remotely. WordPress. Powering multi-millions of standalone sites plus another 20 million blogs at wordpress.com, Automattic's platform is an attack target coveted by hackers. According to wordpress.org 40% of self-hosted sites run the gauntlet with versions 2.3 to 2.9. Interactive. Just being online, let alone offering interaction, sites are targets. A website, after all, is effectively an open drawer in an otherwise lockable filing cabinet, the server. Now, we're inviting people server-side not just to read but to manipulate files and data. Application, size, and complexity. Not only do applications require security patching but, given the sheer size and complexity of WordPress, there are more holes to plug. Then again, being a mature beast, a non-custom, hardened WordPress site is in itself robust. PHP, third party code, plugins, and themes. Here's a whole new dynamic. The use of poorly written or badly maintained PHP and other code adds a slew of attack vectors. SQL database. Containing our most valuable assets, content and data, MySQL, and other database apps are directly available to users making them immediate targets for hackers. Data. User data from e-mails to banking information is craved by cybercriminals and its compromise, else that of our content, costs sites anything from reputation to a drop or ban in search results as well as carrying the remedial cost of time and money. Content and media. Content is regularly copied without permission. Likewise with media, which can also be linked to and displayed on other sites while you pay for its storage and bandwidth. Upload, FTP, and private areas provide further opportunities for mischief. Sites. Sites-plural adds risk because a compromise to one can be a compromise to all. Web server. Server technologies and wider networks may be hacked directly or via WordPress, jeopardizing sites and data, and being used as springboards for wider attacks. File system. Inadequately secured files provide a means of site and server penetration. Administered remotely. Casual or unsecured content, site, server, and network administration allows for multi-faceted attacks and, conversely, requires discipline, a secure local working environment, and impenetrable local-to-remote connectivity.   Meet the hackers This isn't some cunning ploy by yours-truly to see for how many readers I can attain visitor's rights, you understand. The fact is to catch a thief one has to think like one. Besides, not all hackers are such bad hats. Far from it. Overall there are three types-white hat, grey hat, and black hat-each with their sub-groups. White hat One important precedent sets white hats above and beyond other groups: permission. Also known as ethical hackers, these decent upstanding folks are motivated: To learn about security To test for vulnerabilities To find and monitor malicious activity To report issues To advise others To do nothing illegal To abide by a set of ethics to not harm anyone So when we're testing our security to the limit, that should include us. Keep that in mind. Black hat Out-and-out dodgy dealers. They have nefarious intent and are loosely sub-categorized: Botnets A botnet is a network of automated robots, or scripts, often involved in malicious activity such as spamming or data-mining. The network tends to be comprised of zombie machines, such as your server, which are called upon at will to cause general mayhem. Botnet operators, the actual black hats, have no interest in damaging most sites. Instead they want quiet control of the underlying server resources so their malbots can, by way of more examples, spread malware or Denial of Service (DoS) attacks, the latter using multiple zombies to shower queries to a server to saturate resources and drown out a site. Cybercriminals These are hackers and gangs whose activity ranges from writing and automating malware to data-mining, the extraction of sensitive information to extort or sell for profit. They tend not to make nice enemies, so I'll just add that they're awfully clever. Hacktivists Politically-minded and often inclined towards freedom of information, hacktivists may fit into one of the previous groups, but would argue that they have a justifiable cause. Scrapers While not technically hackers, scrapers steal content-often on an automated basis from site feeds-for the benefit of their generally charmless blog or blog farms. Script kiddies This broad group ranges anything from well-intentioned novices (white hat) to online graffiti artists who, when successfully evading community service, deface sites for kicks. Armed with tutorials galore and a share full of malicious warez, the hell-bent are a great threat because, seeking bragging rights, they spew as much damage as they possibly can. Spammers Again not technically hackers but this vast group leeches off blogs and mailing lists to promote their businesses which frequently seem to revolve around exotic pharmaceutical products. They may automate bomb marketing or embed hidden links but, however educational their comments may be, spammers are generally, but not always, just a nuisance and a benign threat. Misfits Not jargon this time, this miscellaneous group includes disgruntled employees, the generally unloved, and that guy over the road who never really liked you. Grey hat Grey hatters may have good intentions, but seem to have a knack for misplacing their moral compass, so there's a qualification for going into politics. One might argue, for that matter, that government intelligence departments provide a prime example. Hackers and crackers Strictly speaking, hackers are white hat folks who just like pulling things apart to see how they work. Most likely, as kids, they preferred Meccano to Lego. Crackers are black or grey hat. They probably borrowed someone else's Meccano, then built something explosive. Over the years, the lines between hacker and cracker have become blurred to the point that put-out hackers often classify themselves as ethical hackers. This author would argue the point but, largely in the spirit of living language, won't, instead referring to all those trying to break in, for good or bad, as hackers. Let your conscience guide you as to which is which instance and, failing that, find a good priest.   Physically hacked off So far, we have tentatively flagged the importance of a safe working environment and of a secure network from fingertips to page query. We'll begin to tuck in now, first looking at the physical risks to consider along our merry way. Risk falls into the broad categories of physical and technical, and this tome is mostly concerned with the latter. Then again, with physical weaknesses being so commonly exploited by hackers, often as an information-gathering preface to a technical attack, it would be lacking not to mention this security aspect and, moreover, not to sweet-talk the highly successful area of social engineering. Physical risk boils down to the loss or unauthorized use of (materials containing) data: Break-in or, more likely still, a cheeky walk-in Dumpster diving or collecting valuable information, literally from the trash Inside jobs because a disgruntled (ex-)employee can be a dangerous sort Lost property when you leave the laptop on the train Social engineering which is a topic we'll cover separately, so that's ominous Something just breaks ... such as the hard-drive Password-strewn sticky notes aside, here are some more specific red flags to consider when trying to curtail physical risk: Building security whether it's attended or not. By the way, who's got the keys? A cleaner, a doorman, the guy you sacked? Discarded media or paper clues that haven't been criss-cross shredded. Your rubbish is your competitor's profit. Logged on PCs left unlocked, unsecured, and unattended or with hard drives unencrypted and lacking strong admin and user passwords for the BIOS and OS. Media, devices, PCs and their internal/external hardware. Everything should be pocketed or locked away, perhaps in a safe. No Ethernet jack point protection and no idea about the accessibility of the cable beyond the building. No power-surge protection could be a false economy too. This list is not exhaustive. For mid-sized to larger enterprises, it barely scratches the surface and you, at least, do need to employ physical security consultants to advise on anything from office location to layout as well as to train staff to create a security culture. Otherwise, if you work in a team, at least, you need a policy detailing each and every one of these elements, whether they impact your work directly or indirectly. You may consider designating and sub-designating who is responsible for what and policing, for example, kit that leaves the office. Don't forget cell and smart phones and even diaries.  
Read more
  • 0
  • 0
  • 3105

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-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

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
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-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-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

article-image-introducing-hierarchical-menu-typo3
Packt
16 Nov 2010
6 min read
Save for later

Introducing Hierarchical Menu in TYPO3

Packt
16 Nov 2010
6 min read
TYPO3 Templates Create and modify templates with TypoScript and TemplaVoila Build dynamic and powerful TYPO3 templates using TypoScript, TemplaVoila, and other core technologies. Customize dynamic menus, logos, and headers using tricks you won’t find in the official documentation. Build content elements and template extensions to overhaul and improve TYPO3’s default back-end editing experience. Follow along with the step-by-step instructions to build a site from scratch using all the lessons in the book in a practical example. Page tree concepts We are about to dive into all of the little details, but there are a few basic concepts that we need to review first. So, we're going to make sure we have a more complete definition that avoids any confusion: Page tree: Our TYPO3 page tree is all of the pages and folders that we work with. This includes the home page, about us, subpages, and even non-public items such as the storage folder in our example site. If we have a very simple website it could look like this: Home About Us Staff Level: Our page tree will almost always have pages, subpages, and pages under those. In TYPO3, these are considered levels, and they increase as you go deeper into the page tree. For example, in our extremely simple website from the example above both Home and About Us are at the base (or root) of our page tree, so they are on level 0. The staff page is underneath the About Us page in the hierarchy, so it is on level 1. If we added a page for a photo gallery of our last staff lunch as a subpage to the staff page, then it would be at level 2: Home (Level 0) About Us (Level 0) Staff (Level 1) Staff Lunch Gallery (Level 2) Rootline: TYPO3 documentation actually has a few different uses for the term "rootline", but for the menu objects it is the list of pages from your current page or level moving up to the root page. In our example above, the current rootline from the Staff Lunch Gallery is Staff Lunch Gallery | Staff| About Us Before we look at all the different kinds of menus in TYPO3 and all their little differences, we need to explore the base TypoScript object for all of them: HMENU. HMENU generates hierarchical menus, and everything related to menus in TYPO3 is controlled by it. As the base object, HMENU is the one thing that every type of menu is guaranteed to have in common. If we understand how HMENU is creating its hierarchical menu, then everything else is just styling. We can already see an example of HMENU being used in our own TypoScript template setup by looking at the menus that the TemplaVoila Wizard generated for us: ## Main Menu [Begin] lib.mainMenu = HMENU lib.mainMenu.entryLevel = 0 lib.mainMenu.wrap = <ul id="menu-area">|</ul> lib.mainMenu.1 = TMENU lib.mainMenu.1.NO { allWrap = <li class="menu-item">|</li> } ## Main Menu [End] ## Submenu [Begin] lib.subMenu = HMENU lib.subMenu.entryLevel = 1 lib.subMenu.wrap = <ul id="submenu-area">|</ul> lib.subMenu.1 = TMENU lib.subMenu.1.NO { allWrap = <li class="submenu-item">|</li> } ## Submenu [End] We can see that the wizard created two new HMENU objects, lib.mainMenu and lib.subMenu, and assigned properties for the entry level and HTML tags associated with each menu. We're about to learn what those specific properties mean, but we can already use the code from the wizard as an example of how HMENU is created and how properties are defined for it. Types of menu objects The HMENU class does not output anything directly. To generate our menus, we must define a menu object and assign properties to it. In our current menus, the TemplaVoila Wizard generated a menu object for each HMENU in the following highlighted lines: ## Main Menu [Begin] lib.mainMenu = HMENU lib.mainMenu.entryLevel = 0 lib.mainMenu.wrap = <ul id="menu-area">|</ul> lib.mainMenu.1 = TMENU lib.mainMenu.1.NO { allWrap = <li class="menu-item">|</li> } ## Main Menu [End] ## Submenu [Begin] lib.subMenu = HMENU lib.subMenu.entryLevel = 1 lib.subMenu.wrap = <ul id="submenu-area">|</ul> lib.subMenu.1 = TMENU lib.subMenu.1.NO { allWrap = <li class="submenu-item">|</li> } ## Submenu [End] There are a handful of classes for menu objects that can be used by HMENU to generate menus in TYPO3, but we are going to be concentrating on the two most powerful and flexible options: TMENU and GMENU. The TemplaVoila Wizard used TMENU in our current menu, and it is used to generate text-based menus. Menus built with TMENU output the title of each page in the menu as a text link, and then we can use HTML and CSS to add styling and layout options. Menus created with the GMENU class are considered graphic menus. We can use GMENU to dynamically generate images from our page titles so that we can use fancy fonts and effects like drop-shadow and emboss that are not supported in CSS by all browsers equally. Menu item states The menu system in TYPO3 allows us to define states for different menu options. For example, using the state definitions, we can customize the behavior of menu items when they are active or rolled over. The normal state (NO) is available and set by default, but all of the menu item states must be enabled in TYPO3 by adding code to our template like this: lib.mainMenu.1.ACT = 1. All menu objects share a common set of menu item states from the table below: HMENU properties Because HMENU is the root of all of our other menu objects, any of the properties that we learn for HMENU will be applicable to all of our menu options that we might use on future websites. I've included a list of the TypoScript properties that we are most likely to use in the TypoScript template setup, but you can see the complete list in the TSref (http://typo3.org/documentation/document-library/references/doc_core_tsref/current). If you haven't used TypoScript much, and this is too much information all at once, don't worry. It will make more sense in a few pages when we start experimenting on our own site. Then, this will serve as a great reference. As we've already witnessed in the main menu, TYPO3 sorts our menu by the order in the page tree by default. We can use this property to list fields for TYPO3 to use in the database query. For example, if we wanted to list the main menu items in reverse alphabetical order, we could call the alternativeSortingField in our template: lib.mainMenu.1 = TMENU lib.mainMenu.1.alternativeSortingField = title desc
Read more
  • 0
  • 0
  • 3042

article-image-skinners-toolkit-plone-3-theming-part-2
Packt
20 Oct 2009
4 min read
Save for later

Skinner's Toolkit for Plone 3 Theming (Part 2)

Packt
20 Oct 2009
4 min read
(For more resources on Plone, see here.) Text editors The last key piece to successfully skinning a site is to choose a text editor or CSS editor that matches your needs and plays well with Plone. We are not talking about a word processor here, like Microsoft Word or Pages; rather, a text editor is a type of program used for editing plain text files. Text editors are often provided with operating systems or software development packages, and can be used to change configuration files and programming language source code. We'll look at a few of the more popular text editors that are appropriate for Plone development and theming. TextMate TextMate is a combination of text editor and programming tool that is exclusively for the Mac, and can be found at http://macromates.com. One of the key joys of working with TextMate is that it lets you open up an entire file structure at once to make navigation between related files easier. For Plone, this is essential. Your average file structure will look something like this: Rather than opening the entire buildouts folder, or even the plonetheme.copperriver folder, generally you only want to open the structure closest to the files you need in order to keep performance snappy—in this case, mybuildout[rockaway]/src/plonetheme.copperriver/plonetheme/copperriver/: As you can see, it opens the entire project in a clean interface with an easily navigable structure. Without this feature, skinning for Plone would be much more time-consuming. TextMate also offers numerous programmer-related tools: You can open two files at once (or more), and using the diff option you can compare the files easily Subversion (svn) support Ability to search and replace in a project Regular expression search and replace (grep) Auto-indent for common actions such as pasting text Auto-completion of brackets and other characters Clipboard history Foldable code blocks Support for more than 50 languages Numerous key combinations (for example, Apple + T opens a search window that makes it easy to locate a file) Themable syntax highlight colors Visual bookmarks to jump between places in a file Copy/paste of columns of text Bundles And much, much more The Bundle feature is one of the more interesting aspects of the tool. If you look at the HTML bundle, for example, it shows a list of common actions that you might wish to perform in a given document, and on the right, the code that spawns that action, and the hot-key that activates it. There's even a Zope/Plone TextMate support bundle found at http://plone.org/products/textmate-support that was developed by some of Plone's core developers. It enhances TextMate's already existing support for Python, XML, (X)HTML, CSS, and Restructured Text by adding features aimed specifically at the modern day Zope and Plone developer. For the geeks in the audience, the bundle's features include: Doctest support (restructured text with inline Python syntax and auto-indent of python code), pdb support (for debugging), ZCML support (no more looking up directives with our handy and exhaustive snippets), and a ZPT syntax that marries the best of both worlds (XML strictness with the goodness of TextMate's HTML support). This bundle plus TextMate's other capabilities make switching to developing for Plone on a Mac a good idea any day! As well as assigning a single key equivalent to a bundle item, it is possible to assign a tab trigger to the item. This is a sequence of text that you enter in the document and follow it by pressing the tab key. This will remove the sequence entered and then execute the bundle item. TextMate is full of hot-keys and features in general, yet it's surprisingly compact. Thankfully, the documentation is thorough. TextMate is a dream for themers and programmers alike. For those who are still new at CSS, another tool might be a good place to start, but for power users, TextMate is the primary tool of choice.
Read more
  • 0
  • 0
  • 3034
article-image-playing-max-6-framework
Packt
06 Sep 2013
17 min read
Save for later

Playing with Max 6 Framework

Packt
06 Sep 2013
17 min read
(For more resources related to this topic, see here.) Communicating easily with Max 6 – the [serial] object The easiest way to exchange data between your computer running a Max 6 patch and your Arduino board is via the serial port. The USB connector of our Arduino boards includes the FTDI integrated circuit EEPROM FT-232 that converts the RS-232 plain old serial standard to USB. We are going to use again our basic USB connection between Arduino and our computer in order to exchange data here. The [serial] object We have to remember the [serial] object's features. It provides a way to send and receive data from a serial port. To do this, there is a basic patch including basic blocks. We are going to improve it progressively all along this article. The [serial] object is like a buffer we have to poll as much as we need. If messages are sent from Arduino to the serial port of the computer, we have to ask the [serial] object to pop them out. We are going to do this in the following pages. This article is also a pretext for me to give you some of my tips and tricks in Max 6 itself. Take them and use them; they will make your patching life easier. Selecting the right serial port we have used the message (print) sent to [serial] in order to list all the serial ports available on the computer. Then we checked the Max window. That was not the smartest solution. Here, we are going to design a better one. We have to remember the [loadbang] object. It fires a bang, that is, a (print) message to the following object as soon as the patch is loaded. It is useful to set things up and initialize some values as we could inside our setup() block in our Arduino board's firmware. Here, we do that in order to fill the serial port selector menu. When the [serial] object receives the (print) message, it pops out a list of all the serial ports available on the computer from its right outlet prepended by the word port. We then process the result by using [route port] that only parses lists prepended with the word port. The [t] object is an abbreviation of [trigger]. This object sends the incoming message to many locations, as is written in the documentation, if you assume the use of the following arguments: b means bang f means float number i means integer s means symbol l means list (that is, at least one element) We can also use constants as arguments and as soon as the input is received, the constant will be sent as it is. At last, the [trigger] output messages in a particular order: from the rightmost outlet to the leftmost one. So here we take the list of serial ports being received from the [route] object; we send the clear message to the [umenu] object (the list menu on the left side) in order to clear the whole list. Then the list of serial ports is sent as a list (because of the first argument) to [iter]. [iter] splits a list into its individual elements. [prepend] adds a message in front of the incoming input message. That means the global process sends messages to the [umenu] object similar to the following: append xxxxxx append yyyyyy Here xxxxxx and yyyyyy are the serial ports that are available. This creates the serial port selector menu by filling the list with the names of the serial ports. This is one of the typical ways to create some helpers, in this case the menu, in our patches using UI elements. As soon as you load this patch, the menu is filled, and you only have to choose the right serial port you want to use. As soon as you select one element in the menu, the number of the element in the list is fired to its leftmost outlet. We prepend this number by port and send that to [serial], setting it up to the right-hand serial port. Polling system One of the most used objects in Max 6 to send regular bangs in order to trigger things or count time is [metro]. We have to use one argument at least; this is the time between two bangs in milliseconds. Banging the [serial] object makes it pop out the values contained in its buffer. If we want to send data continuously from Arduino and process them with Max 6, activating the [metro] object is required. We then send a regular bang and can have an update of all the inputs read by Arduino inside our Max 6 patch. Choosing a value between 15 ms and 150 ms is good but depends on your own needs. Let's now see how we can read, parse, and select useful data being received from Arduino. Parsing and selecting data coming from Arduino First, I want to introduce you to a helper firmware inspired by the Arduino2Max page on the Arduino website but updated and optimized a bit by me. It provides a way to read all the inputs on your Arduino, to pack all the data read, and to send them to our Max 6 patch through the [serial] object. The readAll firmware The following code is the firmware. int val = 0; void setup() { Serial.begin(9600); pinMode(13,INPUT); } void loop() { // Check serial buffer for characters incoming if (Serial.available() > 0){ // If an 'r' is received then read all the pins if (Serial.read() == 'r') { // Read and send analog pins 0-5 values for (int pin= 0; pin<=5; pin++){ val = analogRead(pin); sendValue (val); } // Read and send digital pins 2-13 values for (int pin= 2; pin<=13; pin++){ val = digitalRead(pin); sendValue (val); } Serial.println();// Carriage return to mark end of data flow. delay (5); // prevent buffer overload } } } void sendValue (int val){ Serial.print(val); Serial.write(32); // add a space character after each value sent } For starters, we begin the serial communication at 9600 bauds in the setup() block. As usual with serial communication handling, we check if there is something in the serial buffer of Arduino at first by using the Serial.available() function. If something is available, we check if it is the character r. Of course, we can use any other character. r here stands for read, which is basic. If an r is received, it triggers the read of both analog and digital ports. Each value (the val variable) is passed to the sendValue()function; this basically prints the value into the serial port and adds a space character in order to format things a bit to provide an easier parsing by Max 6. We could easily adapt this code to only read some inputs and not all. We could also remove the sendValue() function and find another way of packing data. At the end, we push a carriage return to the serial port by using Serial.println(). This creates a separator between each pack of data that is sent. Now, let's improve our Max 6 patch to handle this pack of data being received from Arduino. The ReadAll Max 6 patch The following screenshot is the ReadAll Max patch that provides a way to communicate with our Arduino: Requesting data from Arduino First, we will see a [t b b] object. It is also a trigger, ordering bangs provided by the [metro] object. Each bang received triggers another bang to another [trigger] object, then another one to the [serial] object itself. The [t 13 r] object can seem tricky. It just triggers a character r and then the integer 13. The character r is sent to [spell] that converts it to ASCII code and then sends the result to [serial]. 13 is the ASCII code for a carriage return. This structure provides a way to fire the character r to the [serial] object, which means to Arduino, each time that the metro bangs. As we already see in the firmware, it triggers Arduino to read all its inputs, then to pack the data, and then to send the pack to the serial port for the Max 6 patch. To summarize what the metro triggers at each bang, we can write this sequence: Send the character r to Arduino. Send a carriage return to Arduino. Bang the [serial] object. This triggers Arduino to send back all its data to the Max patch. Parsing the received data Under the [serial] object, we can see a new structure beginning with the [sel 10 13] object. This is an abbreviation for the [select] object. This object selects an incoming message and fires a bang to the specific output if the message equals the argument corresponding to the specific place of that output. Basically, here we select 10 or 13. The last output pops the incoming message out if that one doesn't equal any argument. Here, we don't want to consider a new line feed (ASCII code 10). This is why we put it as an argument, but we don't do anything if that's the one that has been selected. It is a nice trick to avoid having this message trigger anything and even to not have it from the right output of [select]. Here, we send all the messages received from Arduino, except 10 or 13, to the [zl group 78] object. The latter is a powerful list for processing many features. The group argument makes it easy to group the messages received in a list. The last argument is to make sure we don't have too many elements in the list. As soon as [zl group] is triggered by a bang or the list length reaches the length argument value, it pops out the whole list from its left outlet. Here, we "accumulate" all the messages received from Arduino, and as soon as a carriage return is sent (remember we are doing that in the last rows of the loop() block in the firmware), a bang is sent and all the data is passed to the next object. We currently have a big list with all the data inside it, with each value being separated from the other by a space character (the famous ASCII code 32 we added in the last function of the firmware). This list is passed to the [itoa] object. itoa stands for integer to ASCII . This object converts integers to ASCII characters. The [fromsymbol] object converts a symbol to a list of messages. Finally, after this [fromsymbol] object we have our big list of values separated by spaces and totally readable. We then have to unpack the list. [unpack] is a very useful object that provides a way to cut a list of messages into individual messages. We can notice here that we implemented exactly the opposite process in the Arduino firmware while we packed each value into a big message. [unpack] takes as many arguments as we want. It requires knowing about the exact number of elements in the list sent to it. Here we send 12 values from Arduino, so we put 12 i arguments. i stands for integer . If we send a float, [unpack] would cast it as an integer. It is important to know this. Too many students are stuck with troubleshooting this in particular. We are only playing with the integer here. Indeed, the ADC of Arduino provides data from 0 to 1023 and the digital input provides 0 or 1 only. We attached a number box to each output of the [unpack] object in order to display each value. Then we used a [change] object. This latter is a nice object. When it receives a value, it passes it to its output only if it is different from the previous value received. It provides an effective way to avoid sending the same value each time when it isn't required. Here, I chose the argument -1 because this is not a value sent by the Arduino firmware, and I'm sure that the first element sent will be parsed. So we now have all our values available. We can use them for different jobs. But I propose to use a smarter way, and this will also introduce a new concept. Distributing received data and other tricks Let's introduce here some other tricks to improve our patching style. Cordless trick We often have to use some data in our patches. The same data has to feed more than one object. A good way to avoid messy patches with a lot of cord and wires everywhere is to use the [send] and [receive] objects. These objects can be abbreviated with [s] and [r], and they generate communication buses and provide a wireless way to communicate inside our patches. These three structures are equivalent. The first one is a basic cord. As soon as we send data from the upper number box, it is transmitted to the one at the other side of the cord. The second one generates a data bus named busA. As soon as you send data into [send busA], each [receive busA] object in your patch will pop out that data. The third example is the same as the second one, but it generates another bus named busB. This is a good way to distribute data. I often use this for my master clock, for instance. I have one and only one master clock banging a clock to [send masterClock], and wherever I need to have that clock, I use [receive masterClock] and it provides me with the data I need. If you check the global patch, you can see that we distribute data to the structures at the bottom of the patch. But these structures could also be located elsewhere. Indeed, one of the strengths of any visual programming framework such as Max 6 is the fact that you can visually organize every part of your code exactly as you want in your patcher. And please, do that as much as you can. This will help you to support and maintain your patch all through your long development months. Check the previous screenshot. I could have linked the [r A1] object at the top left corner to the [p process03] object directly. But maybe this will be more readable if I keep the process chains separate. I often work this way with Max 6. This is one of the multiple tricks I teach in my Max 6 course. And of course, I introduced the [p] object, that is the [patcher] abbreviation. Let's check a couple of tips before we continue with some good examples involving Max 6 and Arduino. Encapsulation and subpatching When you open Max 6 and go to File | New Patcher , it opens a blank patcher. The latter, if you recall, is the place where you put all the objects. There is another good feature named subpatching . With this feature, you can create new patchers inside patchers, and embed patchers inside patchers as well. A patcher contained inside another one is also named a subpatcher. Let's see how it works with the patch named ReadAllCutest.maxpat. There are four new objects replacing the whole structures we designed before. These objects are subpatchers. If you double-click on them in patch lock mode or if you push the command key (or Ctrl for Windows), double-click on them in patch edit mode and you'll open them. Let's see what is there inside them. The [requester] subpatcher contains the same architecture that we designed before, but you can see the brown 1 and 2 objects and another blue 1 object. These are inlets and outlets. Indeed, they are required if you want your subpatcher to be able to communicate with the patcher that contains it. Of course, we could use the [send] and [receive] objects for this purpose too. The position of these inlets and outlets in your subpatcher matters. Indeed, if you move the 1 object to the right of the 2 object, the numbers get swapped! And the different inlets in the upper patch get swapped too. You have to be careful about that. But again, you can organize them exactly as you want and need. Check the next screenshot: And now, check the root patcher containing this subpatcher. It automatically inverts the inlets, keeping things relevant. Let's now have a look at the other subpatchers: The [p portHandler] subpatcher The [p dataHandler] subpatcher The [p dataDispatcher] subpatcher In the last figure, we can see only one inlet and no outlets. Indeed, we just encapsulated the global data dispatcher system inside the subpatcher. And this latter generates its data buses with [send] objects. This is an example where we don't need and even don't want to use outlets. Using outlets would be messy because we would have to link each element requesting this or that value from Arduino with a lot of cords. In order to create a subpatcher, you only have to type n to create a new object, and type p, a space, and the name of your subpatcher. While I designed these examples, I used something that works faster than creating a subpatcher, copying and pasting the structure on the inside, removing the structure from the outside, and adding inlets and outlets. This feature is named encapsulate and is part of the Edit menu of Max 6. You have to select the part of the patch you want to encapsulate inside a subpatcher, then click on Encapsulate , and voilà! You have just created a subpatcher including your structures that are connected to inlets and outlets in the correct order. Encapsulate and de-encapsulate features You can also de-encapsulate a subpatcher. It would follow the opposite process of removing the subpatcher and popping out the whole structure that was inside directly outside. Subpatching helps to keep things well organized and readable. We can imagine that we have to design a whole patch with a lot of wizardry and tricks inside it. This one is a processing unit, and as soon as we know what it does, after having finished it, we don't want to know how it does it but only use it . This provides a nice abstraction level by keeping some processing units closed inside boxes and not messing the main patch. You can copy and paste the subpatchers. This is a powerful way to quickly duplicate process units if you need to. But each subpatcher is totally independent of the others. This means that if you need to modify one because you want to update it, you'd have to do that individually in each subpatcher of your patch. This can be really hard. Let me introduce you to the last pure Max 6 concept now named abstractions before I go further with Arduino. Abstractions and reusability Any patch created and saved can be used as a new object in another patch. We can do this by creating a new object by typing n in a patcher; then we just have to type the name of our previously created and saved patch. A patch used in this way is called an abstraction . In order to call a patch as an abstraction in a patcher, the patch has to be in the Max 6 path in order to be found by it. You can check the path known by Max 6 by going to Options | File Preferences . Usually, if you put the main patch in a folder and the other patches you want to use as abstractions in that same folder, Max 6 finds them. The concept of abstraction in Max 6 itself is very powerful because it provides reusability . Indeed, imagine you need and have a lot of small (or big) patch structures that you are using every day, every time, and in almost every project. You can put them into a specific folder on your disk included in your Max 6 path and then you can call (we say instantiate ) them in every patch you are designing. Since each patch using it has only a reference to the one patch that was instantiated itself, you just need to improve your abstraction; each time you load a patch using it, the patch will have up-to-date abstractions loaded inside it. It is really easy to maintain all through the development months or years. Of course, if you totally change the abstraction to fit with a dedicated project/patch, you'll have some problems using it with other patches. You have to be careful to maintain even short documentation of your abstractions. Let's now continue by describing some good examples with Arduino.
Read more
  • 0
  • 0
  • 3034

article-image-social-networks-and-extending-user-profile-drupal-part-1
Packt
27 Nov 2009
5 min read
Save for later

Social Networks and Extending the User Profile in Drupal: Part-1

Packt
27 Nov 2009
5 min read
The term "social network" means different things to different people. However, the starting point of any network is the individuals within it. A user profile provides a place for site members to describe themselves, and for other site members to find out about them. In this article, we will examine how to create a user profile that is aligned with the goals of your site. Identifying the Goals of Your Profile User profiles can be used for a range of purposes. On one end of the spectrum, a profile can be used to store basic information about the user. On the other end of the spectrum, a user profile can be a place for a user to craft and share an online identity. As you create the functionality behind your user profile page, you should know the type of profile you want to create for your users. Drupal ships with a core Profile module. This module is a great starting point, and for many sites will provide all of the functionality needed. If, however, you want a more detailed profile, you will probably need to take the next step: building a node-based profile. This involves creating a content type that stores profile information. Node-based profiles offer several practical advantages; these nodes can be extended using CCK fields, and they can be categorized using a taxonomy. In Drupal 6, user profiles become nodes through using the Content Profile module. The most suitable approach to user profiles will be determined by the goals of your site. Using Drupal's core Profile module provides some simple options that will be easy to set up and use. Extending profiles via the Content Profile module allows for a more detailed profile, but requires more time to set up. In this article, we will begin by describing how to set up profiles using the core Profile module. Then we will look at how to use the Content Profile module. Using the Core Profile Module To use the core profile module, click on the Administer | Site building | Modules link, or navigate to admin/build/modules. In the Core – optional section, enable the Profile module. Click the Save configuration button to submit the form and save the settings. Once the Profile module has been enabled, you can see a user's profile information by navigating to http://example.com/user/UID, where UID is the user's ID number on the site. To see your own user profile, navigate to http://example.com/user when logged in, or click the My Account link. The default user profile page exposes some useful functionality. First, it shows the user's profile, and secondly, it provides the Edit tab that allows a user to edit their profile. The Edit tab will only be visible to the owner of the profile, or to administrative users with elevated permissions. Other modules can add tabs to the core Profile page. As shown in the preceding screenshot by Item 1, the core Tracker module adds a Track tab; this tab gives an overview of all of the posts to which this user has participated. As shown in the preceding screenshot by item, the Contact tab has been added by the core Contact module. The Contact module allows users to contact one another via the site. Customizing the Core Profile The first step in customizing the user profile requires us to plan what we want the profile to show. By default, Drupal only requires users to create a username and provide an email address. From a user privacy perspective, this is great. However, for a teacher trying to track multiple students across multiple classes, this can be less than useful. For this sample profile, we will add two fields using the core Profile module: a last name, and a birthday. The admin features for the core profile module are accessible via the Administer | User Management | Profiles link, or you can navigate to admin/user/profile. As seen in the preceding screenshot, the core profile module offers the following possibilities for customization: single-line textfield—adds a single line of text; useful for names or other types of brief information. multi-line text field—adds a larger textarea field; useful for narrative-type profile information. checkbox—adds a checkbox; useful for Yes/No options. list selection—allows the site admin to create a set of options; the user can then select from these pre-defined options. Functionally, this is similar to a controlled vocabulary created using the core Taxonomy module. freeform list—adds a field where the user can enter a comma-separated list. Functionally, this is similar to a tag-based vocabulary created using the core Taxonomy module. URL—allows users to enter a URL; this is useful for allowing users to add a link to their personal blog. date—adds a date field. In our example profile—adding a last name and a birthday—our last name will be a single-line textfield; our birthday will be a date field.
Read more
  • 0
  • 0
  • 3032

article-image-advanced-indexing-and-array-concepts
Packt
26 Dec 2012
6 min read
Save for later

Advanced Indexing and Array Concepts

Packt
26 Dec 2012
6 min read
(For more resources related to this topic, see here.) Installing SciPy SciPy is the scientific Python library and is closely related to NumPy. In fact, SciPy and NumPy used to be one and the same project many years ago. In this recipe, we will install SciPy. How to do it... In this recipe, we will go through the steps for installing SciPy. Installing from source: If you have Git installed, you can clone the SciPy repository using the following command: git clone https://github.com/scipy/scipy.gitpython setup.py buildpython setup.py install --user This installs to your home directory and requires Python 2.6 or higher. Before building, you will also need to install the following packages on which SciPy depends: BLAS and LAPACK libraries C and Fortran compilers There is a chance that you have already installed this software as a part of the NumPy installation. Installing SciPy on Linux: Most Linux distributions have SciPy packages. We will go through the necessary steps for some of the popular Linux distributions: In order to install SciPy on Red Hat, Fedora, and CentOS, run the following instructions from the command line: yum install python-scipy In order to install SciPy on Mandriva, run the following command line instruction: urpmi python-scipy In order to install SciPy on Gentoo, run the following command line instruction: sudo emerge scipy On Debian or Ubuntu, we need to type the following: sudo apt-get install python-scipy Installing SciPy on Mac OS X: Apple Developer Tools (XCode) is required, because it contains the BLAS and LAPACK libraries. It can be found either in the App Store, or in the installation DVD that came with your Mac, or you can get the latest version from Apple Developer's connection at https://developer.apple.com/technologies/tools/. Make sure that everything, including all the optional packages is installed. You probably already have a Fortran compiler installed for NumPy. The binaries for gfortran can be found at http://r.research.att.com/tools/. Installing SciPy using easy_install or pip: Install with either of the following two commands: sudo pip install scipyeasy_install scipy Installing on Windows: If you have Python installed already, the preferred method is to download and use the binary distribution. Alternatively, you may want to install the Enthought Python distribution, which comes with other scientific Python software packages. Check your installation: Check the SciPy installation with the following code: import scipy print scipy.__version__ print scipy.__file__ This should print the correct SciPy version. How it works... Most package managers will take care of any dependencies for you. However, in some cases, you will need to install them manually. Unfortunately, this is beyond the scope of this book. If you run into problems, you can ask for help at: The #scipy IRC channel of freenode, or The SciPy mailing lists at http://www.scipy.org/Mailing_Lists Installing PIL PIL, the Python imaging library, is a prerequisite for the image processing recipes in this article. How to do it... Let's see how to install PIL. Installing PIL on Windows: Install using the Windows executable from the PIL website http://www.pythonware.com/products/pil/. Installing on Debian or Ubuntu: On Debian or Ubuntu, install PIL using the following command: sudo apt-get install python-imaging Installing with easy_install or pip: At the t ime of writing this book, it appeared that the package managers of Red Hat, Fedora, and CentOS did not have direct support for PIL. Therefore, please follow this step if you are using one of these Linux distributions. Install with either of the following commands: easy_install PILsudo pip install PIL Resizing images In this recipe, we will load a sample image of Lena, which is available in the SciPy distribution, into an array. This article is not about image manipulation, by the way; we will just use the image data as an input. Lena Soderberg appeared in a 1972 Playboy magazine. For historical reasons, one of those images is often used in the field of image processing. Don't worry; the picture in question is completely safe for work. We will resize the image using the repeat function. This function repeats an array, which in practice means resizing the image by a certain factor. Getting ready A prerequisite for this recipe is to have SciPy, Matplotlib, and PIL installed. How to do it... Load the Lena image into an array. SciPy has a lena function , which can load the image into a NumPy array: lena = scipy.misc.lena() Some refactoring has occurred since version 0.10, so if you are using an older version, the correct code is: lena = scipy.lena() Check the shape. Check the shape of the Lena array using the assert_equal function from the numpy.testing package—this is an optional sanity check test: numpy.testing.assert_equal((LENA_X, LENA_Y), lena.shape) Resize the Lena array. Resize the Lena array with the repeat function. We give this function a resize factor in the x and y direction: resized = lena.repeat(yfactor, axis=0).repeat(xfactor, axis=1) Plot the arrays. We will plot the Lena image and the resized image in two subplots that are a part of the same grid. Plot the Lena array in a subplot: matplotlib.pyplot.subplot(211) matplotlib.pyplot.imshow(lena) The Matplotlib subplot function creates a subplot. This function accepts a 3-digit integer as the parameter, where the first digit is the number of rows, the second digit is the number of columns, and the last digit is the index of the subplot starting with 1. The imshow function shows images. Finally, the show function displays the end result. Plot the resized array in another subplot and display it. The index is now 2: matplotlib.pyplot.subplot(212) matplotlib.pyplot.imshow(resized) matplotlib.pyplot.show() The following screenshot is the result with the original image (first) and the resized image (second): The following is the complete code for this recipe: import scipy.misc import sys import matplotlib.pyplot import numpy.testing # This script resizes the Lena image from Scipy. if(len(sys.argv) != 3): print "Usage python %s yfactor xfactor" % (sys.argv[0]) sys.exit() # Loads the Lena image into an array lena = scipy.misc.lena() #Lena's dimensions LENA_X = 512 LENA_Y = 512 #Check the shape of the Lena array numpy.testing.assert_equal((LENA_X, LENA_Y), lena.shape) # Get the resize factors yfactor = float(sys.argv[1]) xfactor = float(sys.argv[2]) # Resize the Lena array resized = lena.repeat(yfactor, axis=0).repeat(xfactor, axis=1) #Check the shape of the resized array numpy.testing.assert_equal((yfactor * LENA_Y, xfactor * LENA_Y), resized.shape) # Plot the Lena array matplotlib.pyplot.subplot(211) matplotlib.pyplot.imshow(lena) #Plot the resized array matplotlib.pyplot.subplot(212) matplotlib.pyplot.imshow(resized) matplotlib.pyplot.show() How it works... The repeat function repeats arrays, which, in this case, resulted in changing the size of the original image. The Matplotlib subplot function creates a subplot. The imshow function shows images. Finally, the show function displays the end result. See also The Installing SciPy recipe The Installing PIL recipe
Read more
  • 0
  • 0
  • 3019
article-image-self-service-business-intelligence-creating-value-data
Packt
20 Sep 2013
15 min read
Save for later

Self-service Business Intelligence, Creating Value from Data

Packt
20 Sep 2013
15 min read
(For more resources related to this topic, see here.) Over the years most businesses have spent considerable amount of time, money, and effort in building databases, reporting systems, and Business Intelligence (BI) systems. IT often thinks that they are providing the necessary information to the business users for them to make the right decisions. However, when I meet the users they tell me a different story. Most often they say that they do not have the information they need to do their job. Or they have to spend a lot of time getting the relevant information. Many users state that they spend more time getting access to the data than understanding the information. This divide between IT and business is very common, it causes a lot of frustration and can cost a lot of money, which is a real issue for companies that needs to be solved for them to be profitable in the future. Research shows that by 2015 companies that build a good information management system will be 20 percent more profitable compared to their peers. You can read the entire research publication from http://download.microsoft.com/download/7/B/8/7B8AC938-2928-4B65-B1B3-0B523DDFCDC7/Big%20Data%20Gartner%20 information_management_in_the_21st%20Century.pdf. So how can an organization avoid the pitfalls in business intelligence systems and create an effective way of working with information? This article will cover the following topics concerning it: Common user requirements related to BI Understanding how these requirements can be solved by Analysis Services An introduction to self-service reporting Identifying common user requirements for a business intelligence system In many cases, companies that struggle with information delivery do not have a dedicated reporting system or data warehouse. Instead the users have access only to the operational reports provided by each line of business application. This is extremely troublesome for the users that want to compare information from different systems. As an example, think of a sales person that wants to have a report that shows the sales pipeline, from the Customer Relationship Management (CRM) system together with the actual sales figures from the Enterprise Resource Planning (ERP) system. Without a common reporting system the users have to combine the information themselves with whatever tools are available to them. Most often this tool is Microsoft Excel. While Microsoft Excel is an application that can be used to effectively display information to the users, it is not the best system for data integration. To perform the steps of extracting, transforming, and loading data (ETL), from the source system, the users have to write tedious formulas and macros to clean data, before they can start comparing the numbers and taking actual decisions based on the information. Lack of a dedicated reporting system can also cause trouble with the performance of the Online Transaction Processing (OLTP) system. When I worked in the SQL Server support group at Microsoft, we often had customers contacting us on performance issues that they had due to the users running the heavy reports directly on the production system. To solve this problem, many companies invest in a dedicated reporting system or a data warehouse. The purpose of this system is to contain a database customized for reporting, where the data can be transformed and combined once and for all from all source systems. The data warehouse also serves another purpose and that is to serve as the storage of historic data. Many companies that have invested in a common reporting database or data warehouse still require a person with IT skills to create a report. The main reason for this is that the organizations that have invested in a reporting system have had the expert users define the requirements for the system. Expert users will have totally different requirements than the majority of the users in the organization and an expert tool is often very hard to learn. An expert tool that is too hard for the normal users will put a strain on the IT department that will have to produce all the reports. This will result in the end users waiting for their reports for weeks and even months. One large corporation that I worked with had invested millions of dollars in a reporting solution, but to get a new report the users had to wait between nine and 12 months, before they got the report in their hand. Imagine the frustration and the grief that waiting this long before getting the right information causes the end users. To many users, business intelligence means simple reports with only the ability to filter data in a limited way. While simple reports such as the one in the preceding screenshot can provide valuable information, it does not give the users the possibility to examine the data in detail. The users cannot slice-and-dice the information and they cannot drill down to the details, if the aggregated level that the report shows is insufficient for decision making. If a user would like to have these capabilities, they would need to export the information into a tool that enables them to easily do so. In general, this means that the users bring the information into Excel to be able to pivot the information and add their own measures. This often results in a situation where there are thousands of Excel spreadsheets floating around in the organization, all with their own data, and with different formulas calculating the same measures. When analyzing data, the data itself is the most important thing. But if you cannot understand the values, the data is of no benefit to you. Many users find that it is easier to understand information, if it is presented in a way that they can consume efficiently. This means different things to different users, if you are a CEO, you probably want to consume aggregated information in a dashboard such as the one you can see in the following screenshot: On the other hand, if you are a controller, you want to see the numbers on a very detailed level that would enable you to analyze the information. A controller needs to be able to find the root cause, which in most cases includes analyzing information on a transaction level. A sales representative probably does not want to analyze the information. Instead, he or she would like to have a pre-canned report filtered on customers and time to see what goods the customers have bought in the past, and maybe some suggested products that could be recommended to the customers. Creating a flexible reporting solution What the companies need is a way for the end users to access information in a user-friendly interface, where they can create their own analytical reports. Analytical reporting gives the user the ability to see trends, look at information on an aggregated level, and drill down to the detailed information with a single-click. In most cases this will involve building a data warehouse of some kind, especially if you are going to reuse the information in several reports. The reason for creating a data warehouse is mainly the ability to combine different sources into one infrastructure once. If you build reports that do the integration and cleaning of the data in the reporting layer, then you will end up doing the same tasks of data modification in every report. This is both tedious and could cause unwanted errors as the developer would have to repeat all the integration efforts in all the reports that need to access the data. If you do it in the data warehouse you can create an ETL program that will move the data, and prepare it for the reports once, and all the reports can access this data. A data warehouse is also beneficial from many other angles. With a data warehouse, you have the ability to offload the burden of running the reports from the transactional system, a system that is built mainly for high transaction rates at high speed, and not for providing summarized data in a report to the users. From a report authoring perspective a data warehouse is also easier to work with. Consider the simple static report shown in the first screenshot. This report is built against a data warehouse that has been modeled using dimensional modeling. This means that the query used in the report is very simple compared to getting the information from a transactional system. In this case, the query is a join between six tables containing all the information that is available about dates, products, sales territories, and sales. selectf.SalesOrderNumber,s.EnglishProductSubcategoryName,SUM(f.OrderQuantity) as OrderQuantity,SUM(f.SalesAmount) as SalesAmount,SUM(f.TaxAmt) as TaxAmtfrom FactInternetSales fjoin DimProduct p on f.ProductKey=p.ProductKeyjoin DimProductSubcategory s on p.ProductSubcategoryKey =s.ProductSubcategoryKeyjoin DimProductCategory c on s.ProductCategoryKey =c.ProductCategoryKeyjoin DimDate d on f.OrderDateKey = d.DateKeyjoin DimSalesTerritory t on f.SalesTerritoryKey =t.SalesTerritoryKeywhere c.EnglishProductCategoryName = @ProductCategoryand d.CalendarYear = @Yearand d.EnglishMonthName = @MonthNameand t.SalesTerritoryCountry = @Countrygroup by f.SalesOrderNumber, s.EnglishProductSubcategoryName You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. The preceding query is included for illustrative purposes. As you can see it is very simple to write for someone that is well versed in Transact-SQL. Compare this to getting all the information from the operational system necessary to produce this report, and all the information stored in the six tables. It would be a daunting task. Even though the sample database for AdventureWorks is very simple, we still need to query a lot of tables to get to the information. The following figure shows the necessary tables from the OLTP system you would need to query, to get the information available in the six tables in the data warehouse. Now imagine creating the same query against a real system, it could easily be hundreds of tables involved to extract the data that are stored in a simple data model used for sales reporting. As you can see clearly now, working against a model that has been optimized for reporting is much simpler when creating the reports. Even with a well-structured data warehouse, many users would struggle with writing the select query driving the report shown earlier. The users, in general, do not know SQL. They typically do not understand the database schema since the table and column names usually consists of abbreviations that can be cryptic to the casual user. What if a user would like to change the report, so that it would show data in a matrix with the ability to drill down to lower levels? Then they most probably would need to contact IT. IT would need to rewrite the query and change the entire report layout, causing a delay between the need of the data and the availability. What is needed is a tool that enables the users to work with the business attributes instead of the tables and columns, with simple understandable objects instead of a complex database engine. Fortunately for us SQL Server contains this functionality; it is just for us database professionals to learn how to bring these capabilities to the business. That is what this article is all about, creating a flexible reporting solution allowing the end users to create their own reports. I have assumed that you as the reader have knowledge of databases and are well-versed with your data. What you will learn in this article is, how to use a component of SQL Server 2012 called SQL Server Analysis Services to create a cube or semantic model, exposing data in the simple business attributes allowing the users to use different tools to create their own ad hoc reports. Think of the cube as a PivotTable spreadsheet in Microsoft Excel. From the users perspective, they have full flexibility when analyzing the data. You can drag-and-drop whichever column you want to, into either the rows, columns, or filter boxes. The PivotTable spreadsheet also summarizes the information depending on the different attributes added to the PivotTable spreadsheet. The same capabilities are provided through the semantic model or the cube. When you are using the semantic model the data is not stored locally within the PivotTable spreadsheet, as it is when you are using the normal PivotTable functionality in Microsoft Excel. This means that you are not limited to the number of rows that Microsoft Excel is able to handle. Since the semantic model sits in a layer between the database and the end user reporting tool, you have the ability to rename fields, add calculations, and enhance your data. It also means that whenever new data is available in the database and you have processed your semantic model, then all the reports accessing the model will be updated. The semantic model is available in SQL Server Analysis Services. It has been part of the SQL Server package since Version 7.0 and has had major revisions in the SQL Server 2005, 2008 R2, and 2012 versions. This article will focus on how to create semantic models or cubes through practical step-by-step instructions. Getting user value through self-service reporting SQL Server Analysis Services is an application that allows you to create a semantic model that can be used to analyze very large amounts of data with great speed. The models can either be user created, or created and maintained by IT. If the user wants to create it, they can do so, by using a component in Microsoft Excel 2010 and upwards called PowerPivot. If you run Microsoft Excel 2013, it is included in the installed product, and you just need to enable it. In Microsoft Excel 2010, you have to download it as a separate add-in that you either can find on the Microsoft homepage or on the site called http://www.powerpivot.com. PowerPivot creates and uses a client-side semantic model that runs in the context of the Microsoft Excel process; you can only use Microsoft Excel as a way of analyzing the data. If you just would like to run a user created model, you do not need SQL Server at all, you just need Microsoft Excel. On the other hand, if you would like to maintain user created models centrally then you need, both SQL Server 2012 and SharePoint. Instead, if you would like IT to create and maintain a central semantic model, then IT need to install SQL Server Analysis Services. IT will, in most cases, not use Microsoft Excel to create the semantic models. Instead, IT will use Visual Studio as their tool. Visual Studio is much more suitable for IT compared to Microsoft Excel. Not only will they use it to create and maintain SQL Server Analysis Services semantic models, they will also use it for other database related tasks. It is a tool that can be connected to a source control system allowing several developers to work on the same project. The semantic models that they create from Visual Studio will run on a server that several clients can connect to simultaneously. The benefit of running a server-side model is that they can use the computational power of the server, this means that you can access more data. It also means that you can use a variety of tools to display the information. Both approaches enable users to do their own self-service reporting. In the case where PowerPivot is used they have complete freedom; but they also need the necessary knowledge to extract the data from the source systems and build the model themselves. In the case where IT maintains the semantic model, the users only need the knowledge to connect an end user tool such as Microsoft Excel to query the model. The users are, in this case, limited to the data that is available in the predefined model, but on the other hand, it is much simpler to do their own reporting. This is something that can be seen in the preceding figure that shows Microsoft Excel 2013 connected to a semantic model. SQL Server Analysis Services is available in the Standard edition with limited functionality, and in the BI and Enterprise edition with full functionality. For smaller departmental solutions the Standard edition can be used, but in many cases you will find that you need either the BI or the Enterprise edition of SQL Server. If you would like to create in-memory models, you definitely cannot run the Standard edition of the software since this functionality is not available in the Standard edition of SQL Server. Summary In this article, you learned about the requirements that most organizations have when it comes to an information management platform. You were introduced to SQL Server Analysis Services that provides the capabilities needed to create a self-service platform that can serve as the central place for all the information handling. SQL Server Analysis Services allows users to work with the data in the form of business entities, instead of through accessing a databases schema. It allows users to use easy to learn query tools such as Microsoft Excel to analyze the large amounts of data with subsecond response times. The users can easily create different kinds of reports and dashboards with the semantic model as the data source. Resources for Article : Further resources on this subject: MySQL Linked Server on SQL Server 2008 [Article] Connecting to Microsoft SQL Server Compact 3.5 with Visual Studio [Article] FAQs on Microsoft SQL Server 2008 High Availability [Article]
Read more
  • 0
  • 0
  • 3004

article-image-using-aspnet-master-pages-your-mcms-applications
Packt
29 Apr 2010
6 min read
Save for later

Using ASP.NET Master Pages in your MCMS Applications

Packt
29 Apr 2010
6 min read
Overview and Benefits of Master Pages A master page includes common markup and one or more content placeholders. From this master page, new content pages can be created, which include content controls that are linked to the content placeholders in the master page. This provides an ideal way to separate common site branding, navigation, etc., from the actual content pages, and can significantly decrease duplication and markup errors. Master pages make working with template files a lot easier than before. You can add common markup and shared controls such as headers, footers, and navigation bars to master pages. Once a master page has been built, you can create MCMS template files based upon it. The template files will immediately adopt the look and feel defined in the master template. You can also mark certain regions of the master page to be customizable by introducing content placeholders (note that these are controls designed specifically for master pages and are not to be confused with MCMS placeholder controls). The space marked by content placeholders provides areas where you could add individual template markup as well as MCMS placeholder controls, as shown in the following diagram: Although at first glance both master pages and MCMS templates offer a way to standardize the look and feel of a site, their similarities end there. Don’t be mistaken into thinking that master pages take over the role of MCMS templates completely. A key difference between the two is that the use of master pages is reserved solely for site developers to ensure that template files created have a common look and feel. You can’t create a master page and expect authors to use it to create postings. In fact, master pages work alongside template files and offer a number of benefits to MCMS developers. Avoids duplication in MCMS Template files: Often MCMS templates contain common page layout code (usually an HTML table) along with navigation bars, headers, and footers (usually web user controls). This code has to be copied and pasted into each new template file after it is created or abstracted into user controls. In addition a change in the layout of this common code has to be applied to all template files. So, for example, an MCMS application with ten template files will duplicate this markup ten times. By placing this markup within a master page, this duplication can be removed. Separation of site-wide markup from template markup: One of the biggest drawbacks to MCMS is that the task of developing templates cannot be easily separated. It is a common requirement to separate the tasks of defining site branding, layout, and the development of controls such as navigation (performed by webmasters and programmers) from the task of designing template layouts (performed by business users). While master pages and Visual Studio 2005 do not address this completely due to MCMS’s inherent architecture, they offer a substantial improvement in this area. Avoids issues with MCMS Template File Visual Studio templates: The MCMS Project Item Templates have a number of issues, and do not fully embrace the Visual Studio 2005 project system. Although any web form can be MCMS ‘enabled’, master pages offer a more seamless development experience with less manual tweaks required. Visual Studio 2005 Designer support: One of the common problems with using user controls within template files in Visual Studio .NET is that the template design view doesn't provide an adequate experience for template developers. Visual Studio 2005 offers an improved design-view experience including rendering of user control content, and this is especially valuable when working with master pages. Experience of Master Pages: Just as MCMS is a great way to learn ASP.NET, MCMS SP2 is a great way to learn ASP.NET 2.0! In addition, master pages are a fundamental building block of future Web Content Management offerings from Microsoft. MCMS placeholder controls in the master page will work, but are not officially supported. As we will see in this article, master pages provide an ideal way to separate common site branding, navigation, etc., from the actual content pages, and can significantly decrease duplication and markup errors. The TropicalGreen Web Site Tropical Green is the fictitious gardening society upon which the article’s sample website is based. In the book, Building Websites with Microsoft Content Management Server from Packt Publishing (ISBN 1-904811-16-7), we built the Tropical Green website from scratch using ASP.NET 1.x. In this article series, we will attempt to rebuild parts of the website using MCMS SP2 and ASP.NET 2.0. While the code will be rewritten from the ground-up, we won’t start with a blank database. Instead, we’ll take a shortcut and import the TropicalGreen database objects from the TropicalGreen.sdo file available from the support section on Packt Publishing’s website (http://www.packtpub.com/support). Importing the TropicalGreen Site Deployment Object File Before we begin, let’s populate the database by importing objects using the Site Deployment Manager. Download the TropicalGreen.sdo file. Open Site Manager and log in with an MCMS administrator account. From the menu, select File | Package | Import…. In the Site Deployment Import dialog, click on the Browse… button. Navigate to the TropicalGreen_Final.sdo file downloaded earlier. In the Container Rules tab, set the following: Property Value When Adding Containers Use package container rights When Replacing Containers Keep destination container rights In the Rights Group tab, set the following: Property Value Select how Rights Groups are imported Import User Rights Groups Click on Import. The import confirmation dialog appears. Click on Continue. Creating a New MCMS Web Application To get started, let’s create a new MCMS web application using the project templates we created in the previous article. From Visual Studio, from the File Menu, choose New | Web Site. In the New Web Site dialog, select the MCMS SP2 Web Application icon in the My Templates section. Select HTTP in the Location list box. Enter http://localhost/TropicalGreen in the Location textbox, and click on OK. Our MCMS web application is created and opened in Visual Studio 2005.
Read more
  • 0
  • 0
  • 2999
Modal Close icon
Modal Close icon