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

How-To Tutorials

7018 Articles
article-image-creating-and-modifying-filters-moodle-19
Packt
06 May 2010
6 min read
Save for later

Creating and Modifying Filters in Moodle 1.9

Packt
06 May 2010
6 min read
Moodle filters modify content from the database as it is output to the screen, thus adding function to the display. An example of this is the multimedia filter, which can detect references to video and audio files, and can replace them with a "mini-player" embedded in the content. How a filter works Before trying to build a filter, it would help to understand how it works. To begin with, any text written to the screen in Moodle should be processed through the format_text function. The purpose of this function is to process the text, such that it is always safe to be displayed. This means making sure there are no security issues and that any HTML used contains only allowed tags. Additionally, the output is run through the filter_text function, and this is the function we are interested in. This function takes the text destined for the screen, and applies all enabled filters to it. The resulting text will be the result of all of these filters. filter_text applies each enabled filter to the text in the order defined in the filter configuration screen (shown in the following screenshot). The order is important; each filter will be fed the output of the previous filter's text. So it is always possible that one filter may change the text in a way that impacts the next filter. Building a filter Now it's time to build our own filter. To begin with, let's come up with a requirement. Let's assume that our organization, called "Learning is Fun", has a main website at http://2fun2learn.org. Now, we need any instance of the phrase learning is fun to be hyperlinked to the website URL every time it appears on the screen, as in the forum post shown in the following screenshots: We can do this by implementing a policy with our content creators that forces them to create hyperlink tags around the phrase every time they write it. However, this will be difficult to enforce and will be fraught with errors. Instead, wouldn't it be easier if the system itself could recognize the phrase and create the hyperlink for us? That's what our filter will do. Getting started We need a name for our filter. It is the name that will be used for the directory the filter will reside in. We want a name that will describe what our filter does and will be unlikely to conflict with any other filter name. Let's call it "learningisfunlink". To start with, create a new subdirectory in the /filter directory and call it learningisfunlink. Next, create a new file called filter.php. This is the only file required for a filter. Open the new filter.php file in your development environment. The filter only requires one function, which is named after the filter name and suffixed with _filter. Add the PHP open and close tags (<?php and ?>), and an empty function called learningisfunlink_filter that takes two arguments: a course ID and the text to filter. When completed, you should have a file that looks like this: <?phpfunction learningisfunlink_filter($courseid, $text) {return $text;}?> We now have the bare minimum required for the filter to be recognized by the system. It doesn't do what we want yet, but it will be present. Creating the language file Log in to the site (that makes use of your new filter) as an administrator. On the main page of your site, look for the Modules Filters| folder in the Site Administration block. Click on the Manage filters link. If you have the default filter setup, you will see your new filter near the bottom of the list, called Learningisfunlink, as shown in the following screenshot: Now, even though the name is reasonably descriptive, it will be better if it were a phrase similar to the others in the list; something like Main website link. To do this, we need to create a new directory in our /filter/learningisfunlink directory called lang/en_utf8/ (the en_utf8 is the language specific part—English in this case). In this directory, we create a new file called filter_learningisfunlink.php. This name is the concatenation of the phrase filter_ and the name of our filter. In this file, we need to add the following line: $string['filtername'] = "Main website link"; This language string defines the text that will be displayed as the name of our filter, replacing the phrase Learningisfunlink that we saw earlier with Main website link. This file will contain any other strings that we may output to the screen, specifically for this filter. Once we have created this file, returning to the Manage filters page should now show our filter with the name that we provided for it in our language file. Creating the filter code We now have a filter that is recognized by the system and that displays the name we want it to. However, we haven't made it do anything. Let's create the code to add some functionality. Remember, what we want this filter to do is to search the text and add a hyperlink pointing to our website for all occurrences of the phrase "learning is fun". We could simply perform a search and replace function on the text and return it, and that would be perfectly valid. However, for the sake of learning more about the Moodle API, we'll use some functions that are set up specifically for filters. To that end, we'll look at two code constructs: the filterobject class and the filter_phrases function, both of which are contained in the /lib/filterlib.php file. The filterobject class defines an object that contains all of the information required by the filter_phrases function to change the text to the way the filter wants it to be. It contains the phrase to be filtered, the tag to start the replacement with, the tag to end the replacement with, whether to match case, whether a full match is required, and any replacement text for the match. An array of filterobjects is sent to the filter_phrases function, along with the text to search in. It's intended to be used when you have a number of phrases and replacements to apply at one time, but we'll use it anyway. Let's initialize our filter strings: $searchphrase = "learning is fun";$starttag = "<a href="http://2fun2learn.org">";$endtag = "</a>"; Now, let's create our filterobject: $filterobjects = array();$filterobjects[] = new filterobject($searchphrase, $starttag, $endtag); Lastly, let's pass the structure to the filter_phrases function, along with the text to be filtered: $text = filter_phrases($text, $filterobjects); Our function now has the code to change any occurrence of the phrase "learning is fun" to a hyperlinked phrase. Let's go test it
Read more
  • 0
  • 0
  • 2576

article-image-soa-implementing-service-oriented-orchestrations
Packt
05 May 2010
7 min read
Save for later

SOA: Implementing Service-Oriented Orchestrations

Packt
05 May 2010
7 min read
The hello process service is a simplified example of a WS-BPEL process service. It doesn't use partner services to get the job done, simply composing a hello message based on the data sent by the client. In contrast, a real-world WS-BPEL process may invoke a lot of partner services during its execution. The following sections take you through creating the documents composing the bpr archive of a poInfo WS-BPEL process service that interacts with two partner services. The partner services used in this example are the following: poOrderDocService and poOrderStatusService. The poInfo process service discussed here is invoked when a client sends a request message containing two parameters: pono and par. The first one specifies the pono of the order document on which you need to get information, while the second one specifies what kind of information should be returned, meaning two possible choices: the entire document or the status of the document. Since you are going to deploy the poInfo process service to the ActiveBPEL engine, you first need to create the required folders in your file system for the project. For example, you may create the folder named poInfo and then create the META-INF, bpel, and wsdl folders within it. Creating the WSDL Definition Describing the WS-BPEL Process As usual, the first step in creating the service is to create the WSDL definition describing that service to its clients. Here is the poInfo.wsdl document that you should save in the wsdl folder created within the poInfo folder, which is the root folder for this project: <?xml version="1.0" encoding="UTF-8"?><definitions name="poInfo" targetNamespace= "http://localhost:8081/active-bpel/services/poInfoService.wsdl" > <import namespace="http://localhost/WebServices/wsdl/poOrderDoc" location="http://localhost/WebServices/wsdl/po_orderdoc.wsdl"/> <import namespace="http://localhost/WebServices/wsdl/poOrderStatus" location="http://localhost/WebServices/wsdl/po_orderstatus.wsdl"/> <types> <schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace= "http://localhost:8081/active-bpel/services/poInfoService.wsdl" > <element name="poInfoRequest"> <complexType> <sequence> <element name="pono" type="xsd:string"/> <element name="par" type="xsd:string"/> </sequence> </complexType> </element> </schema></types><message name="poInfoResponseMessage"> <part name="payload" type="xsd:string"/></message><message name="poInfoRequestMessage"> <part name="payload" element="tns:poInfoRequest"/></message><portType name="poInfoPT"> <operation name="getInfo"> <input message="tns:poInfoRequestMessage"/> <output message="tns:poInfoResponseMessage"/> </operation></portType><plnk:partnerLinkType name="poInfoLT"> <plnk:role name="poInfoProviderRole"> <plnk:portType name="tns:poInfoPT"/> </plnk:role></plnk:partnerLinkType><plnk:partnerLinkType name="poDocLT"> <plnk:role name="poDocProviderRole"> <plnk:portType name="ns2:poOrderDocServicePortType"/> </plnk:role></plnk:partnerLinkType><plnk:partnerLinkType name="poStatusLT"> <plnk:role name="poStatusProviderRole"> <plnk:portType name="ns3:poOrderStatusServicePortType"/> </plnk:role> </plnk:partnerLinkType></definitions> As you can see, the above WSDL definition imports two definitions describing the poOrderDocService and poOrderStatusService partner services. Note the use of the poInfoRequest complex type when defining the input message. This structure makes it possible for the client to send two parameters, namely pono and par, within a single request message. Another important thing to note here is the use of three partner links. The first one defines the interaction between the WS-BPEL process service and its client, while the other two define the relationships between the WS-BPEL service and the poOrderDocService and poOrderStatusService partner services respectively. Creating the WSDL Catalog The next step is to create the wsdlCatalog.xml WSDL catalog document in the META-INF directory of the project. In this example, the document contains only one entry that refers to the poInfo.wsdl document discussed in the preceding section. <?xml version="1.0" encoding="UTF-8"?><wsdlCatalog> <wsdlEntry location="wsdl/poInfo.wsdl" classpath="wsdl/poInfo.wsdl" /></wsdlCatalog> Creating the WS-BPEL Business Definition Containing Conditional Logic The WS-BPEL definition you create in this example is a bit complicated. This is because the poInfo.bpel definition shown below contains conditional logic. <?xml version="1.0" encoding="UTF-8"?><process name="poInfo.bpel" suppressJoinFailure="yes" targetNamespace="http://poInfo.bpel"> <import importType="http://schemas.xmlsoap.org/wsdl/" location="wsdl/poInfo.wsdl" namespace= "http://localhost:8081/active-bpel/services/poInfoService.wsdl"/> <import importType="http://schemas.xmlsoap.org/wsdl/" location="http://localhost/WebServices/wsdl/po_orderdoc.wsdl" namespace="http://localhost/WebServices/wsdl/poOrderDoc"/> <import importType="http://schemas.xmlsoap.org/wsdl/" location="http://localhost/WebServices/wsdl/po_orderstatus.wsdl" namespace= "http://localhost/WebServices/wsdl/poOrderStatus"/> <partnerLinks> <partnerLink myRole="poInfoProviderRole" name="poInfoProvider"partnerLinkType="ns1:poInfoLT"/> <partnerLink name="poDocRequester" partnerLinkType="ns1:poDocLT"partnerRole="poDocProviderRole"/> <partnerLink name="poStatusRequester" partnerLinkType="ns1:poStatusLT" partnerRole="poStatusProviderRole"/> </partnerLinks> <variables> <variable messageType="ns1:poInfoRequestMessage" name="poInfoRequestMessage"/> <variable messageType="ns1:poInfoResponseMessage" name="poInfoResponseMessage"/> <variable messageType="ns2:getOrderDocInput" name="poDocRequestMessage"/> <variable messageType="ns2:getOrderDocOutput" name="poDocResponseMessage"/> <variable messageType="ns3:getOrderStatusInput" name="poStatusRequestMessage"/> <variable messageType="ns3:getOrderStatusOutput" name="poStatusResponseMessage"/> </variables> <sequence> <receive createInstance="yes" operation="getInfo" partnerLink="poInfoProvider" portType="ns1:poInfoPT" variable="poInfoRequestMessage"/> <if> <condition>($poInfoRequestMessage.payload/ns1:par = 'doc')</condition> <sequence> <assign> <copy> <from part="payload" variable="poInfoRequestMessage"> <query>ns1:pono</query> </from> <to part="pono" variable="poDocRequestMessage"/> </copy> </assign> <invoke inputVariable="poDocRequestMessage" outputVariable="poDocResponseMessage" operation="getOrderDoc" partnerLink="poDocRequester" portType="ns2:poOrderDocServicePortType"> </invoke> <assign> <copy> <from>$poDocResponseMessage.doc</from> <to>$poInfoResponseMessage.payload</to> </copy> </assign> </sequence> <elseif> <condition>($poInfoRequestMessage.payload/ns1:par = 'status')</condition> <sequence> <assign> <copy> <from part="payload" variable="poInfoRequestMessage"> <query>ns1:pono</query> </from> <to part="pono" variable="poStatusRequestMessage"/> </copy> </assign> <invoke inputVariable="poStatusRequestMessage" outputVariable="poStatusResponseMessage" operation="getOrderStatus" partnerLink="poStatusRequester" portType="ns3:poOrderStatusServicePortType"> </invoke> <assign> <copy> <from>$poStatusResponseMessage.status</from> <to>$poInfoResponseMessage.payload</to> </copy> </assign> </sequence> </elseif> <else> <assign> <copy> <from>'Wrong input parameter. Should be either doc or status!'</from> <to>$poInfoResponseMessage.payload</to> </copy> </assign> </else> </if> <reply operation="getInfo" partnerLink="poInfoProvider" portType="ns1:poInfoPT" variable="poInfoResponseMessage"/> </sequence></process> The most interesting part of the above WS-BPEL process definition is the if/ elseif/else construct. Schematically it looks like the following: <sequence> activities <if> <condition>...</condition> <sequence> activities </sequence> <elseif> <condition>...</condition> <sequence> activities </sequence> </elseif> <else> activity </else> </if> activities </sequence> Note the use of the inner sequence constructs in the above structure. The fact is that WS-BPEL doesn't allow you to use more than one activity within if or elseif or else blocks. That is why you have to enclose a set of activities within any of those blocks with sequence.
Read more
  • 0
  • 0
  • 1587

article-image-installing-and-managing-multi-master-replication-managermmm-mysql-high-availability
Packt
04 May 2010
5 min read
Save for later

Installing and Managing Multi Master Replication Manager(MMM) for MySQL High Availability

Packt
04 May 2010
5 min read
(Read more interesting articles on MySQL High Availability here.) Multi Master Replication Manager (MMM): initial installation This setup is asynchronous, and a small number of transactions can be lost in the event of the failure of the master. If this is not acceptable, any asynchronous replication-based high availability technique is not suitable. Over the next few recipes, we shall configure a two-node cluster with MMM. It is possible to configure additional slaves and more complicated topologies. As the focus of this article is high availability, and in order to keep this recipe concise, we shall not mention these techniques (although, they all are documented in the manual available at http://mysql-mmm.org/). MMM consists of several separate Perl scripts, with two main ones: mmmd_mon: Runs on one node, monitors all nodes, and takes decisions. mmmd_agent: Runs on each node, monitors the node, and receives instructions from mmm_mon. In a group of MMM-managed machines, each node has a node IP, which is the normal server IP address. In addition, each node has a "read" IP and a "write" IP. Read and write IPs are moved around depending on the status of each node as detected and decided by mmmd_mon, which migrates these IP address around to ensure that the write IP address is always on an active and working master, and that all read IPs are connected to another master that is in sync (which does not have out-of-date data). mmmd_mon should not run on the same server as any of the databases to ensure good availability. Thus, the best practice would be to keep a minimum number of three nodes. In the examples of this article, we will configure two MySQL servers, node 5 and node 6 (10.0.0.5 and 6) with a virtual writable IP of 10.0.0.10 and two read-only IPs of 10.0.0.11 and 10.0.0.12, using a monitoring node node 4 (10.0.0.4). We will use RedHat / CentOS provided software where possible. If you are using the same nodes to try out any of the other recipes discussed in this article, be sure to remove MySQL Cluster RPMs and /etc/my.cnf before attempting to follow this recipe There are several phases to set up MMM. Firstly, the MySQL and monitoring nodes must have MMM installed, and each node must be configured to join the cluster. Secondly, the MySQL server nodes must have MySQL installed and must be configured in a master-master replication agreement. Thirdly, a monitoring node (which will monitor the cluster and take actions based on what it sees) must be configured. Finally, the MMM monitoring node must be allowed to take control of the cluster. In this article, each of the previous four steps is a recipe. The first recipe covers the initial installation of MMM on the nodes. How to do it... The MMM documentation provides a list of required Perl modules. With one exception, all Perl modules currently required for both monitoring agents and server nodes can be found in either the base CentOS / RHEL repositories, or the EPEL library (see the Appendices for instructions on configuration of this repository), and will be installed with the following yum command: [root@node6 ~]# yum -y install perl-Algorithm-Diff perl-Class-Singleton perl-DBD-MySQL perl-Log-Log4perl perl-Log-Dispatch perl-Proc-Daemon perl-MailTools Not all of the package names are obvious for each module; fortunately, the actual perl module name is stored in the Other field in the RPM spec file, which can be searched using this syntax: [root@node5 mysql-mmm-2.0.9]# yum whatprovides "*File::stat*"Loaded plugins: fastestmirror...4:perl-5.8.8-18.el5.x86_64 : The Perl programming languageMatched from:Other : perl(File::stat) = 1.00Filename : /usr/share/man/man3/File::stat.3pm.gz... This shows that the Perl File::stat module is included in the base perl package (this command will dump once per relevant file; in this case, the first file that matches is in fact the manual page). The first step is to download the MMM source code onto all nodes: [root@node4 ~]# mkdir mmm[root@node4 ~]# cd mmm[root@node4 mmm]# wget http://mysql-mmm.org/_media/:mmm2:mysql-mmm-2.0.9.tar.gz--13:44:45-- http://mysql-mmm.org/_media/:mmm2:mysql-mmm-2.0.9.tar.gz...13:44:45 (383 KB/s) - `mysql-mmm-2.0.9.tar.gz' saved [50104/50104] Then we extract it using the tar command: [root@node4 mmm]# tar zxvf mysql-mmm-2.0.9.tar.gzmysql-mmm-2.0.9/mysql-mmm-2.0.9/lib/...mysql-mmm-2.0.9/VERSIONmysql-mmm-2.0.9/LICENSE[root@node4 mmm]# cd mysql-mmm-2.0.9 Now, we need to install the software, which is simply done with the make file provided: [root@node4 mysql-mmm-2.0.9]# make installmkdir -p /usr/lib/perl5/vendor_perl/5.8.8/MMM /usr/bin/mysql-mmm /usr/sbin /var/log/mysql-mmm /etc /etc/mysql-mmm /usr/bin/mysql-mmm/agent/ /usr/bin/mysql-mmm/monitor/...[ -f /etc/mysql-mmm/mmm_tools.conf ] || cp etc/mysql-mmm/mmm_tools.conf /etc/mysql-mmm/ Ensure that the exit code is 0 and that there are no errors: [root@node4 mysql-mmm-2.0.9]# echo $?0 Any errors are likely caused as a result of dependencies—ensure that you have a working yum configuration (refer to Appendices) and have run the correct yum install command.
Read more
  • 0
  • 0
  • 4227

article-image-setting-mysql-replication-high-availability
Packt
04 May 2010
6 min read
Save for later

Setting up MySQL Replication for High Availability

Packt
04 May 2010
6 min read
MySQL Replication is a feature of the MySQL server that allows you to replicate data from one MySQL database server (called the master) to one or more MySQL database servers (slaves). MySQL Replication has been supported in MySQL for a very long time and is an extremely flexible and powerful technology. Depending on the configuration, you can replicate all databases, selected databases, or even selected tables within a database. In this article, by Alex Davies, author of High Availability MySQL Cookbook, we will cover: Designing a replication setup Configuring a replication master Configuring a replication slave without synchronizing data Configuring a replication slave and migrating data with a simple SQL dump Using LVM to reduce downtime on master when bringing a slave online Replication safety tricks Installing and Managing Multi Master Replication Manager(MMM) for MySQL High Availability is covered seperately. Replication is asynchronous, that is, the process of replication is not immediate and there is no guarantee that slaves have the same contents as the master (this is in contrast to MySQL Cluster). Designing a replication setup There are many ways to architect a MySQL Replication setup, with the number of options increasing enormously with the number of machines. In this recipe, we will look at the most common topologies and discuss the advantages and disadvantages of each, in order to show you how to select the appropriate design for each individual setup. Getting ready MySQL replication is simple. A server involved in a replication setup has one of following two roles: Master: Master MySQL servers write all transactions that change data to a binary log Slave: Slave MySQL servers connect to a master (on start) and download the transactions from the master's binary log, thereby applying them to the local server Slaves can themselves act as masters; the transactions that they apply from their master can be added in turn to their log as if they were made directly against the slave. Binary logs are binary files that contain details of every transaction that the MySQL server has executed. Running the server with the binary log enabled makes performance about 1 percent slower. The MySQL master creates binary logs in the forms name.000001, name.000002, and so on. Once a binary log reaches a defined size, it starts a new one. After a certain period of time, MySQL removes old logs. The exact steps for setting up both slaves and masters are covered in later recipes, but for the rest of this recipe it is important to understand that slaves contact masters to retrieve newer bits of the binary log, and to apply these changes to their local database. How to do it... There are several common architectures that MySQL replication can be used with. We will briefly mention and discuss benefits and problems with the most common designs, although we will explore in detail only designs that achieve high availability. Master and slave A single master with one or more slaves is the simplest possible setup. A master with one slave connected from the local network, and one slave connected via a VPN over the Internet, is shown in the following diagram: A setup such as this—with vastly different network connections from the different slaves to the master—will result in the two slaves having slightly different data. It is likely that the locally attached slave may be more up to date, because the latency involved in data transfers over the Internet (and any possible restriction on bandwidth) may slow down the replication process. This Master-Slave setup has the following common uses and advantages: A local slave for backups, ensuring that there is no massive increase in load during a backup period. A remote location—due to the asynchronous nature of MySQL replication, there is no great problem if the link between the master and the slave goes down (the slave will catch up when reconnected), and there is no significant performance hit at the master because of the slave. It is possible to run slightly different structures (such as different indexes) and focus a small number of extremely expensive queries at a dedicated slave in order to avoid slowing down the master. This is an extremely simple setup to configure and manage. A Master-Slave setup unfortunately has the following disadvantages: No automatic redundancy. It is common in setups such as this to use lower specification hardware for the slaves, which means that it may be impossible to "promote" a slave to a master in the case of an master failure. Write queries cannot be committed on the slave node. This means write transactions will have to be sent over the VPN to the master (with associated latency, bandwidth, and availability problems). Replication is equivalent to a RAID 1 setup, which is not an enormously efficient use of disk space (In the previous example diagram, each piece of data is written three times). Each slave does put a slight load on the master as it downloads its binary log. The number of slaves thus can't increase infinitely. Multi-master (active / active) Multi-master replication involves two MySQL servers, both configured as replication masters and slaves. This means that a transaction executed on one is picked up by the other, and vice versa, as shown in the following diagram: A SQL client connecting to the master on the left will execute a query, which will end up in that master's binary log. The master on the right will pick this query up and execute it. The same process, in reverse, occurs when a query is executed on the master on the right. While this looks like a fantastic solution, there are problems with this design: It is very easy for the data on the servers to become inconsistent due to the non-deterministic nature of some queries and "race conditions" where conflicting queries are executed at the same time on each node Recent versions of MySQL include various tricks to minimize the likelihood of these problems, but they are still almost inevitable in most real-world setups. It is extremely difficult to discover if this inconsistency exists, until it gets so bad that the replication breaks (because a replicated query can't be executed on the other node). This design is only mentioned here for completeness; it is often strongly recommended not to use it. Either use the next design, or if more than one "active" node is required, use one of the other high-availability techniques that are available but not covered in this article.
Read more
  • 0
  • 0
  • 9827

article-image-installing-typo3-extensions
Packt
30 Apr 2010
2 min read
Save for later

Installing TYPO3 Extensions

Packt
30 Apr 2010
2 min read
TYPO3 is one of the most functional and powerful content management systems (CMS). Offering both functionality and expansiveness, TYPO3 is a relevant competitor for commercial solutions. One of the advantages of using TYPO3 is that this CMS has expandability possibilities that are called "extensions". Using these extensions, you can extend the TYPO3 functionality. You can manage shops, galleries, forums, or even a small community portal. You can download extensions from the TYPO3 extension repository (TER): http://typo3.org/extensions. *.t3x is the file format used for extension files. This package is partly compressed using GZIP and it contains the necessary files for the extension (SQL dump, tables, functions, templates, image resources, and so on). This site is a recommended easy way to search for appropriate and suitable extensions. Also, you can find an overview of the extension functionality and additional documentation. For easy extension installation, use its import through Extension Manager. In the extensions section, http://typo3.org/extensions, you'll find the following: New and updated: the latest updated or recently added extensions from the last 20 days—as per the claim on the repository. Popular: a list of the most downloaded extensions on TER. Full list: a complete list of extensions sorted by alphabet. Search: search the form to find an appropriate extension you need. A Search form is also provided in the section New and updated. All the extensions are sorted in groups according to their status: Reviewed extensions: extensions that are secure. These extensions don't affect the normal operation of the system and are qualitative. Alfa: early stage of extension development. Beta: early stage of extension development but operates partly. Stable: stable extension that can be used to provide page functionality. Test: test extension. These kinds of extensions are usually without functionality or are used for concept examples. Obsolete: extensions that are included in the TYPO3 core or are associated with other extensions. For our new shop, we need an eCommerce extension that provides product catalogue and functionality of a shopping cart. You can type shop or commerce in the search area and get a few versions of online shop extensions and those extensions that provide extra functionality to basic extensions. Note the most popular and downloaded online shop extensions: Shop System (tt_products) by Franz Holzinger Webformat Shop System (extendedshop) by Mauro Lorenzutti Commerce (commerce) by Ingo Schmitt, Volker Graubaum, and Thomas Hempel
Read more
  • 0
  • 0
  • 2224

article-image-vim-72-scripting
Packt
30 Apr 2010
9 min read
Save for later

Vim 7.2 Scripting

Packt
30 Apr 2010
9 min read
Scripting tips In this section, we will look at a few extra tips that can be handy when you create scripts for Vim. Some are simple code pieces you can add directly in your script, while others are good-to-know tips. Gvim or Vim? Some scripts have extra features when used in the GUI version of Vim (Gvim). This could be adding menus, toolbars, or other things that only work if you are using Gvim. So what do you do to check if the user runs the script in a console Vim or in Gvim? Vim has already prepared the information for you. You simply have to check if the feature gui_running is enabled. To do so, you use a function called has(), which returns 1 (true) if a given feature is supported / enabled and 0 (false), otherwise. An example could be: if has("gui_running") "execute gui-only commands here.endif This is all you need to do to check if a user has used Gvim or not. Note that it is not enough to check if the feature "gui" exists, because this will return true if your Vim is just compiled with GUI support—even if it is not using it. Look in :help 'feature-list' for a complete list of other features you can check with the has() function. Which operating system? If you have tried to work with multiple operating systems such as Microsoft Windows and Linux, you will surely know that there are many differences. This can be everything from where programs are placed, to which programs you have available and how access to files is restricted. Sometimes, this can also have an influence on how you construct your Vim script as you might have to call external programs, or use other functionality, specific for a certain operating system. Vim lets you check which operation system you are on, such that you can stop executing your script or make decisions about how to configure your script. This is done with the following piece of code: if has("win16") || has("win32") || has("win64")|| has("win95") " do windows things hereelseif has("unix") " do linux/unix things hereendif This example only shows how to check for Windows (all flavors available) and Linux / Unix. As Vim is available on a wide variety of platforms, you can of course also check for these. All of the operating systems can be found in: :help 'feature-list' Which version of Vim? Throughout the last decade or two, Vim has developed and been extended with a large list of functions. Sometimes, you want to use the newest functions in your script, as these are the best / easiest to use. But what about the users who have a version of Vim that is older than the one you use, and hence don't have access to the functions you use? You have three options: Don't care and let it be the user's own problem (not a good option). Check if the user uses an old version of Vim, and then stop executing the script if this is the case. Check if the user has too old a version of Vim, and then use alternative code. The first option is really not one I would recommend anyone to use, so please don't use it. The second option is acceptable, if you can't work around the problem in the old version of Vim. However, if it is possible to make an alternative solution for the older version of Vim, then this will be the most preferable option. So let's look at how you can check the version of Vim. Before we look at how to check the version, we have to take a look at how the version number is built. The number consists of three parts: Major number (for example, 7 for Vim version 7) Minor number (for example, 3 for Vim version 6.3) Patch number (for example, 123 for Vim 7.0.123) The first two numbers are the actual version number, but when minor features / patches are applied to a version of Vim, it is mostly only the patch number that is increased. It takes quite a bit of change to get the minor number to increase, and a major part of Vim should change in order to increase the major version number. Therefore, when you want to check which version of Vim the user is using, you do it for two versions—major and minor versions and patch number. The code for this could look like: if v:version >= 702 || v:version == 701 && has("patch123") " code here is only done for version 7.1 with patch 123 " and version 7.2 and aboveendif The first part of the if condition checks if our version of Vim is version 7.2 (notice that the minor version number is padded with 0 if less than 10) or above. If this is not the case, then it checks to see if we have a version 7.1 with patch 123. If patch version 124 or above is included, then you also have patch 123 automatically. Printing longer lines Vim was originally created for old text terminals where the length of lines was limited to a certain number of characters. Today, this old limitation shows up once in a while. One place where you meet this limitation of line length is when printing longer lines to the screen using the "echo" statement. Even though you use Vim in a window where there are more than the traditional 80 characters per line, Vim will still prompt you to press Enter after echoing lines longer than 80 characters. There is, however, a way to get around this, and make it possible to use the entire window width to echo on. Window width means the total number of columns in the Vim window minus a single character. So if your Vim window is wide enough to have 120 characters on each line, then the window width is 120-1 characters. By adding the following function to your script, you will be able to echo screen-wide long lines in Vim: " WideMsg() prints [long] message up to (&columns-1) lengthfunction! WideMsg(msg) let x=&ruler | let y=&showcmd set noruler noshowcmd redraw echo a:msg let &ruler=x | let &showcmd=yendfunction This function was originally proposed by the Vim script developer Yakov Lerner on the Vim online community site at http://www.vim.org. Now whenever you need to echo a long line of text in your script, instead of using the echo statement you simply use the function Widemsg(). An example could be: :call WideMsg("This should be a very long line of text") The length of a single line message is still limited, but now it is limited to the width of the Vim window instead of the traditional 80-1 characters. Debugging Vim scripts Sometimes things in your scripts do not work exactly as you expect them to. In these cases, it is always good to know how to debug your script. In this section, we will look at some of the methods you can use to find your error. Well-structured code often has fewer bugs and is also easier to debug. In Vim, there is a special mode to perform script debugging. Depending on what you want to debug, there are some different ways to start this mode. So let's look at some different cases. If Vim just throws some errors (by printing them at the bottom of the Vim window), but you are not really sure where it is or why it happens, then you might want to try to start Vim directly in debugging mode. This is done on the command line by invoking Vim with the -Dargument. vim -D somefile.txt The debugging mode is started when Vim starts to read the first vimrc file it loads (in most cases the global vimrc file where Vim is installed). We will look at what to do when you get into debug mode in a moment. Another case where you might want to get into debug mode is when you already know which function the error (most likely) is in, and hence, just want to debug that function. In that case you just open Vim as normal (load the script with the particular function if needed) and then use the following command: :debug call Myfunction() Here everything after the :debug is the functionality you want to debug. In this case, it is a simple call of the function Myfunction(), but it could just as well be any of the following: :debug read somefile.txt:debug nmap ,a :call Myfunction() <CR>:debug help :debug So let's look at what to do when we get into the debugging mode. When reaching the first line that it should debug, Vim breaks the loading and shows something like: Entering Debug mode. Type "cont" to continue.cmd: call MyFunction()> Now you are in the Vim script debugger and have some choices for what to make Vim do. If you are not familiar with debugging techniques, it might be a good idea to read up on this subject before starting to debug your scripts. The following commands are available in the debugger (shortcuts are in parentheses): cont (c): Continue running the scripts / commands as normal (no debugging) until the next breakpoint (more about this later). quit (q): Quit the debugging process without executing the last lines. interrupt (i): Stop the current process like quit, but go back to the debugger. step (s): Execute the next line of code and come back to the debugger when it is finished. If a line calls a function or sources a file, then it will step into the function / file. next (n): Execute the next command and come back to the debugger when it is finished. If used on a line with a function call, it does not go into the function but steps over it. finish (f): Continue executing the script without stopping on breakpoints. Go into debug mode when done.
Read more
  • 0
  • 0
  • 3295
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime
article-image-vim-72-formatting-code
Packt
30 Apr 2010
11 min read
Save for later

Vim 7.2 Formatting Code

Packt
30 Apr 2010
11 min read
Formatting code often depends on many different things. Each programming language has its own syntax, and some languages rely on formatting like indentation more than others. In some cases, the programmer is following style guidelines given by an employer so that code can follow the company-wide style. So, how should Vim know how you want your code to be formatted? The short answer is that it shouldn't! But by being flexible, Vim can let you set up exactly how you want your formatting done. However, the fact is that even though formatting differs, most styles of formatting follow the same basic rules. This means that in reality, you only have to change the things that differ. In most cases, the changes can be handled by changing a range of settings in Vim. Among these, there are a few especially worth mentioning: Formatoptions: This setting holds formatting-specific settings (see :help 'fo') Comments: What are comments and how they should be formatted (see :help 'co') (no)expandtab: Convert tabs to spaces (see :help 'expandtab') Softtabstop: How many spaces a single tab is converted to (see :help 'sts') Tabstop: How many spaces a tab looks like (see :help 'ts') With these options, you can set nearly every aspect of how Vim will indent your code, and whether it should use spaces or tabs for indentation. But this is not enough because you still have to tell Vim if it should actually try to do the indentation for you, or if you want to do it manually. It you want Vim to do the indentation for you, you have the choice between four different ways for Vim to do it. In the following sections, we will look at the options you can set to interact with the way Vim indents code. Autoindent Autoindent is the simplest way of getting Vim to indent your code. It simply stays at the same indentation level as the previous line. So, if the current line is indented with four spaces, then the new line you add by pressing Enter will automatically be indented with four spaces too. It is then up to you as to how and when the indentation level needs to change again. This type of indentation is particularly good for languages where the indentation stays the same for several lines in a row. You get autoindent by using :set, autoindent, or :set ai. Smartindent Smartindent is the next step when you want a smarter indent than autoindent. It still gives you the indentation from the previous line, but you don't have to change the indentation level yourself. Smartindent recognizes the most common structures from the C programming language and uses this as a marker for when to add / remove the indentation levels. As many languages are loosely based on the same syntax as C, this will work for those languages as well. You get smart indent by using any of the following commands: :set smartindent :set si Cindent Cindent is often called clever indent or configurable indent because it is more configurable than the previous two indentation methods. You have access to three different setup options: cinkeys This option contains a comma-separated list of keys that Vim should use to change the indentation level. An example could be: :set cinkeys="0{,0},0#,:", which means that it should reindent whenever it hits a {, a } or a # as the first character on the line, or if you use : as the last character on the line (as used in switch constructs in many languages).The default value for cinkeys is "0{, 0}, 0), :, 0#, !^F, o, O, and e". See :help cinkeys for more information on what else you can set in this option. cinoptions This option contains all the special options you can set specifically for cindent. A large range of options can be set in this comma-separated list. An example could be:set cinoptions=">2,{3,}3", which means that we want Vim to add two extra spaces to the normal indent length, and we want to place { and } three spaces as compared to the previous line. So, if we have a normal indent to be four spaces, then the previous example could result in the code looking like this (dot marks represent a space): if( a == b) ...{ ......print "hello"; ...} The default value for cinoptions is this quite long string: ">s,e0,n0,f0,{0,}0,^0,:s,=s,l0,b0,gs,hs,ps,ts,is,+s,c3,C0,/0,(2s,us,U0,w0,W0,m0,j0,)20,*30" . See :help 'cinoptions' for more information on all the options. cinwords This option contains all the special keywords that will make Vim add indentation on the next line. An example could be: :set cinwords="if,else,do,while,for,switch", which is also the default value for this option. See :help 'cinwords' for more information. Indentexpr Indentexpr is the most flexible indent option to use, but also the most complex. When used, indentexpr evaluates an expression to compute the indent of a line. Hence, you have to write an expression that Vim can evaluate. You can activate this option by simply setting it to a specific expression such as: :set indentexpr=MyIndenter() Here, MyIndenter() is a function that computes the indentation for the lines it is executed on. A very simple example could be a function that emulates the autoindent option: function! MyIndenter() " Find previous line and get its indentation let prev_lineno = s:prevnonblank(v:lnum) let ind = indent( prev_lineno ) return indendfunction Adding just a bit more functionality than this, the complexity increases quite fast. Vim comes with a lot of different indent expressions for many programming languages. These can serve as inspiration if you want to write your own indent expression. You can find them in the indent folder in your VIMHOME. You can read more about how to use indentexpr in :help 'indentexpr' and :help 'indent-expression'. Fast code-block formatting After you have configured your code formatting, you might want to update your code to follow these settings. To do so, you simply have to tell Vim that it should reindent every single line in the file from the first line to the last. This can be done with the following Vim command: 1G=G If we split it up, it simply says: 1G: Go to the first line of the file (alternatively you can use gg) =: Equalize lines; in other words, indent according to formatting configuration G: Go to the last line in the file (tells Vim where to end indenting) You could easily map this command to a key in order to make it easily accessible: :nmap <F11> 1G=G:imap <F11> <ESC>1G=Ga The last a is to get back into the insert mode as this was where we originally were. So, now you can just press the F11key in order to reindent the entire buffer correctly. Note that if you have a programmatic error, for example, missing a semicolon at the end of a line in a C program, the file will not be correctly indented from that point on in the buffer. This can sometimes be useful to identify where a scope is not closed correctly (for example, a { not closed with a } ). Sometimes, you might just want to format smaller blocks of code. In those cases, you typically have two options—use the natural scope blocks in the code, or select a block of code in the visual mode and indent it. The last one is simple. Go into the visual mode with, for example,Shift+v and then press = to reindent the lines. When it comes to using code blocks on the other hand, there are several different ways to do it. In Vim, there are multiple ways to select a block of code. So in order to combine a command that indents a code block, we need to look at the different types and the commands to select them: i{ Inner block, which means everything between { and } excluding the brackets. This can also be selected with i} and iB. a{ A block, which means all the code between { and } including the brackets. This can also be selected with a} and aB. i( Inner parenthesis, meaning everything between ( and ) excluding the parentheses. Can also be selected with i) and ib. a( A parentheses, meaning everything between ( and ) including the parenthesis. Can also be selected with a) and ab. i< Inner < > block, meaning everything between < and > excluding the brackets. Can also be selected with i>. a< A < > block, meaning everything between < and > including the brackets. Can also be selected with a>. i[ Inner [ ] block, meaning everything between [ and ] excluding the square brackets. Can also be selected with i]. a[ A [ ] block, meaning everything between [ and ], including the square brackets. This can also be selected with a]. So, we have defined what Vim sees a block of code as; now, we simply have to tell it what to do with the block. In our case, we want to reindent the code. We already know that = can do this. So, an example of a code block reindentation could look like this: =i{ Let's execute the code block reindentation in the following code (| being the place where the cursor is): if( a == b ) { print |"a equals b"; } This would produce the following code (with default C format settings): if( a == b ) { print |"a equals b"; } If, on the other hand, we choose to use a { as the block we are working on, then the resulting code would look like this: if( a == b ) { print "a equals b"; } As you can see in the last piece of code, the =a{ command corrects the indentation of both the brackets and the print line. In some cases where you work in a code block with multiple levels of code blocks, you might want to reindent the current block and maybe the surrounding one. No worries, Vim has a fast way to do this. If, for instance, you want to reindent the current code block and besides that want to reindent the block that surrounds it, you simply have to execute the following command while the cursor is placed in the innermost block: =2i{ This simply tells Vim that you will equalize / reindent two levels of inner blocks counting from the "active" block and out. You can replace the number 2 with any number of levels of code blocks you want to reindent. Of course, you can also swap the inner block command with any of the other block commands, and that way select exactly what you want to reindent. So, this is really all it takes to get your code to indent according to the setup you have. Auto format pasted code The trend among programmers tells us that we tend to reuse parts of our code, or so-called patterns. This could mean that you have to do a lot of copying and pasting of code. Most users of Vim have experienced what is often referred to as the stair effect when pasting code into a file. This effect occurs when Vim tries to indent the code as it inserts it. This often results in each new line to be indented to another level, and you ending up with a stair: code line 1 code line 2 codeline 3 code line 4 ... The normal workaround for this is to go into the paste-mode in Vim, which is done by using: :set paste After pasting your code, you can now go back to your normal insert mode again: :set nopaste But what if there was another workaround? What if Vim could automatically indent the pasted code such that it is indented according to the rest of the code in the file? Vim can do that for you with a simple paste command. p=`] This command simply combines the normal paste command (p) with a command that indents the previously inserted lines (=`]). It actually relies on the fact that when you paste with p (lowercase), the cursor stays on the first character of the pasted text. This is combined with `], which takes you to the last character of the latest inserted text and gives you a motion across the pasted text from the first line to the last. So, all you have to do now is map this command to a key and then use this key whenever you paste a piece of code into your file. Using external formatting tools Even though experienced Vim users often say that Vim can do everything, this is of course not the truth—but is close. For those things that Vim can't do, it is smart enough to be able to use external tools. In the following sections, we will take a look at some of the most used external tools that can be used for formatting your code, and how to use them.
Read more
  • 0
  • 0
  • 9219

article-image-soa-implementing-message-level-security
Packt
30 Apr 2010
9 min read
Save for later

SOA: Implementing Message-Level Security

Packt
30 Apr 2010
9 min read
One simple way to secure the PO Web service would be to provide legitimate users with a token. This approach assumes that each SOAP message containing a PO document sent by a consumer will contain a username/password pair, which is checked against the database when it arrives at the service provider. While this approach allows the service provider to obtain the information about the consumer to make an authorization decision, a significant disadvantage is that the credentials passed within the message are actually independent of the message payload, and thus, once obtained by a malicious user, may be used to consume the service on behalf of a legitimate user. Of course, you can still use SSL to ensure transport-level security. Often, though, a SOAP message sent from a service consumer to a service provider is processed by an intermediate service or services, running the risk of a malicious user stealing the password travelling with the message. This section discusses how you might work around the above issue by using a hash generated from the value of a particular element or elements of the PO document being transmitted with the message, rather than sending a fixed token. On the client, you might include that hash as part of the SOAP message payload also containing the PO document as the other part. The server in turn is responsible for retrieving the hashed token from the message and checking whether this hash corresponds to the PO that arrived in the same message. Depending on the algorithm used to generate a hash, each new PO document may come with a potentially different hashed token, which makes it harder for a malicious user to illegally access the service. It is important to realize that the above security mechanism does not ensure a private way to transfer the data, since the payload of a SOAP message being transmitted is not encrypted. As for data integrity, you may be fully confident that the message has not been modified in transit only if the hash transmitted within the message was generated upon the entire payload rather than some parts of it. What does this security mechanism do then? Well, it prevents unauthorized users from consuming the service. That is it. Diagrammatically, the security mechanism discussed here might look like the following figure: Here is the PHP code you might use to generate the sha1 hash upon the value of the pono element of a PO XML document: $xmlpo = simplexml_load_string($po); $pono = $xmlpo->purchaseOrder->pono; $hash=sha1($pono); While the previous figure illustrates an example assuming that the hash is generated upon the value of the pono element only, in reality, however, the hash might be built upon any other PO document's element or, even better, upon a combination of elements. The more elements are involved and the more complicated the hashing algorithm is, the harder it will be for a malicious user to guess that algorithm. When choosing elements for hashing, it is always a good idea to consider the element whose value uniquely identifies the document, since it will be most likely used as the primary key when storing the document in the database. So utilizing the pono in this particular example is essential, since an attempt to submit a new PO document with the same pono will fail due to the primary key constraints placed upon the database table holding incoming PO documents. As you can see, with the above approach, you don't even need to create and hold the security accounts in the database, since the security measures are incorporated in a SOAP message itself, thus enabling message-level security. As an alternative to including credentials in the SOAP message body, you might include them in the SOAP message headers. To achieve this with the PHP SOAP extension, you might use the following predefined classes: SoapHeader and SoapVar. Using SOAP message headers to send secure messages, as well as implementing WS-Security authentication, is discussed in detail later, in the Using SOAP Message Headers and Using WS-Security for Message-Level Security sections. In the remainder of this section, you will learn how to implement a secure version of the PO Web service, based on the approach outlined above. The first step is to create the WSDL document for the updated PO Web service. For that, you might create the following document and save it as po_secure.wsdl in the WebServiceswsdl directory: <?xml version="1.0" encoding="utf-8"?> <definitions name ="poServiceSecure" targetNamespace="http://localhost/WebServices/wsdl/po_ secure.wsdl"> <message name="getPlaceOrderInput"> <part name="hash" element="xsd:string"/> <part name="po" element="xsd:string"/> </message> <message name="getPlaceOrderOutput"> <part name="body" element="xsd:string"/> </message> <portType name="poServiceSecurePortType"> <operation name="placeOrder"> <input message="tns:getPlaceOrderInput"/> <output message="tns:getPlaceOrderOutput"/> </operation> </portType> <binding name="poServiceSecureBinding" type="tns:poServiceSecurePortType"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="placeOrder"> <soap:operation soapAction="http://localhost/WebServices/ch4/placeOrder"/> <input> <soap:body use="literal"/> </input> <output> <soap:body use="literal"/> </output> </operation> </binding> <service name="poServiceSecure"> <port name="poServiceSecurePort" binding="tns:poServiceSecureBinding"> <soap:address location="http://localhost/WebServices/ch4/SoapServer_secure.php"/> </port> </service> </definitions> As you can see, this WSDL assumes two message parts in the input message of the placeOrder operation defined here. So, make sure that the binding style defined in the document is rpc. Next, you might want to create the PHP handler class representing the underlying logic of the service discussed here. For that, you might create the following purchaseOrder.php script in the WebServicesch4 directory: <?php //File purchaseOrder_secure.php class purchaseOrder { public function placeOrder($hash, $po) { if(!$conn = oci_connect('xmlusr', 'xmlusr', '//localhost/XE')){ throw new SoapFault("Server","Failed to connect to database"); }; $xmlpo = simplexml_load_string($po); $pono = $xmlpo->pono; $pswd=sha1($pono); $this->checkOrder($hash, $pswd); $sql = "INSERT INTO purchaseOrders VALUES(:po)"; $query = oci_parse($conn, $sql); oci_bind_by_name($query, ':po', $po); if (!oci_execute($query)) { throw new SoapFault("Server","Failed to insert PO"); }; $msg='<rsltMsg>PO inserted!</rsltMsg>'; return $msg; } private function checkOrder($hash, $pswd) { if ($pswd!=$hash) { throw new SoapFault("Server","You're not authorized to consume this service"); } } } ?> In this purchaseOrder class, in the first highlighted code block you load the PO XML document as a SimpleXMLElement object and then extract the value of the pono element. Next, you generate the sha1 hash upon the extracted pono and call the checkOrder private method of purchaseOrder. The code for this method is also highlighted in the listing and is used to check to see whether the hash generated here is equal to the hash that arrived with the message. If there is a mismatch, a SoapFault exception is thrown. The implementation of the SOAP server script to be used in this example is straightforward. It is assumed that you save the following SOAP server script as SoapServer_secure.php in the WebServices/ch4 directory: <?php //File: SoapServer_secure.php require_once "purchaseOrder_secure.php"; $wsdl= "http://localhost/WebServices/wsdl/po_secure.wsdl"; $srv= new SoapServer($wsdl); $srv->setClass("purchaseOrder"); $srv->handle(); ?> Now that you have the service created, all that's left is to build a client script to test the newly created service. For that, you might create the SoapClient_secure.php client script shown below: <?php //File: SoapClient_secure.php $wsdl = "http://localhost/WebServices/wsdl/po_secure.wsdl"; $xmldoc = simplexml_load_file('purchaseOrder.xml'); $pono = $xmldoc->pono; $hash=sha1($pono); $podoc=$xmldoc->asXML(); $client = new SoapClient($wsdl); try { print $result=$client->placeOrder($hash, $podoc); } catch (SoapFault $exp) { print $exp->getMessage(); } ?> Before you can execute this SOAP client script, you need to have a purchaseOrder.xml document containing a PO XML document. So, make sure to copy the purchaseOrder.xml document from the WebServicesch2 to WebServicesch4 directory. In this client script, you extract the value of the pono element from the PO loaded as a SimpleXMLObject from purchaseOrder.xml, and then generate an sha1 hash upon the extracted value. The generated hash and the PO document converted into a string are then passed to the placeOrder SOAP function as arguments. Unlike the above client, the following one uses a more complicated algorithm for generating the hash. In particular, it generates an sha1 hash upon the pono and shipName concatenated together. <?php //File: __SoapClient_secure.php $wsdl = "http://localhost/WebServices/wsdl/po_secure.wsdl"; $xmldoc = simplexml_load_file('purchaseOrder.xml'); $pono = $xmldoc->pono; $shipName = $xmldoc->shipTo->name; $mix=$pono.$shipName; $hash=sha1($mix); $podoc=$xmldoc->asXML(); $client = new SoapClient($wsdl); try { print $result=$client->placeOrder($hash, $podoc); } catch (SoapFault $exp) { print $exp->getMessage(); } ?> Now if you try to run the __SoapClient_secure.php script shown above, you should get the following error message: You're not authorized to consume this service This is because you haven't changed the authentication algorithm on the server side yet. To handle this task, you might modify the purchaseOrder_secure.php script as shown overleaf (the script has been cut down to save space): For the full version, see the __purchaseOrder_secure.php script in the WebServicesch4 directory of the downloadable ZIP archive accompanying this article. However, before you put the script into action, make sure to rename it to purchaseOrder_secure.php. <?php //File __purchaseOrder_secure.php class purchaseOrder { public function placeOrder($hash, $po) { ... $xmlpo = simplexml_load_string($po); $pono = $xmlpo->pono; $shipName = $xmlpo->shipTo->name; $mix=$pono.$shipName; $pswd=sha1($mix); $this->checkOrder($hash, $pswd); ... } ... } ?> Now the mechanism of generating the hash on the client agrees with the one used on the server. So, if you now run the __SoapClient_secure.php script, you should not have a problem.
Read more
  • 0
  • 0
  • 2628

article-image-scripty2-action
Packt
30 Apr 2010
13 min read
Save for later

Scripty2 in Action

Packt
30 Apr 2010
13 min read
(For more resources on Scripty2, see here.) Introduction to Scripty2 Some years ago the web started to see, with great amazement, the born of many JavaScript libraries. Most of them really helped us developers in working with JavasScript code, making life easier, and coding more fun and efective. Some names that usually come to our minds are jQuery, MooTools, dojo, prototype, and surely many, many others. Among these, surely we can remember one called script.aculo.us. It's not only about the cool name, but the great features it brings along with it. Now Thomas Fuchs, the developer behind script.aculo.us, is announcing a newer version. This time called Scripty2, and most interesting of all, this is a full rewrite, every line of code is new, with a big emphasis on making things better, faster and yet easy to use. The three parts in which Scripty2 is divided is: Core Fx Ui We are going to take a quick glance to Fx and Ui, so you can see some of their impressive features. First steps, downloading and placing the necessary code. In order to download the library we need to go to http://scripty2.com/ here we will see an image just like the next one: Clicking on it will result in the file being downloaded, and when the download finishes, we will be able to unzip it. Inside there are three more folders, and the necessary license documents. These folders are: dist → we can find inside this folder the files we will need for the article. doc → the documentation for the library, equal to the online one, but we can check it while offline. However, it's advisable to check the online documentation when possible, as it will be more up to date. src → here we can find the source files for the library, each part of the library being on a separate file. For the Scripty2 library to work, we will also need to included the prototype library, which is also included in the package. But we have another option, that's to include a file called prototype.s2.min.js. This file includes both libraries in it. Summarizing it, if we want to use the Scripty2 libray we have 2 options, to include both libraries separately or simply include prototype.s2.min.js: <script type="text/javascript" src="js/prototype.js"></script> <script type="text/javascript" src="js/s2.js"></script> Note that we are including the prototype-one first, as Scripty2 needs it. The second option, and the one we are going to follow in this article is: <script type="text/javascript" src="js/prototype.s2.min.js"></script> Now, let's take a look at what will be our base structure, first we will have a index.html file, with this code in it: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xml_lang="es-ES" lang="es-ES" ><head><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>Scripty2</title><link rel="stylesheet" href="css/reset.css" type="text/css" /><link rel="stylesheet" href="css/styles.css" type="text/css" /> </head><body> <script type="text/javascript" src="js/prototype.s2.min.js"></script> </body></html> Note that we have our JavaScript file placed at the end of the code, this is usually better for performance. This JavaScript file is located in a folder called js. We have also included two css files, one styles.css, which is empty for now. And the other one is reset.css . I like to use Eric Meyer's css reset which you can find it here:http://meyerweb.com/eric/tools/css/reset/. And that's all we need for now. We are ready to go, we will start with the UI part. Scripty2 UI The Scripty2 includes some very interesting UI controls, like accordion, tabs, autocompleter and many others. I think we could start with the accordion one, as it will make a nice example. Accordion For this we will need to add some code to our index.html file, a good start would be something like this: <body> <div id="tabs_panel"> <ul> <li><a href="#tab1">Sample tab</a></li> <li><a href="#tab2">Another tab</a></li> <li><a href="#tab3">And another one</a></li> </ul> <div id="tab1">1.- This will be the content for the first tab.</div> <div id="tab2">2.- And here we can find the content for the second one.</div> <div id="tab3">3.- Of course we are adding some content to the third one.</div></div> What have we done here? Just three things: First we have created a tabs_panel div, inside which we will place the necessary code for tabs. It will be our container. Next we have placed three div elements, with a link element inside each one, targeting a div. Inside each link, we find the title for the tab. Finally we have placed the final divs, with the ids corresponding to these ones that where being targeted by the previous links. It will be in these divs that we will place the content for each tab. Once we have this code in place we need something more to do the work, as this alone won't do anything. We need to make the necessary Scripty2 function call: ... <div id="tab3">3.- Of course we are adding some content to the third one.</div> </div> <script type="text/javascript" src="./js/prototype.s2.min.js"></script><script type="text/javascript"> new S2.UI.Tabs('tabs_panel');</script> Easy, isn't it? We just need to add this call new S2.UI.Tabs('tabs_panel'); which targets our previously created div. Would this be enough? Let's take a look: It seems nothing has happened, but that's far from true; if we check our page using Firebug, we will see something like the next image: Want to learn more about Firebug? Check this Packt article: http://www.packtpub.com/article/installation-and-getting-started-with-firebug. As we can see in the image, a whole bunch of css classes have been added to our quite simple html code. These classes are responsible for the tabs to work, does that mean that we have to create all of them? Well, not really. Luckily for us, we can use jQuery UI themes for this. Yes, that's it, just go to this url: http://jqueryui.com/themeroller/ And download your favourite one, from the gallery panel: For example, I'm going to download the Hot sneaks one: Once downloaded, we will be able to find the styles we need, inside the packaged file. If we unzip the file we will see these folders: css development-bundle js index.html Opening the css folder we will see a folder called hot-sneaks, or the name of the theme you have downloaded. We will copy the entire folder into our own css folder. Thus we will have this structure: css hot-sneaks reset.css styles.css Inside the hot-sneaks folder there's a file called jquery-ui-1.8.custom.css , we need to link this file in our index.html one, we will add these modifications: … <title>Scripty2</title> <link rel="stylesheet" href="css/reset.css" type="text/css" /> <link rel="stylesheet" href="css/hot-sneaks/jquery-ui-1.8.custom.css" type="text/css" /> <link rel="stylesheet" href="css/styles.css" type="text/css" /> ... But before taking a look at the result of these changes, we still need to do some modifications, this time in our own styles.css file: body{ padding: 10px; }#tabs_panel{ width:350px; font-size: 12px;} And we are done! Our site will look mostly like this: In the image, we can see the three possible states of the tabs: Normal tab Active tab Hover tab It was easy to achieve, isn't it? Next example will be a text autocompleter, stay with us! Text Autocompleter In this example, we are going to use another of the Scripty2 nice feature, this time to build a text autocompleter. This can be used to enhance site search, and it's pretty easy to achieve, thanks to Scripty2. First we need to add the necessary markup in our index.html file: … <div id="tab3">3.- Of course we are adding some content to the third one.</div> </div> <br/><br/> <div id="text_autocompleter"> <input type="text" name="demo" /> </div>... Not much added here, just another container div, and an input, so we can write in it. We now need our JavasCript code to make this work: new S2.UI.Tabs('tabs_panel'); var favourite = [ 'PHP', 'Ruby', 'Python', '.NET', 'JavaScript', 'CSS', 'HTML', 'Java' ]; new S2.UI.Autocompleter('text_autocompleter', { choices: favourite }); </script> … First what we need to do is to create an array of possible values, and then we call the Autocompleter method, with two parameters, first the div we are targetting, and then the array of values. Also we are going to modify our styles.css file, just to add some styling to our text_autocompleter div: ...#tabs_panel, #text_autocompleter{ width:350px; ... If we check our page after these changes, it will be looking this: If we try to enter some text, like a p in the example, we will see how options appear in the box under the input. If we do click on the option, the input box will be filled: Just after we select our desired option the suggestions panel will disappear, as it will do if we click outside the input box. Note that if the theme we are using lacks the ui-helper-hidden class, the suggestions panel won't dissapear. But don't worry, solving this is as easy as adding this class to our styles.css file: .ui-helper-hidden{    visibility: hidden;    } And we are done, now lets see an example about the accordion control. Accordion This is quite similar to the tabs example, quite easy too, first, as always, we are going to add some html markup to our index.html file: <div id="accordion"> <h3><a href="#">Sample tab</a></h3> <div> 1.- This will be the content for the first tab. </div> <h3><a href="#">Another tab</a></h3> <div> 2.- And here we can find the content for the second one. </div> <h3><a href="#">And another one</a></h3> <div> 3.- Of course we are adding some content to the third one. </div> </div> Good, this will be enough for now. We have a container div, where we are placing the necessary elements, each h3 element, with links inside, will be the headings, and the divs will be the contents for each tab. Let's add some styles in our styles.css file: #tabs_panel, #text_autocompleter, #accordion{ width:350px; font-size: 12px;}#accordion h3 a{ padding-left: 30px; } I've placed the necessary changes in bold. Now to the JavaScript code, we will add this in our index.html file: … new S2.UI.Accordion('accordion'); </script> ... The first parameter will be the id of our container div, for now, we don't need anything more. How does all this look like? Just take a look: Good, clicking on each one of the headings will result in closing the current tab and opening the clicked one. But, what if we want to be able to open each clicked tab, but without closing the others? Well, thanks to Scripty2 we can also achieve that. We only need to make some small modifications to the JavaScript call: …new S2.UI.Accordion('accordion', { multiple: true }); </script> … As we see, the second parameter for our accordion function can receive some options, this time we are selecting multiple to true. This way our accordion tabs won't close: In the previous image we can see all our tabs open, but we have some more options, let's see them. The first one will help us define our prefered header selector. As our code is now we are using h3 elements: <h3><a href="#">Sample tab</a></h3> <div> 1.- This will be the content for the first tab.</div>   But what if we wanted to use h1 elements? Well, it won't be very hard, just a tiny add to our JavaScript code: new S2.UI.Accordion('accordion', { multiple: true, headerSelector: 'h1' }); The last option we are going to see is the icons one, by default, this option will use these values: icons: { header:'ui-icon-triangle-1-e',headerSelected: 'ui-icon-triangle-1-s' } Where do these icons come from? Well, these little icons are from the theme we downloaded, and we have plenty of them to use. If you open the theme package, the one we downloaded at the start of the article, and we click on the index.html file, we will be able to see a demo of all styles included in the package. More or less at the bottom we will see a group of tiny icons:   If we hover over these little icons, its name will appear, and that's what we can use to change our options. So in our index.html file, we could change our JavaScript code just like this: new S2.UI.Accordion('accordion', { multiple: true, headerSelector: 'h1', icons: { header: 'ui-icon-circle-plus', headerSelected: 'ui-icon-circle-minus' } }); We define one option for the headers, and other for the selected one, how will this look like:   And with this option we have seen all the three available. With them we can customize our accordion as we wish. Summarizing, we have found that the Scripty2 library includes some very useful UI controllers. We have seen some of them, but there are many others, such as: Buttons → Scripty2 helps us in creating good looking buttons. Not only normal buttons, but also buttons that behave as checkboxes, or even radio buttons. Dialog → There are also some functions in the Scripty2 library that will help us in creating modal dialog boxes, with the contents we want. Slider → If at anytime we are in need of creating a slider, be it for moving the contents of a div, for creating an image gallery or for creating an interesting price filter, it is pretty easy with Scripty2. Progress bar → This one is pretty interesting, as will help us in the task of developing an animated progress bar, very nice! Now we will be taking a look at another interesting part of the library, the FX one.
Read more
  • 0
  • 0
  • 2315

article-image-soa-building-service-providers-and-service-requestors
Packt
30 Apr 2010
6 min read
Save for later

SOA: Building Service Providers and Service Requestors

Packt
30 Apr 2010
6 min read
Depending on the interaction scenario in which a Web service is involved, it can either act as a service provider or a service requestor. In the following sections, you will see how to build a Web service provider and a requestor that will consume the service provider. To start with, let's look at a simple example. Suppose that you need to implement an application based on Web services that performs the following sequence of steps: Receives a purchase order (PO) document in XML format Validates a PO against the appropriate XML schema Stores a PO in the database Sends a response message to the requestor In a real-world situation, to build such an application, you would have to design more than one service and pull these services together into a composite solution. However, for simplicity's sake, the example discussed here uses the only service to handle all of the above tasks. Of course, the above service would be only a part of an entire real-world solution. A service requestor sending a PO document for processing to this service would act as a service provider itself towards another requestor, or would be part of a composite service built, for example, with WS-BPEL. Diagrammatically, the scenario involving the PO Web service that performs the tasks described above might look like the following figure: Here is the detailed explanation of the steps in the figure: Step 1: The service requestor sends a PO XML document wrapped in a SOAP envelope to the service provider. Step 2: The service provider extracts the PO document received from the SOAP envelope and validates the extracted PO against the appropriate XML schema. Step 3: The service provider stores the validated PO document in the database. Step 4: The service provider sends the response message to the service requestor, informing it if the operations being performed have completed successfully or not. To build the PO Web service depicted in the previous figure, you need to accomplish the following five general steps: Set up a database to store incoming PO documents Develop a PHP handler class implementing the PO Web service logic Design an XML schema to validate incoming PO documents Design a WSDL document describing the PO Web service to its requestors Build a SOAP server to handle incoming messages carrying POs The following sections take you through each of the above steps. First, you will see how to create a simple PO Web service that actually performs no validation. Then, you will learn how the XML Schema feature can be used with WSDL to define types in messages being transmitted, making sure that transmitted data is valid with respect to a specific XML schema. Setting Up the Database B efore we go any further, let's take a moment to set up the database required for this example. This example assumes that you are using Oracle Database Express Edition (XE)—a free edition of Oracle Database, or any other edition of Oracle database. You can download a copy of Oracle Database from the Download page of the Oracle Technology Network (OTN) Website at http://www.oracle.com/technology/software/index.html. For this particular example, Oracle is used because it provides native support for XML, which makes it easier for you to get the job done, allowing you to concentrate on using the PHP SOAP extension while building the application. To keep things simple, this section actually discusses how to create a minimal set of the database objects required only to store incoming PO documents. The Oracle XML Schema is part of the Oracle XML DB, which is a set of Oracle XML features available in any edition of Oracle Database by default. With Oracle database, you have several options when it comes to creating, accessing and manipulating the database objects. You can use both the graphical and command-line tools shipped with Oracle Database. As for Oracle Database XE, you might use the Oracle Database XE graphical user interface, a browser-based tool that allows you to administer the database. However, to create the database objects required for this example, it is assumed that you will make use of Oracle SQL*Plus, a command-line SQL tool, which is installed by default with every Oracle database installation. With SQL*Plus, you interact with the database server by entering appropriate SQL statements at the SQL> prompt. Assuming that you have an Oracle database server installed and running, launch SQL*Plus and then follow these steps: Set up a database account that will be used as a container for the database objects by issuing the following SQL statements: //connect to the database as sysdba to be able to create a new account CONN /as sysdba //create a user identified as xmlusr with the same password CREATE USER xmlusr IDENTIFIED BY xmlusr; //grant privileges required to connect and create resources GRANT connect, resource TO xmlusr; Issue the following SQL statements to create a table that will be used to store PO XML documents: //connect to the database using the newly created account CONN xmlusr/xmlusr; //create a purchaseOrders table to be used for storing POs CREATE TABLE purchaseOrders( doc VARCHAR2(4000)); As you can see, the purchaseOrders table created by the above statement contains only one column, namely doc of VARCHAR2. Using the VARCHAR2 Oracle data type is the simplest option when it comes to storing XML documents in an Oracle database. In fact, Oracle provides much more powerful options for storing XML data in the database. Developing the PHP Handler Class N ow that you have set up the database to store the incoming PO documents, it's time to create the PHP code that will perform just that operation: storing incoming POs into the database. Consider the purchaseOrder PHP class containing the PO Web service underlying logic. It is assumed that you will save this class in the purchaseOrder.php file in the WebServicesch2 directory within the document directory of your Web server, so that it will be available at http://localhost/ WebServices/ch2/purchaseOrder.php. <?php //File purchaseOrder.php class purchaseOrder { function placeOrder($po) { if(!$conn = oci_connect('xmlusr', 'xmlusr', '//localhost/xe')){ throw new SoapFault("Server","Failed to connect to database"); }; $sql = "INSERT INTO purchaseOrders VALUES(:po)"; $query = oci_parse($conn, $sql); oci_bind_by_name($query, ':po', $po); if (!oci_execute($query)) { throw new SoapFault("Server","Failed to insert PO"); }; $msg='<rsltMsg>PO inserted!</rsltMsg>'; return $msg; } }?> Looking through the code, you may notice that the purchaseOrder class actually contains the only method, namely placeOrder. As its name implies, the placeOrder method is responsible for placing an incoming PO document. What this method actually does is take a PO XML document as the parameter and then store it in the purchaseOrders table created in the preceding section. Upon failure to connect to the database or execute the INSERT statement, the placeOrder method stops execution and throws a SOAP exception. Another important point to note here is that the placeOrder method doesn't contain any code required to validate an incoming PO document. For simplicity, this example assumes no validation for the moment.
Read more
  • 0
  • 0
  • 4111
article-image-blender-249-scripting-shape-keys-ipos-and-poses
Packt
29 Apr 2010
6 min read
Save for later

Blender 2.49 Scripting: Shape Keys, IPOs, and Poses

Packt
29 Apr 2010
6 min read
A touchy subject—defining an IPO from scratch Many paths of motion of objects are hard to model by hand, for example, when we want the object to follow a precise mathematical curve or if we want to coordinate the movement of multiple objects in a way that is not easily accomplished by copying IPOs or defining IPO drivers. Imagine the following scenario: we want to interchange the position of some objects over the duration of some time in a fluid way without those objects passing through each other in the middle and without even touching each other. This would be doable by manually setting keys perhaps, but also fairly cumbersome, especially if we would want to repeat this for several sets of objects. The script that we will devise takes care of all of those details and can be applied to any two objects. Code outline: orbit.py The orbit.py script that we will design will take the following steps: Determine the halfway point between the selected objects. Determine the extent of the selected objects. Define IPO for object one. Define IPO for object two. Determining the halfway point between the selected objects is easy enough: we will just take the average location of both objects. Determining the extent of the selected objects is a little bit more challenging though. An object may have an irregular shape and determining the shortest distance for any rotation of the objects along the path that the object will be taking is difficult to calculate. Fortunately, we can make a reasonable approximation, as each object has an associated bounding box. This bounding box is a rectangular box that just encapsulates all of the points of an object. If we take half the body diagonal as the extent of an object, then it is easy to see that this distance may be an exaggeration of how close we can get to another object without touching, depending on the exact form of the object. But it will ensure that we never get too close. This bounding box is readily available from an object's getBoundBox() method as a list of eight vectors, each representing one of the corners of the bounding box. The concept is illustrated in the following figure where the bounding boxes of two spheres are shown: The length of the body diagonal of a bounding box can be calculated by determining both the maximum and minimum values for each x, y, and z coordinate. The components of the vector representing this body diagonal are the differences between these maximums and minimums. The length of the diagonal is subsequently obtained by taking the square root of the sum of squares of the x, y, and z components. The function diagonal() is a rather terse implementation as it uses many built-in functions of Python. It takes a list of vectors as an argument and then iterates over each component (highlighted. x, y, and z components of a Blender Vector may be accessed as 0, 1, and 2 respectively): def diagonal(bb): maxco=[] minco=[] for i in range(3): maxco.append(max(b[i] for b in bb)) minco.append(min(b[i] for b in bb)) return sqrt(sum((a-b)**2 for a,b in zip(maxco,minco))) It determines the extremes for each component by using the built-in max() and min() functions. Finally, it returns the length by pairing each minimum and maximum by using the zip() function. The next step is to verify that we have exactly two objects selected and inform the user if this isn't the case by drawing a pop up (highlighted in the next code snippet). If we do have two objects selected, we retrieve their locations and bounding boxes. Then we calculate the maximum distance w each object has to veer from its path to be half the minimum distance between them, which is equal to a quarter of the sum of the lengths of the body diagonals of those objects: obs=Blender.Scene.GetCurrent().objects.selectedif len(obs)!=2: Draw.PupMenu('Please select 2 objects%t|Ok')else: loc0 = obs[0].getLocation() loc1 = obs[1].getLocation() bb0 = obs[0].getBoundBox() bb1 = obs[1].getBoundBox() w = (diagonal(bb0)+diagonal(bb1))/4.0 Before we can calculate the trajectories of both objects, we first create two new and empty Object IPOs: ipo0 = Ipo.New('Object','ObjectIpo0')ipo1 = Ipo.New('Object','ObjectIpo1') We arbitrarily choose the start and end frames of our swapping operation to be 1 and 30 respectively, but the script could easily be adapted to prompt the user for these values. We iterate over each separate IPO curve for the Location IPO and create the first point (or key frame) and thereby the actual curve by assigning a tuple (framenumber, value) to the curve (highlighted lines of the next code). Subsequent points may be added to these curves by indexing them by frame number when assigning a value, as is done for frame 30 in the following code: for i,icu in enumerate((Ipo.OB_LOCX,Ipo.OB_LOCY,Ipo.OB_LOCZ)): ipo0[icu]=(1,loc0[i]) ipo0[icu][30]=loc1[i] ipo1[icu]=(1,loc1[i]) ipo1[icu][30]=loc0[i] ipo0[icu].interpolation = IpoCurve.InterpTypes.BEZIER ipo1[icu].interpolation = IpoCurve.InterpTypes.BEZIER Note that the location of the first object keyframed at frame 1 is its current location and the location keyframed at frame 30 is the location of the second object. For the other object this is just the other way around. We set the interpolation modes of these curves to "Bezier" to get a smooth motion. We now have two IPO curves that do interchange the location of the two objects, but as calculated they will move right through each other. Our next step therefore is to add a key at frame 15 with an adjusted z-component. Earlier, we calculated w to hold half the distance needed to keep out of each other's way. Here we add this distance to the z-component of the halfway point of the first object and subtract it for the other: mid_z = (loc0[2]+loc1[2])/2.0ipo0[Ipo.OB_LOCZ][15] = mid_z + wipo1[Ipo.OB_LOCZ][15] = mid_z - w Finally, we add the new IPOs to our objects: obs[0].setIpo(ipo0)obs[1].setIpo(ipo1) The full code is available as swap2.py in the file orbit.blend (download full code from here). The resulting paths of the two objects are sketched in the next screenshot:
Read more
  • 0
  • 0
  • 3834

article-image-setting-msmq-your-mobile-and-writing-msmq-application-net-compact-framework-35
Packt
29 Apr 2010
3 min read
Save for later

Setting up MSMQ on your Mobile and Writing MSMQ Application with .NET Compact Framework 3.5

Packt
29 Apr 2010
3 min read
Let's get started. Setting up Microsoft Messaging Queue Service (MSMQ) on your mobile device MSMQ is not installed by default on the Windows Mobile platform. This section will guide you on how to install MSMQ on your mobile device or device emulator. You will first need to download the Redistributable Server Components for Windows Mobile 5.0 package (which can also be used for Windows Mobile 6.0) from this location: href="http://www.microsoft.com/downloads/details.aspx?FamilyID=cdfd2bb2-fa13-4062-b8d1-4406ccddb5fd&displaylang=en After downloading and unzipping this file, you will have access to the MSMQ.arm.cab file in the following folder: Optional Windows Mobile 5.0 Server Componentsmsmq Copy this file via ActiveSync to your mobile device and run it on the device. This package contains two applications (and a bunch of other DLL components) that you will be using frequently on the device: msmqadm.exe:This is the command line tool that allows you to start and stop the MSMQ service on the mobile device and also configure MSMQ settings. It can also be invoked programmatically from code. visadm.exe: This tool does the same thing as above, but provides a visual interface. These two files will be unpacked into the Windows folder of your mobile device. The following DLL files will also be unpacked into the Windows folder: msmqd.dll msmqrt.dll Verify that these files exist. The next thing you need to do is to change the name of your device (if you haven't done so earlier). In most cases, you are probably using the Windows Mobile Emulator, which comes with an unassigned device name by default. To change your device name, navigate to Settings | System | About on your mobile device. You can change the device name in the Device ID tab. At this point, you have the files for MSMQ unpacked, but it isn't exactly installed yet. To do this, you must invoke either msmqadm.exe or visadm.exe. Launch the following application: Windowsvisadm.exe A pop-up window will appear. This window contains a text box and a Run button that allows you to type in the desired command and to execute it. The first command you need to issue is the register install command. Type in the command and click the Run button. No message will be displayed in the window. This command will install MSMQ (as a device driver) on your device. Run the following commands in the given order next (one after the other): MSMQ Command Name Purpose register You will need to run the register command one more time (without the install keyword) to create the MSMQ configuration keys in the registry. enable binary This command enables the proprietary MSMQ binary protocol to send messages to remote queues. enable srmp This command enables SRMP (SOAP Reliable Messaging Protocol), for sending messages to remote queues over HTTP. start This command starts the MSMQ service   Verify that the MSMQ service has been installed successfully by clicking on the Shortcuts button and then clicking the Verify button in the ensuing pop-up window. You will be presented with a pop-up dialog as shown in the following screenshot: MSMQ log information If you scroll down in this same window above, you will find the Base Dir path, which contains the MSMQ auto-generated log file. This log file, named MQLOGFILE by default, contains useful MSMQ related information and error messages. After you've done the preceding steps, you will need to do a soft-reset of your device. The MSMQ service will automatically start upon boot up.
Read more
  • 0
  • 0
  • 3126

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
article-image-service-oriented-jbi-invoking-external-web-services-servicemix
Packt
29 Apr 2010
4 min read
Save for later

Service Oriented JBI: Invoking External Web Services from ServiceMix

Packt
29 Apr 2010
4 min read
You can use XFire to create stub classes based on your WSDL exposed by your external web service. Now you can inject the stub into your JSR181 SU. The stub will be used by the proxy to generate the exchange with the HTTP provider (which should be referenced as the "service"). Using JBI proxy now, it is possible to invoke web services in the RPC style from within the JBI bus. For this we leverage the stub classes generated out from the web service WSDL using Axis. Web Service Code Listing We are interested in proxy setup to access a remote web service, hence we will not discuss the details of the web service deployment in this section. Instead, we will just browse through the important web service interfaces and the associated WSDL and then move on to binding the proxy. The web service implements the IHelloWeb remote interface which in turn extends the IHello business interface. They are listed here as follows: IHello.java: IHello is a simple BI, having a single business method hello. public interface IHello{ String hello(String param);} IHelloWeb.java: In order to deploy a web service, we need an interface complying with the Java RMI semantics, and IHelloWeb will serve this purpose. public interface IHelloWeb extends IHello, java.rmi.Remote {} HelloWebService.wsdl: The main sections in the web service WSDL is shown as follows: <?xml version="1.0" encoding="UTF-8"?><wsdl:definitions targetNamespace="http://AxisEndToEnd. axis.apache.binildas.com" ...> <wsdl:types ... /> <wsdl:message ... /> <wsdl:portType name="IHelloWeb"> </wsdl:portType> <wsdl:binding name="HelloWebServiceSoapBinding" type="impl:IHelloWeb"> </wsdl:binding> <wsdl:service name="IHelloWebService"> <wsdl:port binding="impl:HelloWebServiceSoapBinding" name="HelloWebService"> <wsdlsoap:address location="http://localhost:8080/AxisEndToEnd/services/ HelloWebService"/> </wsdl:port> </wsdl:service></wsdl:definitions> This is enough about the web service and we will move on to the next step. Axis Generated Client Stubs We use org.apache.axis.wsdl.WSDL2Java class in the wsdl2java task to generate client-side binding classes and stubs. The main classes are available in the folder ch13JbiProxy 3_AccessExternalWebService 1_wsgensrc and they are as follows: HelloWebService.java HelloWebServiceSoapBindingStub.java IHelloWeb.java IHelloWebService.java IHelloWebServiceLocator.java All the above artifacts are Axis generated client-side stubs, hence we will not look into the details of them here. Instead, let us look into the structural relationship between the various developer created and Axis generated artifacts shown in the following figure: Referring to the above diagram, let us understand the relevant artifacts. Here our aim is to generate a JBI proxy for an externally bound web service. We are doing this using the following classes: ITarget.java: This interface is synonymous to the BI IHello, having a single business method hello. We want to auto-route request-response through the JBI proxy. In order to facilitate this we have retained the method signature in the interfaces the same. public interface ITarget{ String hello(String input);} TargetService.java: In TargetService, we auto-wire the web service stub. So, the helloWeb instance field in TargetService will hold a reference to the stub to the web service. When the hello method is invoked in TargetService, the call is delegated to the stub which will invoke the remote web service. public class TargetService implements ITarget{ private com.binildas.apache.axis.AxisEndToEnd. IHelloWeb helloWeb; public TargetService(){} public TargetService(com.binildas.apache.axis. AxisEndToEnd.IHelloWeb helloWeb) { this.helloWeb = helloWeb; } public String hello(String input) { System.out.println("TargetService.echo : String. this = " + this); try { return helloWeb.hello(input); } catch(Exception exception) { exception.printStackTrace(); return exception.getMessage(); } }} IHelloProxy.java: We now need to wire the JBI proxy to the web services stub. IHelloProxy is an interface defined for this purpose and hence is having the same single business method, hello. public interface IHelloProxy{ public String hello(String input);} IHelloProxyService.java: HelloProxyService is a wrapper or adapter for the JBI proxy. In other words, the helloProxy instance field in HelloProxyService will refer to the JBI proxy. public class HelloProxyService implements IHelloProxy{ private IHelloProxy helloProxy; public void setHelloProxy(IHelloProxy helloProxy) { this.helloProxy = helloProxy; } public String hello(String input) { System.out.println("HelloProxyService.hello. this = " + this); return helloProxy.hello(input); }} The bean wiring discussed in this section is done using Spring and is shown in the next section.
Read more
  • 0
  • 0
  • 1429

article-image-walkthrough-tools-within-sketchup-71
Packt
28 Apr 2010
8 min read
Save for later

Walkthrough Tools within SketchUp 7.1

Packt
28 Apr 2010
8 min read
The same principles for stills and animation Creating moving images, or movies for architectural visualization, takes a slightly different but related mindset to still images (stills). That's because an animated sequence shows off more of the scene than in a still. For example, you might see the back of a building which you wouldn't have bothered modeling for a still. Now you have to model it. Here's a recap If you can't see it, it isn't there (don't model it) If it's in the background, make it low poly or a 2D cutout Use interesting and varied camera angles But this time, all this has to be kept in mind for the duration of a 30-second, 5-minute, or even feature length presentation made up of many views of the model. This can quickly become an overwhelming premise. So, we need to do it like all good movie producers do it. And guess what? You already know what that is, and practice it just about every day, because we're simply talking about breaking it down into bite sized chunks. Rome wasn't built in a day Some architect didn't sit down one day and start sketching Rome, starting with the Coliseum and working outwards until he'd finished the whole city. It took ages (literally) and involved many different designers and designs. So, Rome was made up of component parts, and each component part was made up of individual bricks. Just like you do every day with other design projects, home DIY, life goals, or even a holiday itinerary, you're going to break down your animation scene by scene and shot by shot. Making a start: Sketch it out Even if you already have a fully detailed model that you can quite happily view from any angle, you need to start by planning what you want to see in your animation. Actually, that's a complete lie. Why would the client want to see what you want to see? You're interested in buildings for pity's sake! So, we must start by filling the boots of the client or "audience" and from now on only think in terms of their wishes. If there wes a switch to turn them on, what would it be? Time for action – write out your itinerary If you were to visit the quaint English village of Bourton-on-the-Water, what would be the absolute "must sees" of your trip? If you have travelled for 17 days to get there, you knew you could never go back there again, and you were the last one to go with a film camera before it was leveled by hungry bulldozers? So, write out your itinerary. There's a method of doing this that's completely easy and foolproof. You can do it when you're on the train or eating your cornflakes: Take an A3 sheet of paper. Start at the centre of the page and write down a feature of the building you're "selling" to your audience. Rotate the page randomly and write another somewhere in a blank space. Do it again and again Go completely crazy and write down whatever pops into your head (such as "dishwasher", "great drainage", or "south facing"). When you've filled the page, collect them all up in a list. Put three columns down the right-hand side, labeled Quality, Desirability, and a blank column. It doesn't matter if you spell desirability wrong. That's the point of the exercise, no wrong answers, don't worry about spelling or getting the best stuff down. Just get the flow going. When you're done, in the Quality column give a rating 1 to 5 for how "nice" this part of this particular development is: Now do a valley fold to hide the first column. In the Desirability column, give a rating 1 to 5 for how desirable such a building feature is to your audience. You need to divorce this from your particular building completely. Rate it purely on how your audience would view this feature on any building. Does anti-vandal paint on a bin store make someone want to buy a property? When you're done, multiply the first and second column and put the total in the third. What just happened? Without knowing it or finding it remotely difficult, you have written the itinerary for your animation. Easy wasn't it? You probably don't think you've achieved much, but you have. By using this method you were forced to be dispassionate about your design or model. You were also forced to separate out what you like (as a building feature lover) and what your audience wants (as the ones wanti ng to be in it!). What you have in the third column is a definitive rating of the impact of each feature on your audience. Go ahead and label it "impact" now. Generating the story board You are now ready to sketch out the storyboard, because you now know what to include in your animation and what to leave out. Take a pink marker and highlight everything with a score of 20-25. This is your prime real-estate. Take an orange marker and highlight scores of 12-16. And take a yellow marker to all the nines. Nines are just about tolerable. What you now have is a color coded scene allocation system. When deciding what to put into your animation, you should get all the pinks in as many times as you can. You should get the oranges in the rest of the time. And you should use the yellows to pad the content out where necessary and give an overall context to the presentation. And guess what? Anything you've not colored will actually detract from the presentation and stop people buying the property. Don't you dare even model them! Dealing with detractions As you've discovered, anything in your list that didn't get colored could easily detract so much from your presentation that someone who would normally be enamored with it is left cold instead. So, these areas should be minimized if possible, but what do you do if they're a central feature and have to be included for context (or honesty)? For example the electricity enclosure, the bin store, or the plant room? Here's a quick list of ways to overcome this problem: Leave non-critical areas blank and un-textured, giving the context but not the detail Cover or mask with entourage Leave unfocussed in the background (with moving images this only possible when using professional level compositing software) Use viewing angles that obscure these features Probably as much of your effort should be spent in minimizing bad features as promoting good ones. You should aim at showing the development in its best light and greatest potential. Time for action – the storyboard Now that you've decided what needs to be included and what needs to be left out, you need to decide how long to allocate to each, and what the camera views should be. Do the following on paper with sketches. Split up your list into scenes, including wide views and close-up views. Decide how long the whole animation should last. Add a couple of seconds for cutting out later. What about transitions? Are you going to travel from one scene to the next, or cut to it? Work out how long to spend on each scene, each transition. Create a rough sketch for the start of each scene. Scan them into your computer. The following steps are shown specific to Windows Movie Maker, but are similar to all basic video editing software (Adobe Premiere Elements, Final Cut Express, iMovie, or similar) In Windows Movie Maker or similar, import each picture. In Import Pictures hold Ctrl to select more than one then click Import. The pictures will open in the Collections area. Drag them one by one into the StoryBoard in the sequence you want Click Show Timeline. Drag the edge of each image out to the correct time-length. Press play on the preview viewer. Keep adding scene sketches and editing the timing until you're happy. Add voice or music to the audio channel if you want to key the scene transitions to that as follows: Click Import Audio or Music. Navigate to the file, then drag into the storyboard as before. Remember to save the project. What just happened? You just storyboarded your whole animation so that you now know exactly where and what you need to go and model. You did this in Movie Maker or something similar, creating place markers so you can easily import your moving clips later. This saves an enormous amount of time in the long run because you will only model, texture, animate, and render what you're going to see, not what'll get left on the cutting room floor. If you already have your SketchUp scene completed, you could take screenshots from that instead of sketching it out. You can use this later, as a template to insert the actual animations into. When you're doing a complex project such as an animation, it's vital to get a second or third pair of eyes onto it early on. Use your rough and ready movie to talk it through with a colleague, tutor, or a "clued up" friend. It's important to do it at this early stage because you haven't invested lots of time and emotion into it yet.
Read more
  • 0
  • 0
  • 8122
Modal Close icon
Modal Close icon