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

How-To Tutorials - Web Development

1802 Articles
article-image-interacting-gnu-octave-operators
Packt
20 Jun 2011
6 min read
Save for later

Interacting with GNU Octave: Operators

Packt
20 Jun 2011
6 min read
GNU Octave Beginner's Guide Become a proficient Octave user by learning this high-level scientific numerical tool from the ground up The reader will benefit from the previous article on GNU Octave Variables. Basic arithmetic Octave offers easy ways to perform different arithmetic operations. This ranges from simple addition and multiplication to very complicated linear algebra. In this section, we will go through the most basic arithmetic operations, such as addition, subtraction, multiplication, and left and right division. In general, we should think of these operations in the framework of linear algebra and not in terms of arithmetic of simple scalars. Addition and subtraction We begin with addition. Time for action – doing addition and subtraction operations I have lost track of the variables! Let us start afresh and clear all variables first: octave:66> clear (Check with whos to see if we cleared everything). Now, we define four variables in a single command line(!) octave:67> a = 2; b=[1 2 3]; c=[1; 2; 3]; A=[1 2 3; 4 5 6]; Note that there is an important difference between the variables b and c; namely, b is a row vector, whereas c is a column vector. Let us jump into it and try to add the different variables. This is done using the + character: octave:68>a+a ans = 4 octave:69>a+b ans = 3 4 5 octave:70>b+b ans = 2 4 6 octave:71>b+c error: operator +: nonconformant arguments (op1 is 1x3, op2 is 3x1) It is often convenient to enter multiple commands on the same line. Try to test the difference in separating the commands with commas and semicolons. What just happened? The output from Command 68 should be clear; we add the scalar a with itself. In Command 69, we see that the + operator simply adds the scalar a to each element in the b row vector. This is named element-wise addition. It also works if we add a scalar to a matrix or a higher dimensional array. Now, if + is applied between two vectors, it will add the elements together element-wise if and only if the two vectors have the same size, that is, they have same number of rows or columns. This is also what we would expect from basic linear algebra. From Command 70 and 71, we see that b+b is valid, but b+c is not, because b is a row vector and c is a column vector—they do not have the same size. In the last case, Octave produces an error message stating the problem. This would also be a problem if we tried to add, say b with A: octave:72>b+A error: operator +: nonconformant arguments (op1 is 1x3, op2 is 2x3) From the above examples, we see that adding a scalar to a vector or a matrix is a special case. It is allowed even though the dimensions do not match! When adding and subtracting vectors and matrices, the sizes must be the same. Not surprisingly, subtraction is done using the - operator. The same rules apply here, for example: octave:73> b-b ans = 0 0 0 is fine, but: octave:74> b-c error: operator -: nonconformant arguments (op1 is 1x3, op2 is 2x3) produces an error. Matrix multiplication The * operator is used for matrix multiplication. Recall from linear algebra that we cannot multiply any two matrices. Furthermore, matrix multiplication is not commutative. For example, consider the two matrices: The matrix product AB is defined, but BA is not. If A is size n x k and B has size k x m, the matrix product AB will be a matrix with size n x m. From this, we know that the number of columns of the "left" matrix must match the number of rows of the "right" matrix. We may think of this as (n x k)(k x m) = n x m. In the example above, the matrix product AB therefore results in a 2 x 3 matrix: Time for action – doing multiplication operations Let us try to perform some of the same operations for multiplication as we did for addition: octave:75> a*a ans = 4 octave:76> a*b ans = 2 4 6 octave:77> b*b error: operator *: nonconformant arguments (op1 is 1x3, op2 is 1x3) octave:78> b*c ans = 14 What just happened? From Command 75, we see that * multiplies two scalar variables just like standard multiplication. In agreement with linear algebra, we can also multiply a scalar by each element in a vector as shown by the output from Command 76. Command 77 produces an error—recall that b is a row vector which Octave also interprets as a 1 x 3 matrix, so we try to perform the matrix multiplication (1 x 3)(1 x 3), which is not valid. In Command 78, on the other hand, we have (1 x 3)(3 x 1) since c is a column vector yielding a matrix with size 1 x 1, that is, a scalar. This is, of course, just the dot product between b and c. Let us try an additional example and perform the matrix multiplication between A and B discussed above. First, we need to instantiate the two matrices, and then we multiply them: octave:79> A=[1 2; 3 4]; B=[1 2 3; 4 5 6]; octave:80> A*B ans = 9 12 15 19 26 33 octave:81> B*A error: operator *: nonconformant arguments (op1 is 2x3, op2 is 2x2) Seems like Octave knows linear algebra! Element-by-element, power, and transpose operations If the sizes of two arrays are the same, Octave provides a convenient way to multiply the elements element-wise. For example, for B: octave:82> B.*B ans = 1 4 9 16 25 36 Notice that the period (full stop) character precedes the multiplication operator. The period character can also be used in connection with other operators. For example: octave:83> B.+B ans = 2 4 6 8 10 12 which is the same as the command B+B. If we wish to raise each element in B to the power 2.1, we use the element-wise power operator.ˆ: octave:84> B.^2.1 ans = 1.0000 4.2871 10.0451 18.3792 29.3655 43.0643 You can perform element-wise power operation on two matrices as well (if they are of the same size, of course): octave:85> B.^B ans = 1 4 27 256 3125 46656 If the power is a real number, you can use ˆ instead of .ˆ; that is, instead of Command 84 above, you can use: octave:84>Bˆ2.1 Transposing a vector or matrix is done via the 'operator. To transpose B, we simply type: octave:86> B' ans = 1 4 2 5 3 6 Strictly, the ' operator is a complex conjugate transpose operator. We can see this in the following examples: octave:87> B = [1 2; 3 4] + I.*eye(2) B = 1 + 1i 2 + 0i 3 + 0i 4 + 1i octave:88> B' ans = 1 - 1i 3 - 0i 2 - 0i 4 - 1i Note that in Command 87, we have used the .* operator to multiply the imaginary unit with all the elements in the diagonal matrix produced by eye(2). Finally, note that the command transpose(B)or the operator .' will transpose the matrix, but not complex conjugate the elements.
Read more
  • 0
  • 0
  • 17820

article-image-ejb-31-controlling-security-programmatically-using-jaas
Packt
17 Jun 2011
5 min read
Save for later

EJB 3.1: Controlling Security Programmatically Using JAAS

Packt
17 Jun 2011
5 min read
  EJB 3.1 Cookbook Build real world EJB solutions with a collection of simple but incredibly effective recipes The reader is advised to refer the initial two recipies from the previous article on the process of handling security using annotations. Getting ready Programmatic security is affected by adding code within methods to determine who the caller is and then allowing certain actions to be performed based on their capabilities. There are two EJBContext interface methods available to support this type of security: getCallerPrincipal and isCallerInRole. The SessionContext object implements the EJBContext interface. The SessionContext's getCallerPrincipal method returns a Principal object which can be used to get the name or other attributes of the user. The isCallerInRole method takes a string representing a role and returns a Boolean value indicating whether the caller of the method is a member of the role or not. The steps for controlling security programmatically involve: Injecting a SessionContext instance Using either of the above two methods to effect security How to do it... To demonstrate these two methods we will modify the SecurityServlet to use the VoucherManager's approve method and then augment the approve method with code using these methods. First modify the SecurityServlet try block to use the following code. We create a voucher as usual and then follow with a call to the submit and approve methods. out.println("<html>"); out.println("<head>"); out.println("<title>Servlet SecurityServlet</title>"); out.println("</head>"); out.println("<body>"); voucherManager.createVoucher("Susan Billings", "SanFrancisco", BigDecimal.valueOf(2150.75)); voucherManager.submit(); boolean voucherApproved = voucherManager.approve(); if(voucherApproved) { out.println("<h3>Voucher was approved</h3>"); } else { out.println("<h3>Voucher was not approved</h3>"); } out.println("<h3>Voucher name: " + voucherManager.getName() + "</h3>"); out.println("</body>"); out.println("</html>"); Next, modify the VoucherManager EJB by injecting a SessionContext object using the @Resource annotation. public class VoucherManager { ... @Resource private SessionContext sessionContext; Let's look at the getCallerPrincipal method first. This method returns a Principal object (java.security.Principal) which has only one method of immediate interest: getName. This method returns the name of the principal. Modify the approve method so it uses the SessionContext object to get the Principal and then determines if the name of the principal is "mary" or not. If it is, then approve the voucher. public boolean approve() { Principal principal = sessionContext.getCallerPrincipal(); System.out.println("Principal: " + principal.getName()); if("mary".equals(principal.getName())) { voucher.setApproved(true); System.out.println("approve method returned true"); return true; } else { System.out.println("approve method returned false"); return false; } } Execute the SecurityApplication using "mary" as the user. The application should approve the voucher with the output as shown in the following screenshot: Execute the application again with a user of "sally". This execution will result in an exception. INFO: Access exception The getCallerPrincipal method simply returns the principal. This frequently results in the need to explicitly include the name of a user in code. The hard coding of user names is not recommended. Checking against each individual user can be time consuming. It is more efficient to check to see if a user is in a role. The isCallerInRole method allows us to determine whether the user is in a particular role or not. It returns a Boolean value indicating whether the user is in the role specified by the method's string argument. Rewrite the approve method to call the isCallerInRole method and pass the string "manager" to it. If the return value returns true, approve the voucher. public boolean approve() { if(sessionContext.isCallerInRole("manager")) { voucher.setApproved(true); System.out.println("approve method returned true"); return true; } else { System.out.println("approve method returned false"); return false; } } Execute the application using both "mary" and "sally". The results of the application should be the same as the previous example where the getCallerPrincipal method was used. How it works... The SessionContext class was used to obtain either a Principal object or to determine whether a user was in a particular role or not. This required the injection of a SessionContext instance and adding code to determine if the user was permitted to perform certain actions. This approach resulted in more code than the declarative approach. However, it provided more flexibility in controlling access to the application. These techniques provided the developer with choices as to how to best meet the needs of the application. There's more... It is possible to take different actions depending on the user's role using the isCallerInRole method. Let's assume we are using programmatic security with multiple roles. @DeclareRoles ({"employee", "manager","auditor"}) We can use a validateAllowance method to accept a travel allowance amount and determine whether it is appropriate based on the role of the user. public boolean validateAllowance(BigDecimal allowance) { if(sessionContext.isCallerInRole("manager")) { if(allowance.compareTo(BigDecimal.valueOf(2500)) <= 0) { return true; } else { return false; } } else if(sessionContext.isCallerInRole("employee")) { if(allowance.compareTo(BigDecimal.valueOf(1500)) <= 0) { return true; } else { return false; } } else if(sessionContext.isCallerInRole("auditor")) { if(allowance.compareTo(BigDecimal.valueOf(1000)) <= 0) { return true; } else { return false; } } else { return false; } } The compareTo method compares two BigDecimal values and returns one of three values: -1 – If the first number is less than the second number 0 – If the first and second numbers are equal 1 – If the first number is greater than the second number The valueOf static method converts a number to a BigDecimal value. The value is then compared to allowance. Summary This article covered programmatic EJB security based upon the Java Authentication and Authorization Service (JAAS) API. Further resources on this subject: EJB 3.1: Introduction to Interceptors [Article] EJB 3.1: Working with Interceptors [Article] Hands-on Tutorial on EJB 3.1 Security [Article] EJB 3 Entities [Article] Developing an EJB 3.0 entity in WebLogic Server [Article] Building an EJB 3.0 Persistence Model with Oracle JDeveloper [Article] NetBeans IDE 7: Building an EJB Application [Article]
Read more
  • 0
  • 0
  • 3223

article-image-interacting-gnu-octave-variables
Packt
17 Jun 2011
8 min read
Save for later

Interacting with GNU Octave: Variables

Packt
17 Jun 2011
8 min read
GNU Octave Beginner's Guide Become a proficient Octave user by learning this high-level scientific numerical tool from the ground up          In the following, we shall see how to instantiate simple variables. By simple variables, we mean scalars, vectors, and matrices. First, a scalar variable with name a is assigned the value 1 by the command: octave:1> a=1 a = 1 That is, you write the variable name, in this case a, and then you assign a value to the variable using the equal sign. Note that in Octave, variables are not instantiated with a type specifier as it is known from C and other lower-level languages. Octave interprets a number as a real number unless you explicitly tell it otherwise. In Octave, a real number is a double-precision, floating-point number,which means that the number is accurate within the first 15 digits. Single precision is accurate within the first 6 digits. You can display the value of a variable simply by typing the variable name: octave:2>a a = 1 Let us move on and instantiate an array of numbers: octave:3 > b = [1 2 3] b = 1 2 3 Octave interprets this as the row vector: rather than a simple one-dimensional array. The elements (or the entries) in a row vector can also be separated by commas, so the command above could have been: octave:3> b = [1, 2, 3] b = 1 2 3 To instantiate a column vector: you can use: octave:4 > c = [1;2;3] c = 1 2 3 Notice how each row is separated by a semicolon. We now move on and instantiate a matrix with two rows and three columns (a 2 x 3 matrix): using the following command: octave:5 > A = [1 2 3; 4 5 6] A = 1 2 3 4 5 6 Notice that I use uppercase letters for matrix variables and lowercase letters for scalars and vectors, but this is, of course, a matter of preference, and Octave has no guidelines in this respect. It is important to note, however, that in Octave there is a difference between upper and lowercase letters. If we had used a lowercase a in Command 5 above, Octave would have overwritten the already existing variable instantiated in Command 1. Whenever you assign a new value to an existing variable, the old value is no longer accessible, so be very careful whenever reassigning new values to variables. Variable names can be composed of characters, underscores, and numbers. A variable name cannot begin with a number. For example, a_1 is accepted as a valid variable name, but 1_a is not. In this article, we shall use the more general term array when referring to a vector or a matrix variable. Accessing and changing array elements To access the second element in the row vector b, we use parenthesis: octave:6 > b(2) ans = 2 That is, the array indices start from 1. This is an abbreviation for "answer" and is a variable in itself with a value, which is 2 in the above example. For the matrix variable A, we use, for example: octave:7> A(2,3) ans = 6 to access the element in the second row and the third column. You can access entire rows and columns by using a colon: octave:8> A(:,2) ans = 2 5 octave:9 > A(1,:) ans = 1 2 3 Now that we know how to access the elements in vectors and matrices, we can change the values of these elements as well. To try to set the element A(2,3)to -10.1: octave:10 > A(2,3) = -10.1 A = 1.0000 2.0000 3.0000 4.0000 5.0000 -10.1000 Since one of the elements in A is now a non-integer number, all elements are shown in floating point format. The number of displayed digits can change depending on the default value, but for Octave's interpreter there is no difference—it always uses double precision for all calculations unless you explicitly tell it not to. You can change the displayed format using format short or format long. The default is format short. It is also possible to change the values of all the elements in an entire row by using the colon operator. For example, to substitute the second row in the matrix A with the vector b (from Command 3 above), we use: octave:11 > A(2,:) = b A = 1 2 3 1 2 3 This substitution is valid because the vector b has the same number of elements as the rows in A. Let us try to mess things up on purpose and replace the second column in A with b: octave:12 > A(:,2) = b error: A(I,J,...) = X: dimension mismatch Here Octave prints an error message telling us that the dimensions do not match because we wanted to substitute three numbers into an array with just two elements. Furthermore, b is a row vector, and we cannot replace a column with a row. Always read the error messages that Octave prints out. Usually they are very helpful. There is an exception to the dimension mismatch shown above. You can always replace elements, entire rows, and columns with a scalar like this: octave:13> A(:,2) = 42 A = 1 42 3 1 42 3 More examples It is possible to delete elements, entire rows, and columns, extend existing arrays, and much more. Time for action – manipulating arrays To delete the second column in A, we use: octave:14> A(:,2) = [] A = 1 3 1 3 We can extend an existing array, for example: octave:15 > b = [b 4 5] b = 1 2 3 4 5 Finally, try the following commands: octave:16> d = [2 4 6 8 10 12 14 16 18 20] d = 2 4 6 8 10 12 14 16 18 20 octave:17> d(1:2:9) ans = 2 6 10 14 18 octave:18> d(3:3:12) = -1 d = 2 4 -1 8 10 -1 14 16 -1 20 0 -1 What just happened? In Command 14, Octave interprets [] as an empty column vector and column 2 in A is then deleted in the command. Instead of deleting a column, we could have deleted a row, for example as an empty column vector and column 2 in A is then deleted in the command. octave:14> A(2,:)=[] On the right-hand side of the equal sign in Command 15, we have constructed a new vector given by [b 4 5], that is, if we write out b, we get [1 2 3 4 5] since b=[1 2 3]. Because of the equal sign, we assign the variable b to this vector and delete the existing value of b. Of course, we cannot extend b using b=[b; 4; 5] since this attempts to augment a column vector onto a row vector. Octave first evaluates the right-hand side of the equal sign and then assigns that result to the variable on the left-hand side. The right-hand side is named an expression. In Command 16, we instantiated a row vector d, and in Command 17, we accessed the elements with indices 1,3,5,7, and 9, that is, every second element starting from 1. Command 18 could have made you a bit concerned! d is a row vector with 10 elements, but the command instructs Octave to enter the value -1 into elements 3, 6, 9 and 12, that is, into an element that does not exist. In such cases, Octave automatically extends the vector (or array in general) and sets the value of the added elements to zero unless you instruct it to set a specific value. In Command 18, we only instructed Octave to set element 12 to -1, and the value of element 11 will therefore be given the default value 0 as seen from the output. In low-level programming languages, accessing non-existing or non-allocated array elements may result in a program crash the first time it is running2. This will be the best case scenario. In a worse scenario, the program will work for years, but then crash all of a sudden, which is rather unfortunate if it controls a nuclear power plant or a space shuttle. As you can see, Octave is designed to work in a vectorized manner. It is therefore often referred to as a vectorized programming language. Complex variables Octave also supports calculations with complex numbers. As you may recall, a complex number can be written as z = a + bi, where a is the real part, b is the imaginary part, and i is the imaginary unit defined from i2 = –49491. To instantiate a complex variable, say z = 1 + 2i, you can type: octave:19> z = 1 + 2I z = 1 + 2i When Octave starts, the variables i, j, I, and J are all imaginary units, so you can use either one of them. I prefer using I for the imaginary unit, since i and j are often used as indices and J is not usually used to symbolize i. To retrieve the real and imaginary parts of a complex number, you use: octave:20> real(z) ans = 1 octave:21>imag(z) ans = 2 You can also instantiate complex vectors and matrices, for example: octave:22> Z = [1 -2.3I; 4I 5+6.7I] Z = 1.0000 + 0.0000i 0.0000 - 2.3000i 0.0000 + 4.0000i 5.0000 + 6.7000i Be careful! If an array element has non-zero real and imaginary parts, do not leave any blanks (space characters) between the two parts. For example, had we used Z=[1 -2.3I; 4I 5 + 6.7I] in Command 22, the last element would be interpreted as two separate elements (5 and 6.7i). This would lead to dimension mismatch. The elements in complex arrays can be accessed in the same way as we have done for arrays composed of real numbers. You can use real(Z) and imag(Z) to print the real and imaginary parts of the complex array Z. (Try it out!)
Read more
  • 0
  • 0
  • 6095

article-image-overview-joomla-virtuemart
Packt
15 Jun 2011
12 min read
Save for later

An overview of Joomla! and VirtueMart

Packt
15 Jun 2011
12 min read
Navigating through the Joomla! and VirtueMart directories You should have a Joomla! and VirtueMart e-commerce site installed somewhere. If not, you should now install one first before reading on. From this point onward, we will assume that you can access a Joomla! VirtueMart site and can freely browse its content, either on your local computer using the file manager of your operating system or in a web server somewhere using an FTP client program. To work on the exercises, you should also be able to edit each of the files. OK. Let's start our study by navigating through the Joomla! directories. If you look at the root of your Joomla! site, you will be amazed how large the Joomla! project is. There are totally close to 5,000 files under some 350 directories! It would be difficult to find your way through this vast structure of files if there are no hints at all. Fortunately, Joomla! has a very good directory structure and will be easy to follow once you know its basic organization. Knowing your way through this vast structure is very important when embarking on any VirtueMart customization project of considerable size. The good news is that usually we only need to know a very small fraction of those 350 directories and 5,000 files. In the Joomla! root, the most important directories we need to know are the administrator, components, modules, and plugins directories (This does not mean that the other directories are not important. We highlight these few directories just because they are the directories we will reference from time-to-time) You will probably recognize that the last three of these shortlisted directories correspond to the three major extension types of Joomla! So within these directories, we will expect to see a series of subdirectories, each of which corresponds to an extension installed in the Joomla! framework. This is exactly the case, except for the plugins where the directories are arranged in terms of their type instead of their source. Let's take a closer look at one of the most important components that comes with Joomla!. Navigate to the components directory and open the subdirectory com_content. The com_content component is the one that manages articles we created in Joomla!. You have probably been using a lot of this component. Within this directory, you will find a number of files and a few subdirectories. We notice there is a file named controller.php and two subdirectories named models and views. We will have more to say on these in a moment. Let's move back to the root directory and take a look at the last important directory mentioned above. This administrator directory mimics the root directory in many respects. We see that most of the subdirectories we found in the root have a corresponding subdirectory within the administrator directory. For example, we find subdirectories named components and modules within the administrator as well. As we know, there are two main sections of a Joomla! website, also known as the frontend and the backend. The root directory and administrator directory are respectively the location where the frontend and backend files are located. While this dividing line is not rigid, we can use this as a guide when we want to locate a frontend or backend file. Since both the root and the administrator directories contain a subdirectory called components, to avoid ambiguity, we will refer to them as the root components and administrator components directory, respectively. Now, let's work our way a little bit down the directory tree to see how VirtueMart fits into this framework. Within the root components directory, you will see a subdirectory called com_virtuemart. Yes, this is the location where you can find all the files used by VirtueMart for the frontend. Under the com_virtuemart directory, among some other files and subdirectories, you will notice a themes subdirectory. You will find each of the VirtueMart themes you have installed there. The themes directory is the major work area. From now on, we will refer to the com_virtuemart directory under the root components directory as the root VirtueMart directory or the frontend VirtueMart directory. Within the administrator components directory, there is also a subdirectory called com_virtuemart where the backend VirtueMart files are located. Under this main directory, there are four subdirectories named as classes, html, languages, and sql. Obviously, these directories will contain, respectively, the class files, HTML files, language files, and SQL (also known as database) files. Actually, the classes and html directories have a deeper meaning than their names suggest, as we shall see in a moment. Structure of the Joomla! URL path Before leaving our high-level exploration of the Joomla! tree structure, let's digress a little bit to study how a Joomla! URL is built up. While the Joomla! directory structure is so complicated, the URL used to access the site is much simpler. Most of the time, the URL just starts with index.php?. (If you have a Search Engine Friendly or SEF system enabled, you should turn it off during the development and testing of your customization, or at least turn it off mentally while we are talking about the URL. You can turn off SEF in the Joomla! Configuration page.) For example, if we want to access the VirtueMart (frontend) home page, we can use the following URL: http://your_joomla_live_site/index.php?option=com_virtuemart Similarly, the URL http://your_joomla_live_site/administrator/index.php?option=com_virtuemart will bring up the VirtueMart backend control panel, if you're already logged in. All other Joomla! URL, in fact, work in the same way, although many times you see some additional parameters as well. (Don't forget to replace your_joomla_live_site in the above URL with your domain name and the Joomla! root directory, in case the site is not installed in the root.) Actually, the index.php script is the main entry into your Joomla! site. All major requests to the frontend start from here (major requests only since there are some other entry points as well, but they don't bother us at this point). Similarly, all major requests to the backend start from the file administrator/index.php. Restricting the entry point to the site makes it very easy to control authorized and unauthorized accesses. For example, if we want to put the site offline, we can simply change a configuration in Joomla! and all components will be offline as well. We don't need to change each page or even each component one-by-one. Understanding the structure of the Joomla! URL is pretty useful during the development and debugging process. Sometimes we may need to work on a partly live site in which the Joomla! site is already working, but the VirtueMart shop is still under construction. In such cases, it is common to unpublish the menu items for the shop so that the shop is still hidden from the public. The fact that the menu item is hidden actually means the shop is less accessible but not inaccessible. If we want to test the VirtueMart shop, we can still type the URL on the browser by ourselves. Using the URL http://your_joomla_live_site/index.php?option=com_virtuemart we can bring up the VirtueMart home page. We will learn some more tricks in testing individual shop pages along the way of our study of VirtueMart themes and templates. One simple application of what we learnt about the URL can be used when customizing Joomla!. When working with VirtueMart projects, we will need to go to the VirtueMart backend from time-to-time to modify the VirtueMart settings. As we all know, after logging in, what we have on the browser window is the control panel page. We will need to point to the components/virtuemart menu before we can open the VirtueMart backend home. This is not a complicated task, but will be very tedious if repeated every time we log back into the site. Can we make Joomla! smarter, to open the VirtueMart home by default when we log on? Yes, we can. The trick actually relates to what we talked about so far. If you want to customize Joomla! to open the VirtueMart backend by default, you can stay with me for the following warm-up exercise. I understand some of you may not want to change the default login page. Exercise 1.1: Making the Joomla! backend default to VirtueMart Open your favorite text editor. Navigate to the Joomla! site root. Open the file administrator/includes/helper.php. At around line 44 (the actual line may vary from version-to-version), change the code $option = 'com_cpanel'; to $option = 'com_virtuemart'; Save the file. Open your browser and log in to your Joomla! site. Alas, you should see the VirtueMart control panel instead of the Joomla! control panel. This simple exercise demonstrated that sometimes a useful change does not need complex coding. What we need is a little knowledge of how things work. I bet you probably understand what we have done above without explanation. After login, Joomla! will automatically go to the default component, hardcoded in the file helper.php. For standard Joomla!, this will be the com_cpanel component. In Exercise 1.1, we have changed this default backend component from com_cpanel to com_virtuemart. Instead of VirtueMart, we can certainly change the default to other components such as community builder or MOSET. Joomla! 1.5 presentation framework Since VirtueMart is a Joomla! component, it cannot exist outside Joomla!. So before diving into the detail of the VirtueMart engine, it pays to take a brief look at how Joomla! actually works. While an understanding of the presentation framework of Joomla! and VirtueMart may be useful for themes and templates development, it is not essential for the actual customization design. Joomla! emerged from version 1.0 and later developed into 1.5. In this upgrade, Joomla! has been basically rewritten from the ground up. A presentation structure called Model-View-Controller or MVC has been adopted in Joomla! 1.5. While a detailed explanation of the MVC structure is out of the scope, a basic understanding of its working will help us understand why and how VirtueMart 1.1 behaves in the way it is right now. Joomla! is a web application. Each page of Joomla! is in fact a text file consisting of HTML code. Depending on the detail parameters of a web request, Joomla! will generate a dynamic HTML page by combining data stored in the database and site configuration data stored in various PHP files. In the early history of dynamic web pages, program code were written in a way that HTML tags are mixed with presentation logic in one place. The spaghetti code, as it is sometimes called, makes maintenance and extension of the coding very difficult. As the basic structure of a dynamic web page is better understood, more and more new coding patterns emerge to make the life of a web developer easier. The MVC presentation framework is one of those patterns that have been proposed to build computer applications. This framework has gradually become the standard pattern for building web applications and has been adopted by many open source web projects. Models In the MVC presentation framework , the job of building a web page is divided into three main tiers. The backend tier is the data that is stored in the database (strictly speaking, there is no prescribed data storage format though a database is a natural way to manage the data). We need to grab data needed to build the web page. This tier of the job is done by the Model, which describes how data is stored and how data can be retrieved from the data server. Views The frontend tier determines what and how data is presented on the browser. This is the job of the View. For a given dataset from a Model, there can be many different ways to present the data. Let's say, we have a set of statistical data, for example. We can present this data as a bar graph or a pie chart. Each of these presentations is called a View of the same Model. Controllers Now statistical data is just a set of numbers. How can we convert them into a bar graph or a pie chart? That is exactly how the Controller comes into place. A Controller is a routine specifying how to convert the Model into various Views. One major advantage of this separation of data (Model) and presentation (View) makes changes to the application much easier. We can change the presentation independent of the underlying data and vice versa. So, in the Joomla! 1.5 world, we will have a set of Models which interface with the database, a set of Views to tell the browser how to present the data, and a set of Controllers that control how to convert the Model into the View. According to the best practice, all Joomla! 1.5 components should follow this same structure. Thus, each Joomla! 1.5 component should have two subdirectories called models and views. Also, the root directory will contain a controller.php which extends the Joomla! controller's capability. This structure is revealed as we look at the contents of a Joomla! component which we had done previously. However, because of historical reasons and others, not all components follow this best practice. VirtueMart is one of those exceptions.
Read more
  • 0
  • 0
  • 2280

article-image-hands-tutorial-ejb-31-security
Packt
15 Jun 2011
9 min read
Save for later

Hands-on Tutorial on EJB 3.1 Security

Packt
15 Jun 2011
9 min read
EJB 3.1 Cookbook Security is an important aspect of many applications. Central to EJB security is the control of access to classes and methods. There are two approaches to controlling access to EJBs. The first, and the simplest, is through the use of declarative annotations to specify the types of access permitted. The second approach is to use code to control access to the business methods of an EJB. This second approach should not be used unless the declarative approach does not meet the needs of the application. For example, access to a method may be denied during certain times of the day or during certain maintenance periods. Declarative security is not able to handle these types of situations. In order to incorporate security into an application, it is necessary to understand the Java EE environment and its terminology. The administration of security for the underlying operating system is different from that provided by the EE server. The EE server is concerned with realms, users and groups. The application is largely concerned with roles. The roles need to be mapped to users and groups of a realm for the application to function properly. A realm is a domain for a server that incorporates security policies. It possesses a set of users and groups which are considered valid users of an application. A user typically corresponds to an individual while a group is a collection of individuals. Group members frequently share a common set of responsibilities. A Java EE server may manage multiple realms. An application is concerned with roles. Access to EJBs and their methods is determined by the role of a user. Roles are defined in such a manner as to provide a logical way of deciding which users/groups can access which methods. For example, a management type role may have the capability to approve a travel voucher whereas an employee role should not have that capability. By assigning certain users to a role and then specifying which roles can access which methods, we are able to control access to EJBs. The use of groups makes the process of assigning roles easier. Instead of having to map each individual to a role, the user is assigned to a group and the group is mapped to a role. The business code does not have to check every individual. The Java EE server manages the assignment of users to groups. The application needs only be concerned with controlling a group's access. A group is a server level concept. Roles are application level. One group can be associated with multiple applications. For example, a student group may use a student club and student registration application while a faculty group might also use the registration application but with more capability. A role is simply a name for a set of capabilities. For example, an auditor role may be to review and certify a set of accounts. This role would require read access to many, if not all, of the accounts. However, modification privileges may be restricted. Each application has its own set of roles which have been defined to meet the security needs of the application. The EE server manages realms consisting of users, groups, and resources. The server will authenticate users using Java's underlying security features. The user is then referred to as a principal and has a credential containing the user's security attributes. During the deployment of an application, users and groups are mapped to roles of the application using a deployment descriptor. The configuration of the deployment descriptor is normally the responsibility of the application deployer. During the execution of the application, the Java Authentication and Authorization Service (JAAS) API authenticates a user and creates a principal representing the user. The principal is then passed to an EJB. Security in a Java EE environment can be viewed from different perspectives. When information is passed between clients and servers, transport level security comes into play. Security at this level can include Secure HTTP (HTTPS) and Secure Sockets Layer (SSL). Messages can be sent across a network in the form of Simple Object Access Protocol (SOAP) messages. These messages can be encrypted. The EE container for EJBs provides application level security which is the focus of the chapter. Most servers provide unified security support between the web container and the EJB container. For example, calls from a servlet in a web container to an EJB are handled automatically resulting in a flexible security mechanism. Most of the recipes presented in this article are interrelated. If your intention is to try out the code examples, then make sure you cover the first two recipes as they provide the framework for the execution of the other recipes. In the first recipe, Creating the SecurityApplication, we create the foundation application for the remaining recipes. In the second recipe, Configuring the server to handle security, the basic steps needed to configure security for an application are presented. The use of declarative security is covered in the Controlling security using declarations recipe while programmatic security is discussed in the next article on Controlling security programmatically. The Understanding and declaring roles recipe examines roles in more detail and the Propagating identity recipe talks about how the identity of a user is managed in an application. Creating the SecurityApplication In this article, we will create a SecurityApplication built around a simple Voucher entity to persist travel information. This is a simplified version of an application that allows a user to submit a voucher and for a manager to approve or disapprove it. The voucher entity itself will hold only minimal information. Getting ready The illustration of security will be based on a series of classes: Voucher – An entity holding travel-related information VoucherFacade – A facade class for the entity AbstractFacade – The base class of the VoucherFacade VoucherManager – A class used to manage vouchers and where most of the security techniques will be demonstrated SecurityServlet – A servlet used to drive the demonstrations All of these classes will be members of the packt package in the EJB module except for the servlet which will be placed in the servlet package of the WAR module. How to do it... Create a Java EE application called SecurityApplication with an EJB and a WAR module. Add a packt package to the EJB module and an entity called Voucher to the package. Add five private instance variables to hold a minimal amount of travel information: name, destination, amount, approved, and an id. Also, add a default and a three argument constructor to the class to initialize the name, destination, and amount fields. The approved field is also set to false. The intent of this field is to indicate whether the voucher has been approved or not. Though not shown below, also add getter and setter methods for these fields. You may want to add other methods such as a toString method if desired. @Entity public class Voucher implements Serializable { private String name; private String destination; private BigDecimal amount; private boolean approved; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; public Voucher() { } public Voucher(String name, String destination, BigDecimal amount) { this.name = name; this.destination = destination; this.amount = amount; this.approved = false; } ... } Next, add an AbstractFacade class and a VoucherFacade class derived from it. The VoucherFacade class is shown below. As with other facade classes found in previous chapters, the class provides a way of accessing an entity manager and the base class methods of the AbstractFacade class. @Stateless public class VoucherFacade extends AbstractFacade<Voucher> { @PersistenceContext(unitName = "SecurityApplication-ejbPU") private EntityManager em; protected EntityManager getEntityManager() { return em; } public VoucherFacade() { super(Voucher.class); } } Next, add a stateful EJB called VoucherManager. Inject an instance of the VoucherFacade class using the @EJB annotation. Also add an instance variable for a Voucher. We need a createVoucher method that accepts a name, destination, and amount arguments, and then creates and subsequently persists the Voucher. Also, add get methods to return the name, destination, and amount of the voucher. @Stateful public class VoucherManager { @EJB VoucherFacade voucherFacade; Voucher voucher; public void createVoucher(String name, String destination, BigDecimal amount) { voucher = new Voucher(name, destination, amount); voucherFacade.create(voucher); } public String getName() { return voucher.getName(); } public String getDestination() { return voucher.getDestination(); } public BigDecimal getAmount() { return voucher.getAmount(); } ... } Next add three methods: submit – This method is intended to be used by an employee to submit a voucher for approval by a manager. To help explain the example, display a message showing when the method has been submitted. approve – This method is used by a manager to approve a voucher. It should set the approved field to true and return true. reject – This method is used by a manager to reject a voucher. It should set the approved field to false and return false. @Stateful public class VoucherManager { ... public void submit() { System.out.println("Voucher submitted"); } public boolean approve() { voucher.setApproved(true); return true; } public boolean reject() { voucher.setApproved(false); return false; } } To complete the application framework, add a package called servlet to the WAR module and a servlet called SecurityServlet to the package. Use the @EJB annotation to inject a VoucherManager instance field into the servlet. In the try block of the processRequest method, add code to create a new voucher and then use the submit method to submit it. Next, display a message indicating the submission of the voucher. public class SecurityServlet extends HttpServlet { @EJB VoucherManager voucherManager; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { voucherManager.createVoucher("Susan Billings", "SanFrancisco", BigDecimal.valueOf(2150.75)); voucherManager.submit(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet SecurityServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h3>Voucher was submitted</h3>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } ... } Execute the SecurityServlet. Its output should appear as shown in the following screenshot: How it works... In the Voucher entity, notice the use of BigDecimal for the amount field. This java.math package class is a better choice for currency data than float or double. Its use avoids problems which can occur with rounding. The @GeneratedValue annotation, used with the id field, is for creating an entity facade. In the VoucherManager class, notice the injection of the stateless VoucherFacade session EJB into a stateful VoucherManager EJB. Each invocation of a VoucherFacade method may result in the method being executed against a different instance of VoucherManager. This is the correct use of a stateless session EJB. The injection of a stateful EJB into a stateless EJB is not recommended.  
Read more
  • 0
  • 0
  • 2977

article-image-wordpress-3-security-apache-modules
Packt
10 Jun 2011
6 min read
Save for later

WordPress 3 Security: Apache Modules

Packt
10 Jun 2011
6 min read
  WordPress 3 Ultimate Security Protect your WordPress site and its network         Read more about this book       (For more resources on WordPress, see here.) IP deny with mod_access Apache offers a sure-fire way to lock down admin, care of the mod_access module. Similar to cPanel's IP Deny Manager, the greater flexibility of hand-coding empowers us to allow or deny all but specified IP addresses, domains, hosts, and networks. For now, we'll prevent access to the wp-admin directory pages for all IPs except yours. Open an htaccess file in your wp-admin directory via your control panel or the terminal: nano /path/to/WP-root/wp-admin/.htaccess Add these lines, swapping the IP for yours: order deny,allowdeny from allallow from 123.45.67.890 Need access from more IPs? Just add more alongside the first one, single space separated. But. If your IP address is dynamic, which very often it is, you may find this method a little too effective. If you do become locked out, cruise server-side to switch the IP. What is my IP? That old chestnut: whatismyip – http://whatismyip.com IP spoofing A chestnut gone bad, denying alone won't protect against man-in-the-middle attacks, so if you got this farthinking that you could have avoided all the SSL stuff after all, no, you were right to do that. No safeguard is a silver bullet. Deny syntax sure helps though, if you're not on the move.   Password protect directories Password protection is a way to give access to a directory and its sub-tree to a selected few people and may be used, typically: To house private files to which you need access from anywhere By developers fine-tuning a new blog theme For a client zone on a commercial site As an extra layer of protection to, say, wp-login or phpMyAdmin The procedure is to choose a directory, granting access to specified users. These privileged directory users are separate from, and should not be confused with, your server or WordPress users, the control being governed by Apache rather than by Linux or your WordPress database. That's a good thing, adding an independent tier of protection. cPanel's Password Protect Directories There are various ways to secure a directory, so let's start off with the regular control panel option, which in cPanel, is called Password Protect Directories: Browse to the target directory in File Manager, right-clicking and choosing Password Protect (or click through the panel icon if you like). Select the checkbox and give the directory a name to appear on the authentication screen. Save and you are redirected to a confirmation page. Click back to the previous page and add a username and password to access the folder. Save the newly authorized user. Now you can surf to that folder or some file within, are asked for credentials, and can log in. So what did we really just do there? Clicked on some shiny icons, added some details, and cPanel interacted a bit over far too many pages. Let's get geeky, it's worth it.   Authentication with mod_auth When we protect a folder, cPanel uses Apache's mod_auth module to amend or create two hidden files, htaccess and passwd. htaccess lives in the folder to protect and passwd lives safely above the web root in the hush-hush htpasswd directory. Using an example file, we can compare our control panel actions with those using the terminal, interacting directly with mod_auth. Cue screenshots, using cPanel we did this: And mod_auth creates the ruleset in the htaccess file, which we equally could just type: AuthType BasicAuthName "Protect me pretty please"AuthUserFile "/home/USERNAME/.htpasswds/public_html/protectme/passwd"Require valid-user Then we did this: And mod_auth yawns a bit while it adds credentials to a password file: johndoe:L9c7m/hO16slA (John's password is encrypted, server-side, but he logs in using the plaintext hackth!s.) Now then. Two points. First, with the syntax learnt or duplicated, it's quicker to bin the middleman and just use the shell. More importantly, by directly chatting up Apache, we have a better array of security tools. To clarify, let's take this a step at a time. The htaccess file Before we look at the mod_auth syntax that goes in htaccess files, a quick aside ... A quick shout out to htaccess, bless We've met the hidden htaccess file already. It's essentially a convenient and versatile web configuration file that can be added to multiple directories. The directives these files contain can equally be placed in other types of files such as those for our virtual hosts (which is tidier, all those directives from htaccess files being in one place). Uniquely, however, rules added in htaccess can be parsed immediately, or in other words, without the need to restart Apache. Feel the power! One other thing about htaccess: you don't need root access to add or edit these files. Listen up, shared hosting people, this is very convenient because you don't have root access (to hack into your co-sharers directories!) to those configuration files, but you do have access to your own jailed (or chroot-ed) web files. And because htaccess files live with your files, you can tweak them at will. Now back to using htaccess to store that mod_auth syntax ... In this case, for any directory you want to protect, just add or append an htaccess file with your tailored mod_auth directives. Here's a closer look at the mod_auth syntax, beginning with its type: AuthType Basic Pretty basic then and more on that later. For when we navigate to the login page we want some kind of instructional message: AuthName "Protect me pretty please" Now the link to the directory's corresponding password file: AuthUserFile "/home/USERNAME/.htpasswds/public_html/DIRECTORY-TOPROTECT/passwd" And we'll specify to give access only to users recorded in the password file: Require valid-user So far so good. Carry on. The passwd file Often referred to as the htpasswd file, here's the syntax it houses: johndoe:L9c7m/hO16slA johndoe is the authorized, or required user. L9c7m/hO16slA is the encrypted form of hackth!s , his password. We use a handy tool, also called htpasswd, to encrypt that. Add as many usernames and passwords as you like to this file, each on a new line. The file itself can live and be called whatever you like as long as the AuthUserFile directive corresponds. One thing though: the file should be located above your web root.  
Read more
  • 0
  • 0
  • 2013
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-cocoa-and-objective-c-handling-events
Packt
09 Jun 2011
8 min read
Save for later

Cocoa and Objective-C: Handling events

Packt
09 Jun 2011
8 min read
Some recipes in this article require Mac OS X Snow Leopard 10.6. The Trackpad preferences allow you to easily adjust many gestures that will used in the following recipes. To make sure that your trackpad is recognizing gestures, make sure that you have set the correct preferences to enable gesture support under the Trackpad System Preference. Interpreting the pinch gesture The pinch gesture is a gesture normally used for the zooming of a view or for changing the font size of text. In this recipe, we will create a custom view that handles the pinch gesture to resize a custom view. Getting ready In Xcode, create a new Cocoa Application and name it Pinch. How to do it... In the Xcode project, right-click on the Classes folder and choose Add…, then choose New File… Under the MacOS X section, select Cocoa Class, then select Objective-C class. Finally, choose NSView in the Subclass of popup. Name the new file MyView.m Double-click on the MainMenu.xib file in the Xcode project. From Interface Builders Library palette, drag a Custom View into the application window. From Interface Builders Inspector's palette, select the Identity tab and set the Class popup to MyView. Choose Save from the File menu to save the changes that you have made. In Xcode, Add the following code in the drawRect: method of the MyView class implementation: NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect: [self bounds] xRadius:8.0 yRadius:8.0]; [path setClip]; [[NSColor whiteColor] setFill]; [NSBezierPath fillRect:[self bounds]]; [path setLineWidth:3.0]; [[NSColor grayColor] setStroke]; [path stroke]; Next, we need to add the code to handle the pinch gesture. Add the following method to the MyView class implementation: - (void)magnifyWithEvent:(NSEvent *)event { NSSize size = [self frame].size; size.height = size.height * ([event magnification] + 1.0); size.width = size.width * ([event magnification] + 1.0); [self setFrameSize:size]; } Choose Build and Run from Xcode's toolbar to run the application. How it works... In our drawRect: method, we use Cocoa to draw a simple rounded rectangle with a three point wide gray stroke. Next, we implement the magnifyWithEvent: method. Because NSView inherits from NSResponder, we can override the magnifyWithEvent: method from the NSResponder class. When the user starts a pinch gesture, and the magnifyWithEvent: method is called, the NSEvent passed to us in the magnifyWithEvent: method which contains a magnification factor we can use to determine how much to scale our view. First, we get the current size of our view. We add one to the magnification factor and multiply by the frame's width and height to scale the view. Finally, we set the frame's new size. There's more... You will notice when running the sample code that our view resizes with the lower-left corner of our custom view remaining in a constant position. In order to make our view zoom in and out from the center, change the magnifyWithEvent: method's code to the following: NSSize size = [self frame].size; NSSize originalSize = size; size.height = size.height * ([event magnification] + 1.0); size.width = size.width * ([event magnification] + 1.0); [self setFrameSize:size]; CGFloat deltaX = (originalSize.width - size.width) / 2; CGFloat deltaY = (originalSize.height - size.height) / 2; NSPoint origin = self.frame.origin; origin.x = origin.x + deltaX; origin.y = origin.y + deltaY; [self setFrameOrigin:origin]; Basically, what we have done is moved our custom view's origin by the difference between the original size and the new size. Interpreting the swipe gesture The swipe gesture is detected when three or more fingers move across the trackpad. This gesture is often used to page through a series of images. In this recipe, we will create a custom view that interprets the swipe gesture in four different directions and displays the direction of the swipe in our custom view: Getting ready In Xcode, create a new Cocoa Application and name it Swipe. How to do it... In the Xcode project, right-click on the Classes folder and choose Add…, then choose New File… Under the MacOS X section, select Cocoa Class, then select Objective-C class. Finally, choose NSView in the Subclass of popup. Name the new file MyView.m Double-click on the MainMenu.xib file in the Xcode project. From Interface Builders Library palette, drag a Custom View into the application window. From Interface Builders Inspector's palette, select the Identity tab and set the Class popup to MyView. Choose Save from the File menu to save the changes that you have made. In Xcode, open the MyView.h file and add the direction variable to the class interface: NSString *direction; Open the MyView.m file and add the following code in the drawRect: method of the MyView class implementation: NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect: [self bounds] xRadius:8.0 yRadius:8.0]; [path setClip]; [[NSColor whiteColor] setFill]; [NSBezierPath fillRect:[self bounds]]; [path setLineWidth:3.0]; [[NSColor grayColor] setStroke]; [path stroke]; if (direction == nil) { direction = @""; } NSAttributedString *string = [[[NSAttributedString alloc] initWithString:direction] autorelease]; NSPoint point = NSMakePoint(([self bounds].size.width / 2) - ([string size].width / 2), ([self bounds].size.height / 2) - ([string size].height / 2)); [string drawAtPoint:point]; Add the following code to handle the swipe gesture: - (void)swipeWithEvent:(NSEvent *)event { if ([event deltaX] > 0) { direction = @"Left"; } else if ([event deltaX] < 0) { direction = @"Right"; } else if ([event deltaY] > 0) { direction = @"Up"; } else if ([event deltaY] < 0){ direction = @"Down"; } [self setNeedsDisplay:YES]; } In Xcode, choose Build and Run from the toolbar to run the application. How it works... As we did in the other recipes in this article, we draw a simple rounded rectangle in the drawRect: method of the view. However, we will also be drawing a string denoting the direction of the swipe in the middle of our view. In order to handle the swipe gesture, we override the swipeWithEvent: method from the NSResponder class which NSView inherits. By inspecting the values of deltaX and deltaY of the NSEvent passed into the swipeWithEvent: method, we can determine the direction of the swipe. We set the direction string with the direction of the swipe so we can draw it in the drawRect: method. Finally, we call setNeedsDisplay:YES to force our view to redraw itself. There's more... You might have noticed that we do not need to override the acceptsFirstResponder: method in our view in order to handle the gesture events. When the mouse is located within our view, we automatically receive the gesture events. All we need to do is implement the methods for the gestures we are interested in. Interpreting the rotate gesture The rotate gesture can be used in any number of ways in a custom view. From rotating the view itself or simulating a rotating dial in a custom control. This recipe will show you how to implement the rotate gesture to rotate a custom view. Using your thumb and index finger, you will be able to rotate the custom view around its center: Getting ready In Xcode, create a new Cocoa Application and name it Rotate. How to do it... In the Xcode project, right-click on the Classes folder and choose Add…, then choose New File… Under the MacOS X section, select Cocoa Class, then select Objective-C class. Finally, choose NSView in the Subclass of popup. Name the new file MyView.m. Double-click on the MainMenu.xib file in the Xcode project. From Interface Builders Library palette, drag a Custom View into the application window. From Interface Builders Inspector's palette, select the Identity tab and set the Class popup to MyView. Choose Save from the File menu to save the changes that you have made. In Xcode, add the following code in the drawRect: method of the MyView class implementation: NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect: [self bounds] xRadius:8.0 yRadius:8.0]; [path setClip]; [[NSColor whiteColor] setFill]; [NSBezierPath fillRect:[self bounds]]; [path setLineWidth:3.0]; [[NSColor grayColor] setStroke]; [path stroke]; Next we need to add the code to handle the rotate gesture. Add the following method to the MyView class implementation: - (void)rotateWithEvent:(NSEvent *)event { CGFloat currentRotation = [self frameCenterRotation]; [self setFrameCenterRotation:(currentRotation + [event rotation])]; } Choose Build and Run from Xcode's toolbar to test the application. How it works... As we did in the previous recipe, we will create a simple rounded rectangle with a three-point stroke to represent our custom view. Our custom view overrides the rotateWithEvent: method from NSResponder to handle the rotation gesture. The rotation property of the NSEvent passed to us in the rotateWithEvent: contains the change in rotation from the last time the rotateWithEvent: method was called. We simply add this value to our view's frameCenterRotation value to get the new rotation. There's more... The value returned from NSEvent's rotation will be negative when the rotation is clockwise and positive when the rotation is counter-clockwise.
Read more
  • 0
  • 0
  • 4401

article-image-how-build-rss-reader-windows-phone-7
Packt
09 Jun 2011
10 min read
Save for later

How to Build a RSS Reader for Windows Phone 7

Packt
09 Jun 2011
10 min read
  Microsoft SharePoint 2010 Enterprise Applications on Windows Phone 7 Create enterprise-ready websites and applications that access Microsoft SharePoint on Windows Phone 7         Read more about this book       (For more resources on Microsoft Sharepoint, see here.) Security in SharePoint 2010 We begin this article with a discussion on security for a very simple reason: security in SharePoint is tricky. In addition to that one very simple reason, authenticating users against SharePoint from within a Windows Phone 7 client application is even trickier. In this article, the example RSS reader that we develop will only use anonymous access to the RSS feeds in SharePoint. Setting up anonymous access is very simple and we'll walk through the steps here. When writing this article, I came across a lot of errors on my testing server, but not my development server. After a couple of days of unsuccessful web searches and reinstalling different components, I discovered the root of my problem was due to the fact that the SharePoint 2010 Prerequisites install a non-final version of ADO. NET Data Services 1.5. Make sure the final version is installed from Microsoft. More information is available at the following URL: http://blogs.msdn.com/b/astoriateam/archive/2010/01/27/data-services-update-for-net-3-5-sp1-available-for-download.aspx There are two places where we need to make changes to our SharePoint site to enable anonymous access: Central Administration Site Permissions Central Administration Classic mode authentication is more or less just classic Windows authentication using NTLM or Kerberos. Although Internet Explorer Mobile in Windows Phone 7 can do the NTLM authentication, as we've been doing up to now to view SharePoint sites in the browser, the version of Silverlight that is included in Windows Phone 7 cannot currently use this authentication mechanism. Carry out the following steps to configure Central Administration for anonymous access: From the Start menu, select All Programs. Find the folder named Microsoft SharePoint 2010 Products in the list of programs and click on it. Click on SharePoint 2010 Central Administration. You need to select the Yes option on the User Account Control dialog that may appear. At this point, the home page for SharePoint 2010 Central Administration should appear as displayed in the following screenshot: (Move the mouse over the image to enlarge.) Next, click on Manage web applications. The page that appears lists out all of the web applications in the SharePoint site. There should be two items listed here, but it is possible there are more. Select the main website by clicking on its name. This main website is usually titled SharePoint – 80. Once selected, the ribbon bar across the top should light up, as all the icons become active. Carry out the following steps to enable anonymous access: Click on the Authentication Providers icon. In the Authentication Providers dialog that appears, select the Default link. The Edit Authentication dialog box will appear. In the third section, down under a heading of Anonymous Access there is a check box listed as Enable anonymous access. Check that box. Scroll all the way to the bottom of the dialog box and select the Save button. SharePoint 2010 will process the request. Then, return to the Authentication Providers dialog box and close it. There is one more section that may need tweaking and if this is a production environment, it should be considered. That section is Anonymous Policy. Click on the icon for it in the ribbon and a dialog box will appear. From here, we can customize the anonymous policy for the site. None – No policy basically leaves the door open for read and write access from anonymous users. This is a good policy to use when anyone who can access the site should also be able to modify the content of the site. This is a good policy for Wiki's. Deny Write – Has no write access allows the anonymous users to read the site, but they cannot write, update, or delete content. This is a good policy to use for sites that we want to specify particular authenticated accounts write access, but allow everyone the ability to read the content. Some Wiki's use this policy and a lot of blogs use this policy. Deny All – Has no access selecting this removes all permissions to the anonymous user. Secure content should always use this policy. Site Permissions Once we have updated the web application to allow anonymous access, we have to give anonymous users access to the site collection. To do this, we close Central Administration and open our SharePoint site. Once on the site, select Site Permissions from the Site Actions menu. This will open the Permissions home page. In the ribbon at the top, there is an icon named Anonymous Access. Click on that button and the Anonymous Access dialog will appear, as shown in the following screenshot: This dialog has three radio buttons to fine tune the access that anonymous users have. The key point to remember here is that although we are really opening up the site for everyone to see, we can break the inherit permissions model on a child page at any time if we need to remove anonymous access. Now that we have opened up our SharePoint site to anonymous users, we can begin to write applications for Windows Phone 7. In a production environment, we may not have the privilege of opening a SharePoint site this wide, but remember that we are only doing it for demonstration purposes here. We have to walk before we can run. Now, let's get started on the RSS reader.   Using WebClient to get data from the web As was stated in the introduction to this article, we are going to build a really simple RSS reader for Windows Phone 7. We are going to keep everything really simple. What that means is that we are going to focus on the pieces of code that actually do something. This is what we are going to do: Create our base project Add a text block to display the WebClient results Create a WebClient Use the WebClient to request the contents of our SharePoint home page Display the raw HTML that is returned in the text block on the page First, a quick word about WebClient. WebClient isn't the most robust method of making requests over a network, but it's really simple and works for simple cases, such as the one we are working with. Creating the base project We can start by creating our base project. This RSS reader will use the Visual Studio Silverlight for Windows Phone Windows Phone Application template. Carry out the following steps to start the project: Open Visual Studio 2010. Select File from the main menu and then select New Project…. In the New Project dialog box that appears, select Silverlight for Windows Phone. Then select Windows Phone Application from the list of templates for Windows Phone. Give the project a name, for example SimpleRSSReader. Give the Solution a name, for example Chapter06. Change the Location as desired and click on the OK button. At this point, Visual Studio will go off and create the solution and project. When it has finished, MainPage.xaml will appear on the screen in split screen mode, as shown in the following screenshot: Displaying WebClient results by adding a text block The first thing we are going to do here is add a text block to the content panel. Add the following code to the Grid that has a name of ContentPanel. <TextBlock x_Name="webClientResults" /> This creates a text block named webClientResults and puts it in ContentPanel. We could spruce this up a bit by providing a font size, or padding, but we are going to keep this really simple and only show the code needed to get things done. Save the progress. Creating a WebClient Open up the code behind by either clicking on it in the top tab bar, double-clicking the file name in Solution Explorer, or press F7 while in the XAML code. In the code behind, create a private member variable, outside the constructor, named client of type WebClient and a private member variable, also outside the constructor, named siteUrl of type string. The siteUrl should have a value that is the URL to your SharePoint home page. private WebClient client = new WebClient();private string siteUrl = "http://ssps2010/"; These are the variables that we'll be using in just a minute. The first is the WebClient that makes the requests on the network. The second is the Url for our SharePoint home page. This is the address that the WebClient will use to request a web page. Requesting the contents of our SharePoint home page Now that we have a WebClient, let us do something with it. Add the following code to the Main Page constructor: client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);client.DownloadStringAsync(new Uri(siteUrl)); The first line adds a new event handler to the DownloadStringCompleted event. This event handler is called client_DownloadStringCompleted and we will write it shortly. The second line is what starts an asynchronous request to our SharePoint home page to get the HTML content. Displaying the raw HTML that is returned Until now, we've created a place in the content panel to display our results. We've created a couple of variables. We've added a new event handler for when the WebClient finishes and we've made the web request for our SharePoint home page. Next, we are going to receive the result from the WebClient. Earlier, when we added a new event handler to the WebClient, we told WebClient that when it finishes downloading the string, it should call our method named client_DownloadStringCompleted. The following is the code for that method: void client_DownloadStringCompleted(object sender,DownloadStringCompletedEventArgs e) { if(e.Error == null) { webClientResults.Text = e.Result; }} First, we check to see if there is an error. To make this as simple as possible, we are not handling the situation where there is an error. We only care if there are no errors. Always check that errors are null. If there is an exception in the WebClient request, the DownloadStringCompletedEventArgs Error property will contain an object of type Exception. These exceptions can range from network connections being down, which is common for cell phones, to invalid URLs. We then take the result of the web request and put it in the text block we created earlier. Save the progress and press F5 to see the application run on the Windows Phone 7 Emulator. In the preceding screenshot, ApplicationTitle and PageTitle have also been updated. Both of these text blocks are found in the XAML in TitlePanel. We have successfully used WebClient to read data from the web and display it on the screen. It is still in a raw format though, and it isn't much of an RSS reader, especially since this page isn't even RSS. We will get there, but first let's find some RSS in SharePoint.  
Read more
  • 0
  • 0
  • 1683

article-image-moodle-20-multimedia-working-2d-and-3d-maps
Packt
08 Jun 2011
12 min read
Save for later

Moodle 2.0 Multimedia: Working with 2D and 3D Maps

Packt
08 Jun 2011
12 min read
  Moodle 2.0 Multimedia Cookbook Add images, videos, music, and much more to make your Moodle course interactive and fun         Read more about this book       (For more resources on Moodle 2.0, see here.) Introduction Whenever you think of a map, you may either think of the traditional planisphere or the terrestrial globe. There are several types of maps apart from those previously mentioned. We can work with maps of the moon, Mars, constellations, and even the universe! Thus, we are not only going to focus on our planet, but we are going to travel even further! The topic of this article is going to deal with Traveling Around the World and Watching the Universe. After reading this article, you can focus on your next holiday! We explain how to work with different types of maps. We are going to be as creative as possible. We should try to work with maps in an unconventional way. That is to say, the idea is to use a map for a Geography class, but we can use maps as a resource for any type of activity. Thus, we can work with the Geography teacher and he/she could work on another geographical feature of the place that we are working with. Therefore, in that way, we are adding more information to the place we are exploring. Maps are very attractive and they may become quite appealing to our students as long as we find a way to develop a rich activity using them. We should encourage the use of maps and the available resources that we have on the Web so that they can insert them in their homework by themselves as well. Thus, we can develop the activities in such a way that we can either provide the map or ask them to design a map. We can also work with maps in the case of Literature. We can ask students to draw a map of a place that has never existed in the real world, though it did in a story. Thus, another bit of homework that could prove helpful would be for students to design and carry out the map of such a place using the tools that we are going to explore in the following recipes. An example of this could be to draw the map of the country Ruritania and locate the cities of Zenda and Strealsau. These places do not exist in the real world, but they exist in the book The Prisoner of Zenda by Anthony Hope. So, many things can be done with maps. Creating maps with sceneries In this activity, we are going to create a map with sceneries. Therefore, we could either browse our files for pictures from our trips or holidays, or we can search for sceneries on the Web. After selecting the pictures, we create a new folder in Windows Explorer, for example C:Images_Traveling. In this folder, we save all the pictures so as to organize our work. We will use the following well-known website: http://earth.google.com/ to design a map using the pictures we have saved in the folder that we have just created. Let's get ready! Getting ready In this activity, we will work with the previously mentioned website. Therefore, we need to open the web browser and enter it. Click on Download Google Earth 6. Read the Google Maps/Earth Terms of Service and if you agree, click on Agree and Download. The icon of Google Earth will appear on your desktop, as shown in the following screenshot: How to do it... We have already carried out the first steps for this activity. Now, we have to design the maps with the pictures that we want to add. There are also some pictures that are available in the maps; you can also work with them, though the aim of this activity is to upload images in the map. Follow these steps in order to create a folder and find images for the activity: Click on the icon on your desktop and open Google Earth. Bring the Earth closer with the icons on the right. Locate a remote city in the southern hemisphere, as shown in the following screenshot: In the Fly to block, write "Mar del Plata", or any other remote city. Then press Enter or click on the magnifying glass next to the block. You will travel virtually to the desired city. Bring the map forward and locate the place where the picture to be uploaded was taken. Click on Add | Photo. Complete the Name block. Click on Browse. Search for the picture that you want to upload and click on it. Complete the other blocks: Description | View | Photo. Click on OK. The picture will appear, as shown in the following screenshot: You can repeat the same process as many times as the number of pictures you want to upload. After uploading all the pictures, click on File | Save | Save Image, as shown in the following screenshot: Complete the File name block and click on Save. How it works... After uploading the desired pictures to the map, we can create an activity. We could start this course with a little social interaction. We ask our students to think about what element they shouldn't forget if they happen to go to this place. They may not know this city, for sure, unless they live nearby. This is the most interesting part of inserting a remote city that they may want to know more about it! Therefore, a Chat is a good idea to have where all the students will be invited in order to discuss the city. We upload the map that we have created with the images to our activity within the Moodle course. Choose the weekly outline section where you want to insert this activity and follow these steps: Click on Add an activity | Chat. Complete the Name of this chat room and Introduction text blocks. Click on the Insert/edit image icon | Find or upload an image | Browse and look for the image that we have just saved. Click on Upload this file. Complete the Image description block and click on Insert. Click on Save and return to course. The activity looks as shown in the following screenshot: Drawing regions within a map In this activity, we are going to use an interactive website in which we choose a map to work with. It is a very simple one, but we could enhance it by adding interesting ingredients to the recipe. We will use a software for drawing a region on the map, and highlight a region for our students to work with. As it was pointed out before, we are not going to focus on geographical features, though you can add this ingredient yourself when designing the activity. Getting ready We open our default web browser and work with the following website: http://www.fusioncharts.com/maps/Default.asp. We click on Map Gallery and choose a map to work with. In this case, we choose a map of the world and highlight five regions, one for each continent. You can modify it and work with different regions within a continent or a country too. How to do it... We look for the desired map. We can find different types of maps to work with. Everything depends on what type of activity we have in mind. In this case, as the topic of this article has to do with traveling, we circle five regions and ask our students to choose where they would like to go. First of all, we have to find the map and save it as an image so that we can draw the regions and upload it to our Moodle course. Therefore, follow these steps: Click on click here | World Map with countries on the aforementioned site. Another pop-up window appears, displaying a map of the world with the countries. There appears a Map Configuration block where you can customize some features, as shown in the next screenshot. Click on Save Map as Image, as shown in the following screenshot: Another pop-up window will appear. Click on Save. Complete the File name block. Click on Save. Click on Open. A pop-up window displaying the map will appear. Click on File | Copy. Paste the map in Paint or Inkscape. Click on Edit | Paste from and browse for the name of the file. Select the file and click on Open. Use the resources available to draw the regions that you want students to work with, as shown in the following screenshot: Click on File | Save as and write a name for the file. Click on Save. How it works... We have already drawn the regions that we want our students to work with. We have chosen one country from every continent; you can choose another or design it in a different way. We can add a writing activity in which students choose where they would like to travel using the previous map. Select the weekly outline section where you want to add the activity and follow these steps: Click on Add an activity | Upload a single file within Assignments. Complete the Assignment name and Description blocks. Click on the Insert/edit image icon | Find or upload an image | Browse. When you find the image that you want to upload, click on Open | Upload this file. Complete the Image description block. Click on Insert. Click on Save and return to course. The activity is ready! When students click on the activity, it looks as shown in the following screenshot: Labeling a map with pins In this recipe, we will learn how to insert a map in our Moodle course labeled with pins, because we pin all the cities that we are going to work with. Therefore, we insert the map as a resource. After that, we design activities for our students to use the interactive map that we have just added. It is another way to use a resource, making our Moodle course more appealing to the eyes of our students. Getting ready We are going to work with Google Earth, as we did in the first recipe, so we have already installed it. We should think of the cities to insert in our course because we need to pin them all! How to do it... Click on the Google Earth icon that you have on your desktop. This is a way to enrich our traveling course by enhancing its appearance. So, these are the steps that you have to follow: Complete the Fly to block with the place that you want to pin. Click on the yellow pin, as shown in the following screenshot: A pop-up window will appear. Complete the Name block by writing the name of the city. Check the Latitude and Longitude, so that you place the pin correctly. You may complete the Description block. You can change the appearance of the pin by clicking on the pin itself. Another pop-up window will appear showing different sorts of icons, as shown in the following screenshot: You can choose the desired icon by clicking on it | OK. The icon that you have selected will appear in the map. Pin as many cities as you are going to work with and repeat steps 1-7. After pinning all the cities, save the file. Click on File | Save | Save Place as. Complete the File name block (remember to save the file in the folder which was created for this course) | Save. You have already saved the pinned map. How it works... We have to insert the map in our Moodle course. In this case, we are going to Add a resource, because we are introducing all the activities that are to come. So, choose the weekly outline section where you want to save the resource. These are the steps that you have to follow: Click on Add a resource | File. Complete the Name and Description blocks. Click on Add | Browse. Click on the file that you are going to upload | Open | Upload this file | Save and return to course. Although we have added a file, students can work with the map interactively! There's more We can embed the map in an HTML block in our Moodle course. Click on the downwards arrow next to Add... in Add a block, as shown in the following screenshot: Choose HTML and a new block will appear in our Moodle course. Embedding a map in an HTML block Open Google Earth and follow these steps in order to embed the map in the block that we have already added: Click on the View in Google Maps icon, as shown in the following screenshot: Another window appears. Click on Link | Customize and preview embedded map, as shown in the following screenshot: Click on Custom and adjust the Width and Height. In the Preview section, click on the minus sign and adjust the map to fit the window. Copy the HTML code to embed in our Moodle course. Go back to the Moodle course and click on the configuration icon to embed the map. Complete the Block title. In the Content block, click on the HTML icon, paste the HTML code which was copied, and click on Update. Click on Save changes. The map will look as shown in the following screenshot:
Read more
  • 0
  • 0
  • 2904

article-image-python-3-designing-tasklist-application
Packt
08 Jun 2011
7 min read
Save for later

Python 3: Designing a Tasklist Application

Packt
08 Jun 2011
7 min read
  Python 3 Web Development Beginner's Guide Use Python to create, theme, and deploy unique web applications         Read more about this book       (For more resources on Python, see here.) Designing a tasklist application   Designing an application should start with a clear idea of what is expected. Not only to determine what is technically required, but almost as important, to define clear boundaries so that we don't lose time on things that are just nice to have. Nice to have features are something to be added if there is time left in the project. Thehighlightedcodesetstherotationofthecircletofalse.Withoutthis,therevolute jointwouldbejustaweld jointintheend. So let's draw up a shortlist of the relevant features of our tasklist application. Some of these may seem obvious, but as we will see, these have a direct impact on some implementation choices that we have to make, such as: The application will be used by multiple users Task lists should be stored indefinitely A task list may contain an unlimited number of tasks but the user interface is designed for optimal performance for up to 25 tasks or so Tasks may be added, deleted, and marked as done Although this list isn't exhaustive, it has some important implications. The fact that the tasklist application will be used by more than one user means that we have to identify and authorize people who want to use it. In other words, we will need some sort of logon screen and a way to check people against some sort of password database. Because we do not want to burden the user with identifying himself/herself each and every time a task list is refreshed or altered, we need some way of implementing the concept of a session. Web applications use the stateless HTTP protocol. This means, from the server's point of view, every request is a single, unrelated event, and no information is retained at the server. This obviously presents us with a problem if we want to perform a set of related actions. The solution is to ask the web browser to send a small piece of information along with every request it makes to the application after the application has identified the user. This might be accomplished in a number of ways. The server may add an extra parameter to all links inside any web page it generates, commonly referred to as a session id, or use the even more general concept of a cookie. Once the server asks the web browser to store a cookie, this cookie is sent with every following request to the same website. The advantage of cookies is that common web application frameworks (like CherryPy) are already equipped to deal with them and implementing sessions with cookies is much simpler than designing the application to alter all hyperlinks it generates to include a proper session ID. The disadvantage might be that people may block their browser from storing cookies because some websites use them to track their clicking behavior. We let the simplicity of implementation prevail and opt for cookies. If users want to block cookies this is not much of a problem as most browsers also have the option to selectively allow cookies from designated websites. The following image illustrates the way CherryPy manages sessions with the help of cookies: It starts when the client (the web browser) sends a request to CherryPy. Upon receiving the request, the first check is to see if the web browser has sent along a cookie with a session ID. If it didn't, a new session idea is generated. Also, if there was a cookie with a session ID, if this ID is no longer valid (because it has expired, for example, or is a remnant from a very old interaction and doesn't exist in the current cache of session IDs) CherryPy also generates a new session ID. At this point, no persistent information is stored if this is a new session, but if it's an existing session there might be persistent data available. If there is, CherryPy creates a Session object and initializes it with the available persistent data. If not, it creates an empty Session object. This object is available as a global variable cherrypy.session. The next step for CherryPy is to pass control to the function that will handle the request. This handler has access to the Session object and may change it, for example, by storing additional information for later reuse. (Note that the Session object acts like a dictionary so you can simply associate values with keys with cherrypy.session['key']=value. The only restriction to the keys and values is that they must be serializable if the persistent storage is on disk). Then before returning the results generated by the handler, CherryPy checks if the Session object has changed. If (and only if) it has, are the contents of the Session object saved to a more permanent storage. Finally, the response is returned accompanied by a cookie with the session ID. Time for action – creating a logon screen Our first task is to create a small application that does little more than present the user with a logon screen. It will be the starting point of our tasklist application and many others as well. The code for this example is available from the Packt website. If you have not downloaded it yet, this might be a good time to do so. Enter the following pieces of code and save it in a file called logonapp.py import cherrypy import logon class Root(object): logon = logon.Logon(path="/logon", authenticated="/", not_authenticated="/goaway") @cherrypy.expose def index(self): username=logon.checkauth('/logon') return ''' <html><body> <p>Hello user <b>%s</b></p> </body></html>'''%username @cherrypy.expose def goaway(self): return ''' <html> <body><h1>Not authenticated, please go away.</h1> </body></html>''' @cherrypy.expose def somepage(self): username=logon.checkauth('/logon',returntopage=True) return '''<html> <body><h1>This is some page.</h1> </body> </html>''' if __name__ == "__main__": import os.path current_dir = os.path.dirname(os.path.abspath(__file__)) cherrypy.quickstart(Root(),config={ '/': {'tools.sessions.on': True } } ) If you now run logonapp.py, a very simple application is available on port 8080. It presents the user with a logon screen when the top level page http://localhost:8080/ is accessed. An example is shown in the following illustration: If a correct username/password combination is entered, a welcome message is shown. If an unknown username or wrong password is entered, the user is redirected to http://localhost:8080/goaway. The somepage() method (highlighted) returns a page with (presumably) some useful content. If the user is not yet authenticated, the logon screen is shown and upon entering the correct credentials, the user is directed back to http://localhost:8080/somepage. The complete tree of web pages within the logon sample application and the possible paths the user may pick through is shown next: Logon + session ID vs. HTTP basic authentication You may wonder why we choose not to reuse CherryPy's bundled auth_basic tool that offers basic authentication (for more information on this tool, see http://www.cherrypy.org/wiki/BuiltinTools#tools.auth_ basic). If all we wanted was to check whether a user is allowed access to a single page, this would be a good choice. The basic authentication is sufficient to authenticate a user, but has no concept of a session. This means we lack a way to store data that needs to be accessible when we process subsequent requests by the same user. The sessions tool we use here does provide this additional functionality.
Read more
  • 0
  • 0
  • 11288
article-image-25-useful-extensions-drupal-7-themers
Packt
07 Jun 2011
5 min read
Save for later

25 Useful Extensions for Drupal 7 Themers

Packt
07 Jun 2011
5 min read
Drupal 7 Themes Create new themes for your Drupal 7 site with a clean layout and powerful CSS styling Drupal modules There exist within the Drupal.org site a number of modules that are relevant to your work of theming a site. Some are straightforward tools that make your standard theming tasks easier, others are extensions to Drupal functionality that enable to you do new things, or to do things from the admin interface that normally would require working with the code. The list here is not meant to be comprehensive, but it does list all the key modules that are either presently available for Drupal 7 or at least in development. There are additional relevant modules that are not listed here, as at the time this was written, they showed no signs of providing a Drupal 7 version. Caution One thing to keep in mind here—some of these modules attempt to reduce complex tasks to simple GUI-based admin interfaces. While that is a wonderful and worthy effort, you should be conscious of the fact that sometimes tools of this nature can raise performance and security issues and due to their complexity, sometimes cause conflicts with other modules that also are designed to perform at least part of the functions being fulfilled by the more complex module. As with any new module, test it out locally first and make sure it not only does what you want, but also does not provide any unpleasant surprises. The modules covered in this article include: Administration Menu Chaos Tool Suit Colorbox Conditional Stylesheets Devel @font-your-face Frontpage HTML5 Tools .mobi loader Mobile Theme Nice Menus Noggin Organic Groups Panels Semantic Views Skinr Style Guide Sweaver Taxonomy Theme Theme Developer ThemeKey Views Webform Administration Menu The Administration Menu was a mainstay of many Drupal sites built during the lifespan of Drupal 6.x. With the arrival of Drupal 7, we thought it unlikely we would need the module, as the new toolbar functionality in the core accomplished a lot of the same thing. In the course of writing this, however, we installed Administration Menu and were pleasantly surprised to find that not only can you run the old-style Administration Menu, but they have also now included the option to run a Toolbar-style Administration Menu, as shown in the following screenshot: The Administration Menu Toolbar offers all the options of the default Toolbar plus the added advantage of exposing all the menu options without having to navigate through sub-menus on the overlay. Additionally, you have fast access to clearing the caching, running cron, and disabling the Devel module (assuming you have it installed). A great little tweak to the new Drupal 7 administration interface. View the project at: http://drupal.org/project/admin_menu. Chaos Tool Suite This module provides a collection of APIs and tools to assist developers. Though the module is required by both the Views and Panels modules, discussed elsewhere in this article, it provides other features that also make it attractive. Among the tools to help themers are the Form Wizard, which simplifies the creation of complex forms, and the Dependent widget that allows you to set conditional field visibility on forms. The suite also includes CSS Tools to help cache and sanitize your CSS. Learn more at http://drupal.org/project/ctools. Colorbox The Colorbox module for Drupal provides a jQuery-based lightbox plugin. It integrates the third-party plugin of the same name (http://colorpowered.com/colorbox/). The module allows you to easily create lightboxes for images, forms, and content. The module supports the most commonly requested features, including slideshows, captions, and the preloading of images. Colorbox comes with a selection of styles or you can create your own with CSS. To run this module, you must first download and install the Colorbox plugin from the aforementioned URL. Visit the Colorbox Drupal module project page at: http://drupal.org/project/colorbox. Conditional Stylesheets The module allows themers to easily address cross-browser compatibility issues with Internet Explorer. With this module installed, you can add stylesheets targeting the browser via the theme's .info file, rather than having to modify the template.php file. The module relies on the conditional comments syntax originated by Microsoft. To learn more, visit the project site at http://drupal.org/project/conditional_styles. Devel The Devel module is a suite of tools that are useful to both module and theme developers. The module provides a suite of useful tools and utilities. Among the options it provides: Auto-generate content, menus, taxonomies, and users Print summaries of DB queries Print arrays Log performance Summaries of node access The module is also a prerequisite to the Theme Developer module, discussed later in this article. Learn more: http://drupal.org/project/devel. @font-your-face @font-your-face provides an admin interface for browsing and applying web fonts to your Drupal themes. The module employs the CSS @font-face syntax and draws upon a variety of online font resources, including Google Fonts, Typekit. com, KERNEST, and others. The system automatically loads fonts from the selected sources and you can apply them to the styles you designate—without having to manually edit the stylesheets. It's easy-to-use and has the potential to change the way you select and use fonts on your websites. @font-your-face requires the Views module to function. Learn more at the project site: http://drupal.org/project/fontyourface. Frontpage This module serves a very specific purpose—it allows you to designate, from the admin interface, different front pages for anonymous and authenticated users. Though you can accomplish the same thing through use of $classes and a bit of work, the module makes it possible for anyone to set this up without having to resort to coding. Visit the project site at http://drupal.org/project/frontpage.
Read more
  • 0
  • 0
  • 5839

article-image-customizing-sharepoint-communities-windows-phone-7
Packt
03 Jun 2011
9 min read
Save for later

Customizing SharePoint Communities for Windows Phone 7

Packt
03 Jun 2011
9 min read
  Microsoft SharePoint 2010 Enterprise Applications on Windows Phone 7 Create enterprise-ready websites and applications that access Microsoft SharePoint on Windows Phone 7         Read more about this book       (For more resources on Microsoft Sharepoint, see here.) Let's get started with the discussion of SharePoint communities by taking a look at blogs.   Blogs At this point in the 21st century, everyone is familiar with what a blog is. In SharePoint, a blog is a site that is characterized by entries of content being listed from newest at the top of the page to oldest at the bottom. Content is determined by the author and can contain metadata such as the author, date, and keywords or tags to designate the categories in which the content belongs. Creating a blog site in SharePoint A blog site can either be the root site or a site contained within another site. This is consistent with all site types in SharePoint. The reason this is pointed out though, is that when creating a new SharePoint engagement, it is important to truly think of the overall goal of the website as a whole. If the website will essentially be a blog with other content thrown in from time to time, then it makes sense for the root site to be of the type blog. Otherwise, it makes sense to make the root site something else like the team site or a blank site and then add a blog site within that root site. This is important to think about because to add a blog to an existing site is fairly straightforward. Simply, carry out the following steps: From the root site, click on the Site Actions menu. On the Site Actions menu, select the New Site option. From the Installed Items list, select Blog. Give the new blog site a Title and a URL name. Finally, click on the Create button. At this point, SharePoint will create a new blog site. The new blog will contain some seed data to get the blog going. There are three categories named appropriately: Category 1 Category 2 Category 3 The new blog site will also have a location for archives containing the one entry that was seeded in the site titled Welcome to your Blog! This can all be seen in the following screenshot: Customizing a SharePoint blog site Although this blog site is ready to go right now, we will probably want to customize it for our usage scenario. There are several places to customize it, which are as follows: About this blog Categories Blog Tools Links About this blog When new readers reach a blog they look for information about the blog so they can get a high level overview of what to expect from the content of the site. This is usually found in the "about this blog" section of the site. In the SharePoint blog site, the About this blog section is a Wiki Web Part found in the right column. Although we will learn more about Wikis in the next section, for now just know that this web part allows us a what-you-see-is-what-you-get (WYSIWYG) editing surface to enter any content we want. To get into this editing mode, carry out the following steps: From the Site Actions menu, select Edit Page. When the page changes to edit mode, click on the text inside the About this blog section. At this point, the ribbon at the top will have the following four main sections: Editing Tools: This has the basic text editing tools that are familiar to anyone who has used Word. Table Tools: The about section is actually a table with two rows and one column. The top cell has the image, and the bottom has the text. The Table Tools section of the ribbon allows us to manage this table. Page Tools: These are the basic tools that are global to the page and not specific to this section. Web Part Tools:This part of the ribbon contains tools that allow us to minimize, restore, or delete the web part. It also allows us to edit the Web Part Properties. These properties include the title, as well as other appearance features such as height and width. It also includes layout information and some advanced features. Categories The next section to customize on this blog site is the list of categories. When creating a blog entry, we can categorize the contents with a tag. The default categories for a new blog are as follows: Category 1 Category 2 Category 3 The following steps show how to customize these categories: Click on the title Categories in the left column. This will open the list page for the categories. The categories list will display the three default categories. For each category, click on the Edit icon, as shown in the following screenshot: (Move the mouse over the image to enlarge.) Change the Title to something that makes sense for the blog which we are creating. Click on the Save button. Repeat these steps for all three of the default categories. To add more categories, click on the Add new item link below the list of categories. To delete a category, carry out the following steps: Move the pointer over the title of the category. This will trigger an arrow to appear to the right of the title next to the edit icon. Click on this down arrow. In the context menu that appears, select the Delete Item option. A confirmation message will appear asking if we are sure we want to send it to the recycle bin. Click on OK and the category will be deleted. Blog Tools Now that we have a blog, how do we manage the content? This is where the Blog Tools section comes into use. There are 4 links to help us manage the blog, which are as follows: Create a post Manage posts Manage comments Launch blog program to post Create a post Clicking on the Create a post link will open a modal dialog with a form to fill out to create a new blog entry. The fields include the following: Title: This is a plain text field used for the title of the entry. Body: This is a rich text field that utilizes the edit ribbon. Category: Here we can select the categories that the entry is a part of. Published: Here we can set a date for our entry to be published. Publishing an entry in the future is helpful when we have information that isn't supposed to be public knowledge until a specifi c time and date, or when information needs to be published at a specifi c time and date. The preceding fields are shown in the following screenshot: Manage posts Blog entries, like most things in SharePoint, are items in a list. Clicking on the Manage posts link will display all the blog entries. From this list, we can perform many management functions such as the following: Manage approval status Edit entries View entries Manage permissions Delete entries Manage comments All of the comments are managed in a separate list from the blog entries. Clicking on the Manage comments link will display all of the comments for all of the blog entries in this site. From here we can view, edit, or delete the comments, as well as manage permissions. Managing permissions on comments and posts is a lot like managing permissions elsewhere in SharePoint. By default, the list items inherit the parent permissions, but occasionally we will want to have specific permissions for special cases. We could have a blog entry that we only want a small group of people to see, or maybe we want to save a comment, so that only we can see it. The manage permissions section is how we can deal with these cases. More information on managing permissions can be found in the online help or on TechNet at the following URL: http://technet.microsoft.com/en-us/library/cc721640.aspx Launch blog program to post Although creating a blog entry in the web browser works well, sometimes we may want to use a more powerful tool to create entries. The Launch blog program to post link will open Microsoft Word 2007, or a newer version, to edit a new blog entry. Configuring Windows Live Writer There is a link in Blog Tools to launch Microsoft Word 2007 or newer, to create a new blog entry. Although Word does a pretty good job of creating new blog entries, there is a free tool from Microsoft, named Windows Live Writer (http://explore.live.com/windows-live-writer) which is true genius when it comes to editing blog entries. Using this tool can make most, if not all, blog posting tasks much easier within SharePoint. Configuring Windows Live Writer for a SharePoint is simple: When setting up Windows Live Writer, select SharePoint from the What blog service do you use? Click on Next and enter the URL of the SharePoint blog. Click on Next and provide the SharePoint authentication information. That's all there is to it. The Windows Live Writer interface also displays a preview of what the blog entry will look like in the site by clicking on the Preview tab at the bottom, as shown in the following screenshot: Links Finally, the links section allows us to add hyperlinks to the page for easy access to anything. The default entry is to a photo library named Photos. Adding a new link is as simple as the following steps: Click on the Add new link hyperlink. Enter the URL for the link. Optionally, enter a description that will be used in place of the raw URL for display. Optionally, add any notes. Notes show up when viewing the full list of links. The full list of links can be viewed by clicking on the title Links from the home page. Click on Save, as shown in the following screenshot:  
Read more
  • 0
  • 0
  • 2001

article-image-html5-generic-containers
Packt
01 Jun 2011
15 min read
Save for later

HTML5: Generic Containers

Packt
01 Jun 2011
15 min read
  HTML5 Multimedia Development Cookbook Recipes for practical, real-world HTML5 multimedia driven development.         Read more about this book       (For more resources on Multimedia development, see here.) Introduction "On the web, a man should not be judged by the color of his skin but by the content of his content." - Internet meme To be correct according to the specification semantically, we need to know what the content is so we can wrap it with the most appropriate new element tag. While this may mean we developers have to think differently, a new challenge is exactly why we're here. In this article we'll look at some examples of how to do just that using several of HTML5's new elements. "In case of conflict, consider users over authors over implementers over specifiers over theoretical purity." - Priority of Constituencies Throughout this article, we'll show you how to use the new <article> element to mark up both blog posts and comments, add a meaningful publication date to an <article>, use the new <mark> element to highlight text, and how to note visual elements using the new <figure> element. We'll then turn our attention to some new methods of styling text with font replacement techniques, as well as adding drop shadows and gradients to our text.   Structuring a blog article "The <article> element represents a self-contained composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content." - WHATWG's HTML5 Draft Standard - http://whatwg.org/html5 Getting ready Blog entries are perfect candidates for the new <article> element, which is designed for syndicated content. For this recipe, let's start by identifying the major elements of a blog <article>: There's usually a headline in the form of a heading tag, the blog entry itself consisting of several paragraphs and perhaps one or more images, and some information that usually includes the author's name and other related metadata. Notice this is all self-contained related content. How to do it... We're going to continue using the new HTML5 <header> and <footer> elements. The headline, entry and meta-information should be wrapped in their own unique tags, like <h2>, multiple <p>s and the new &ltfooter>. Let's start with a foundation and add our new <article> element twice: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Blog Title</title> <!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"> </script>[endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body><article> <header> <h2>Headline</h2> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer></article><article> <header> <h2>Headline</h2> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer></article></body></html> Put your code on a diet? Ready for a shocker? Want to have your mind blown? The <html> and <head> and <body> tags (as well as their closing tags) are now optional in the HTML5 specification. Sure, you could leave them in there, and your pages will validate just fine, but why should we? If remove them from the previous code, we are left with the spartan: <!DOCTYPE html><meta charset="UTF-8"><title>Blog Title</title><!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"> </script>[endif]--><meta name="viewport" content="width=device-width, initial-scale=1.0"><article> <header> <h2>Headline</h2> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer></article><article> <header> <h2>Headline</h2> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer></article> Don't believe me? Run that code through the World Wide Web Consortium's validator at: http://validator.w3.org, and you'll see it displays correctly in the browser. Well, not so fast buster. The problem is that removing those elements breaks our code for screen readers. Uh oh. Strike one. Also, removing the <body> tag breaks our new HTML5-enabling JavaScript for Internet Explorer. Strike two. And guess what? You can see it coming, can't you? Yes, removing the <html> tag removes the language of the page. There it is: Strike three. So let's add those elements back in, shall we? <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Blog Title</title> <!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"> </script>[endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body> <article> <header> <h2>Headline</h2> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer> </article> <article> <header> <h2>Headline</h2> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer> </article></body></html> There, that's better. How it works... Remember, the new <article> element is a collection of related information intended for syndication via RSS or another means. There's more... Richer, more meaningful semantics is perhaps the most significant goal for HTML5. It's better for machines, better for authors, and most importantly, better for our audiences. Validation as an aid, not a crutch As we saw previously, removing the &lthtml> and <head> and <body> tags render a still valid page. So that begs the question of how valid validators are. Unlike the XML world, HTML5 can use incorrect syntax and still render just fine. The author makes every effort to validate his code whenever possible. It's not necessary to be slavish to the validator, but it's always a good quality control check. And the closer you get to valid code, the better chance browsers will display your work in as consistent a manner as possible. Eric Meyer's funny The author loves how CSS guru Eric Meyer thinks about validators: Where to find validators You can make good use of code validators at: http://validator.nu http://validator.w3.org   Highlighting text using the mark element "The &ltmark> element represents a run of text in one document marked or highlighted for reference purposes, due to its relevance in another context. When used in a quotation or other block of text referred to from the prose, it indicates a highlight that was not originally present but which has been added to bring the reader's attention to a part of the text that might not have been considered important by the original author when the block was originally written, but which is now under previously unexpected scrutiny. When used in the main prose of a document, it indicates a part of the document that has been highlighted due to its likely relevance to the user's current activity." - WHATWG's HTML5 Draft Standard - http://whatwg.org/html5 Getting ready When viewing search results, you'll often find the term for which you searched highlighted. Instead of relying on a semantically meaningless tag, we can now use the more meaningful <mark> element. How to do it... In this recipe, you'll see HTML5doctor.com has an excellent example of how to use the new <mark> element to highlight a search results term. This gives a useful semantic hook not only for styling but also for the machine tracking the results. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title> <!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"> </script>[endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body> <h1>716,000,000 search results for the query "<mark>HTML 5</mark>"</h1> <section id="search-results"> <article> <h2><a href="http://en.wikipedia.org/wiki/HTML_5"> <mark>HTML 5</mark> - Wikipedia, the free encyclopedia</a></h2> <p><mark>HTML 5</mark> is the next major revision of <mark>HTML</mark> ("hypertext markup language"), the core markup language of the World Wide Web. The WHATWG started work on the ... <a href="http://en.wikipedia.org/wiki/HTML_5"> Read more</a></p> </article> <article> <h2><a href="http://dev.w3.org/html5/spec/Overview.html"> <mark>HTML 5</mark></a></h2> <p>A vocabulary and associated APIs for <mark>HTML</mark> and XHTML. Editor's Draft 16 August 2009. Latest Published Version: http://w3.org/TR/<mark>html5</mark>/; Latest Editor's ... <a href="http://dev.w3.org/html5/spec/Overview.html"> Read more</a></p> </article> </section></body></html> Adding a simple style declaration like: <style type="text/css"> mark {background-color: yellow; font-weight: bold;}</style> in the <head> section helps us render this highlighted text: How it works... The new <mark> element simply highlights a word or phrase to draw the reader's attention. To do this, simply specify the <mark> to be bold or italicized or highlighted in some way in your corresponding Cascading Style Sheet. There's more... Sure, you could mark up and style a search-results page to use the <b> or <i> or even <span> tags to indicate for which term the search took place, but each of those tags only affects the presentation layer. They lack meaning. The new &ltmark> element can accomplish the same visual effect, while also adding that extra meaning to your markup. In fact, the new &ltmark> element is full of win. <Mark> long and prosper Another great use of the new <mark> element is highlighting a date in a calendar picker, as we often see on any date-based reservation system website like Priceline.com. Priceline.com highlights the current date by default when booking your itinerary. Instead of using a semantically meaningless tag to achieve this, the new <mark> element could be a perfect candidate to use. Waiting for browsers The new <mark> element isn't fully supported by any web browser at the time of this writing. Though the extra semantic meaning may not be apparent to machine readers, we can still use the new <mark> element as a stylistic "hook" until the day its meaning is fully supported by a variety of browsers. Is "future proof" a word? Remember that HTML5's new elements attempt to add extra meaning to our markup. The goal is never to take away meaning or break pages. With this in mind, it becomes much more palatable to layer on new elements like the <mark> element that's not fully implemented by browsers yet. Even if its meaning is not fully understood by machines yet, it certainly does not hurt to add it and make our pages as "future proof" as we possibly can. See also In 2001, Carrie Bickner prepared the "New York Public Library Online Style Guide" (http://legacy.www.nypl.org/styleguide) for branches of the NYPL to use when updating their websites. In this seminal publication, Bickner made the case for web standards by separating content (markup) from presentation (Cascading Style Sheets) from behavior (JavaScript). The publication was extremely forward-thinking for the time and was in use for many years.   Using the time element "The &lttime> element represents either a time on a 24-hour clock, or a precise date in the proleptic Gregorian calendar, optionally with a time and a time-zone offset." - WHATWG's HTML5 Draft Standard - http://whatwg.org/html5 Getting ready The new <time> element is a powerful way to display time or a specific date. How to do it... In this recipe we'll display dates and times that will be readable for both humans and machines. Let's look at four examples. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title> <!--[if lt IE 9]><script src=http://html5shiv.googlecode.com/svn/trunk/html5.js> </script>[endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body> <article> <header> <h2>Headline</h2> <time datetime="2010-11-29">November 29, 2010</time> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer> </article> <article> <header> <h2>Headline</h2> <time datetime="2010-11-29">Nov. 29</time> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer> </article> <article> <header> <h2>Headline</h2> <time datetime="2010-11-29">the date this was written</time> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer> </article> <article> <header> <h2>Headline</h2> <time datetime="2010-11-29T11:34">the date and time this was written</time> </header> <p>First paragraph</p> <p>Second paragraph</p> <footer>Meta information.</footer> </article></body></html> How it works... We can use the new <time> element to indicate specific dates, times, or both. There's more... The new &lttime> element specifies an exact moment in time—not a time period. Odd rules One interesting aspect of the new <time> element is that you can't use a date before the Christian Era. You also can't use a date like "November 2010." Whatever date we specify must be a positive, specific date—not a relative one. The HTML5 Working Group continues to address this seemingly arbitrary restriction. <time>'s Time will come Browsers display the new <time> element but don't do anything special with it—yet. Always remember SEO Time. Why are we so obsessed with it? One very valid reason to focus on time and dates on the web is Search Engine Optimization. SEO, once seen as some sort of mysterious voodoo only black hatted wizards understood, is now everyone's responsibility online. You spend time creating good code and expect a writer to create content worth reading. Now go one step further and ensure that your intended audience can actually find the content you have taken the time to create. And the new <time> element is just one of the ways search engines draw attention to the most recent content. See also The new HTML5 <time> element is a possible addition to the Microformats movement. Microformats promise to add additional semantic meaning to our markup. Though not officially a standard, Microformats are slowly gaining acceptance in the web development community. Learn more at Microformats.org.  
Read more
  • 0
  • 0
  • 3477
article-image-cocoa-and-objective-c-animating-calayers
Packt
27 May 2011
6 min read
Save for later

Cocoa and Objective-C: Animating CALayers

Packt
27 May 2011
6 min read
Cocoa and Objective-C Cookbook Understanding the CALayer class In this recipe, we will use multiple layers to draw our custom view. Using a delegate method, we will draw the background of our view. A second layer will be used to include an image centered in the view. When complete, the sample application will resemble the following screenshot: Getting ready In Xcode, create a new Cocoa Application and name it CALayer. How to do it... In the Xcode project, right-click on the Classes folder and choose Add…, then choose New File… Under the MacOS X section, select Cocoa Class, then select Objective-C class. Finally, choose NSView in the Subclass of popup. Name the new file MyView.m. In the Xcode project, expand the Frameworks group and then expand Other Frameworks. Right-click on Other Frameworks and choose Add…, then choose Existing Frameworks… Find QuartzCore.framework in the list of frameworks and choose Add. Click on MyView.m to open it and add the following import: #import <QuartzCore/QuartzCore.h> Remove the initWithFrame: and drawRect: methods. Add the following awakeFromNib method: - (void) awakeFromNib { CALayer *largeLayer = [CALayer layer]; [largeLayer setName:@"large"]; [largeLayer setDelegate:self]; [largeLayer setBounds:[self bounds]]; [largeLayer setBorderWidth:4.0]; [largeLayer setLayoutManager:[CAConstraintLayoutManager layoutManager]]; CALayer *smallLayer = [CALayer layer]; [smallLayer setName:@"small"]; CGImageRef image = [self convertImage:[NSImage imageNamed:@"LearningJQuery"]]; [smallLayer setBounds:CGRectMake(0, 0, CGImageGetWidth(image), CGImageGetHeight(image))]; [smallLayer setContents:(id)image]; [smallLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMidY relativeTo:@"superlayer" attribute:kCAConstraintMidY]]; [smallLayer addConstraint:[CAConstraint constraintWithAttribute:kCAConstraintMidX relativeTo:@"superlayer" attribute:kCAConstraintMidX]]; CFRelease(image); [largeLayer addSublayer:smallLayer]; [largeLayer setNeedsDisplay]; [self setLayer:largeLayer]; [self setWantsLayer:YES]; } Add the following two methods to the MyView class as well: - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context { CGContextSetRGBFillColor(context, .5, .5, .5, 1); CGContextFillRect(context, [layer bounds]); } - (CGImageRef) convertImage:(NSImage *)image { CGImageSourceRef source = CGImageSourceCreateWithData((CFDataRef )[image TIFFRepresentation], NULL); CGImageRef imageRef = CGImageSourceCreateImageAtIndex(source, 0, NULL); CFRelease(source); return imageRef; } Open the MyView.h file and add the following method declaration: - (CGImageRef) convertImage:(NSImage *)image; Right-click on the CALayer project in Xcode's project view and choose Add…, then choose Existing Files…. Choose the LearningJQuery.jpg image and click on Add. Double-click on the MainMenu.xib file in the Xcode project. From Interface Builder's Library palette, drag a Custom View into the application window. From Interface Builder's Inspectors palette, select the Identity tab and set the Class popup to MyView. Back in Xcode, choose Build and Run from the toolbar to run the application. How it works... We are creating two layers for our view. The first layer is a large layer, which will be the same size as our MyView view. We set the large layers delegate to self so that we can draw the layer in the drawLayer: delegate method. The drawLayer: delegate method simply fills the layer with a mid-gray color. Next, we set the bounds property and a border width property on the larger layer. Next, we create a smaller layer whose contents will be the image that we included in the project. We also add a layout manager to this layer and configure the constraints of the layout manager to keep the smaller layer centered both horizontally and vertically relative to the larger view using the superlayer keyword. Lastly, we set the small layer as a sub-layer of the large layer and force a redraw of the large layer by calling setNeedsDisplay. Next, we set the large layer as the MyView's layer. We also need to call the setWantsLayer:YES on the MyView to enable the use of layers in our view. There's more... Since we used a layout manager to center the image in the view, the layout manager will also handle the centering of the image when the user resizes the view or window. To see this in action, modify the Size properties in Interface Builder for the custom view as shown in the screenshot below: Animation by changing properties Cocoa provides a way to animate views by changing properties using implied animations. In this recipe, we will resize our custom view when the resize button is clicked, by changing the views frame size. Getting ready In Xcode, create a new Cocoa Application and name it ChangingProperties. How to do it... In the Xcode project, right-click on the Classes folder and choose Add…, then choose New File… Under the MacOS X section, select Cocoa Class, then select Objective-C class. Finally, choose NSView from the Subclass of popup. Name the new file MyView.m. Click on the MyView.m file to open it and add the following in the drawRect: method: NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:[ self bounds] xRadius:8.0 yRadius:8.0]; [path setClip]; [[NSColor whiteColor] setFill]; [NSBezierPath fillRect:[self bounds]]; [path setLineWidth:3.0]; [[NSColor grayColor] setStroke]; [path stroke]; Click on the ChangingPropertiesAppDelegate.h to open it. Next, insert an import for the MyView.h header file: #import "MyView.h" Add the following variables to the class interface: NSButton *button; MyView *myView; Add the following properties to the class interface: @property (assign) IBOutlet NSButton *button; @property (assign) IBOutlet MyView *myView; Add the method declaration for when the Resize button is clicked: - (IBAction) resizeButtonHit:(id)sender; Click on the ChangingPropertiesAppDelegate.m file to open it. Add our synthesized variables below the synthesized window variable: @synthesize button; @synthesize myView; Create a global static boolean for tracking the size of the view: static BOOL isSmall = YES; Add the resizeButtonHit: method to the class implementation: - (IBAction) resizeButtonHit:(id)sender { NSRect small = NSMakeRect(20, 250, 150, 90); NSRect large = NSMakeRect(20, 100, 440, 240); if (isSmall == YES) { [[myView animator] setFrame:large]; isSmall = NO; } else { [[myView animator] setFrame:small]; isSmall = YES; } } Double-click on the MainMenu.xib file in the Xcode project. From Interface Builders Library palette, drag a Custom View into the application window. From Interface Builder's Inspector's palette, select the Identity tab and set the Class popup to MyView. From the Library palette, drag a Push Button into the application window. Adjust the layout of the Custom View and button so that it resembles the screenshot below: From Interface Builder's Inspector's palette, select the Identity tab and set the Class popup to MyView. Right-click on the Changing Properties App Delegate so that you can connect the outlets to the MyView Custom View, the Resize Push Button, and the resizeButtonHit action: Back in Xcode, choose Build and Run from the toolbar to run the application. How it works... We define two sizes for our view, one small size that is the same as the initial size of the view, and one large size. Depending on the state of the isSmall global variable, we set the view's frame size to one of our predefined sizes. Note that we set the view's frame via the views animator property. By using this property, we make use of the implicit animations available in the view. There's more... Using the same technique, we can animate several other properties of the view such as its position or opacity. For more information on which properties can be implicitly animated, see Apple's Core Animation Programming Guide.
Read more
  • 0
  • 0
  • 4130

article-image-joomla-virtuemart-product-list-templates
Packt
26 May 2011
23 min read
Save for later

Joomla! VirtueMart: Product List Templates

Packt
26 May 2011
23 min read
Joomla! VirtueMart 1.1 Theme and Template Design Give a unique look and feel to your VirtueMart e-Commerce store         Read more about this book       (For more resources on Joomla!, see here.) The product list page Product list page is the most important starting page for the shopping life cycle. While the landing page will give some general information regarding the shop, the list of items for sale in the shop is the major job of the product list page. Some shop owners even prefer to use product list page as their home page. Product list page is in singular, but actually the product list page is a series of pages. The total number of pages in the series varies from store-to-store and typically depends on the number of categories you have in the site. Each category will have its own page or even pages, if the category contains many products. Furthermore, the product list page is also used to list the products that relate to a particular manufacturer. It is also used for the keyword search and advanced search, if you enable the product search and advanced search Joomla! modules or the product search Joomla! plugin. To simplify our discussion, we will first restrict ourselves to the study of category listing. The manufacturer listing and search listing are very similar. Let's take a look at a typical category listing. From the preceding screenshot, we can identify a number of important elements on a product list page: Page header: This includes the category name, category description, the PDF, and print icons. The layout of the page header will depend on the page header templates. Navigation: This includes the order by form, the order by direction button (toggle between ascending and descending), number per page drop-down box, and the page navigation links. Note that the page navigation links can appear both at the top and the bottom. The navigation layout is controlled by the navigation templates. Product listing: This is the major item of the page, where the products are listed in a way defined by the product listing style and the number of products per row settings. Each of the products displayed within the listing is controlled by the core browse template (the core browse template is explained in the section Core browse templates). Addendum elements: This includes the recent products, latest products, featured products, and so on. Each of the addenda may have its own template. Page footer: This is the element placed at the end of the listing. Right now, there is only one element within the page footer, the page navigation. As we shall see, the layout of each of these elements is controlled by one or more templates. By customizing any one of these templates, we may be able to change the look of the page completely. We need to distinguish the usage between the terms browse templates and core browse templates. For the purpose of making things clear, we retain the term "browse templates" to refer to all templates within the browse template group. Within this broad template group, there are two subgroups: those which control the layout detail of each individual product (each product in the product listing section) and those which control all the other elements. We refer to them as core and non-core templates, respectively. The core browse templates reside directly under the templates/browse subdirectory. All the non-core templates reside under the subdirectory templates/browse/includes. The difference between the core and non-core templates will become clear in the following explanation.   Looking at our first template While VirtueMart templates are different from each other, they actually follow a definite pattern. To understand how the template is structured, probably the best way is to look at a sample. Let's take a look at the file browse_1.tpl.php as an example. This is one of the core browse templates. The full text of this file is as follows (with line numbers added): 1. <?php if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) )die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );2. mm_showMyFileName(__FILE__);3. ?>4. <div class="browseProductContainer">5. <h3 class="browseProductTitle"><a title="<?php echo$product_name ?>" href="<?php echo $product_flypage ?>">6. <?php echo $product_name ?></a>7. </h3>8.9. <div class="browsePriceContainer">10. <?php echo $product_price ?>11. </div>12.13. <div class="browseProductImageContainer">14. <script type="text/javascript">//<![CDATA[15. document.write('<a href="javascript:void window.open('<?php echo $product_full_image ?>', 'win2', 'status=no,toolbar=no,scrollbars=yes,titlebar=no,menubar=no,resizable=yes,width=<?php echo $full_image_width ?>,height=<?php echo $full_image_height ?>,directories=no,location=no');">');16. document.write( '<?php echo ps_product::image_tag( $product_thumb_image, 'class="browseProductImage" border="0"title="'.$product_name.'" alt="'.$product_name .'"' ) ?></a>' );17. //]]>18. </script>19. <noscript>20. <a href="<?php echo $product_full_image ?>"target="_blank" title="<?php echo $product_name ?>">21. <?php echo ps_product::image_tag($product_thumb_image, 'class="browseProductImage" border="0"title="'.$product_name.'" alt="'.$product_name .'"' ) ?>22. </a>23. </noscript>24. </div>25.26. <div class="browseRatingContainer">27. <?php echo $product_rating ?>28. </div>29. <div class="browseProductDescription">30. <?php echo $product_s_desc ?>&nbsp;31. <a href="<?php echo $product_flypage ?>"title="<?php echo $product_details ?>"><br />32. <?php echo $product_details ?>...</a>33. </div>34. <br />35. <span class="browseAddToCartContainer">36. <?php echo $form_addtocart ?>37. </span>38.39. </div> Downloading the example code You can download the example code files here HTML fragments The coding is pretty typical of a VirtueMart template file. You can see that the template is basically an HTML fragment embedded with PHP coding. All PHP code is enclosed within the tag <?php … ?>. In most cases, the PHP code uses the statement echo $field_name to add the field value to the HTML code. We will be looking at those PHP constructs in the next subsection. After parsing the template, the output should be a well-formed HTML code. You should note that the template is just an HTML fragment, meaning no <html>, <head>, and <body> tags are needed. As you can recall, VirtueMart is just a Joomla! component that will handle the main content. So the HTML fragment produced by the template (together with other code, if any, built up by the page file) will be returned to the Joomla! engine for further processing. Typically, the Joomla! engine will pass this HTML fragment into the Joomla! template which, in turn, will insert the HTML into a location designated by the template. The final output of the Joomla! template will then be a valid HTML document. The <html>, <head>, and <body> tags will therefore be the responsibility of the Joomla! template. Let's look at the code to see how these 39 lines of code work. Remarks will only be needed for lines with the PHP tag. All the rest are HTML code that you should be familiar with. Lines 1 to 3 are actually some housekeeping code following the Joomla!/VirtueMart pattern. They will restrict direct access to the code and print out the template filename when debugging. Line 5 will output the product title with the product name embedded inside a hot link pointing to the product detail page. Line 10 will output the product price. Lines 14 to 23 contain a lengthy JavaScript code. The purpose is to output the image thumbnail embedded inside a hot link to open the full image. We need JavaScript here because we want to ensure the pop-up window size fits the full image size. (Otherwise, the pop-up window size will depend on the default size of the browser.) The window size cannot be controlled by HTML and so we need JavaScript help. If JavaScript is not enabled in a client browser, we will fall back to HTML code to handle the pop-up. Line 27 outputs the product rating, as reviewed by the user. Line 30 outputs the product's short description. Lines 31 to 33 outputs the text of product details within a hot link pointing to the product details page. Line 36 outputs the add-to-cart form, which includes the add-to-cart button, the quantity box, and so on. PHP crash course While we are not going to present all the complex program structure of PHP, it will be useful if we have a basic understanding of some of its major constructs. You may not fully understand what exactly each line of code does at first, but stick with us for a little while. You will soon grasp the concept as the pattern appears repeatedly in the exercise we will work on. In the preceding sample template, the PHP coding is pretty simple. (The most complex structure is actually the JavaScript that tries to spit out some HTML on the client browser, not PHP!) We can identify a few basic PHP constructs among the sample code: Variables: Just like any other programming language, a variable is a basic element in PHP. All PHP variables start with the dollar sign $. A variable name consists of alphanumeric characters and the underscore _ character. The first character must be either alphabetical or _, while numerals can also be used after the first character. It should be noted that the space character, together with most punctuation characters, are not allowed in a variable name. Alphabetic characters can be either uppercase or lowercase. Conventionally, VirtueMart will use only lowercase letters for variable names. While both uppercase and lowercase letters can be used without restrictions, variable names are case sensitive, meaning that $Product and $product will be treated as two different variables. The variable name chosen usually reflects the actual usage of the variable. In the sample template, $product_name and $product_flypage, for example, are typical variables and they will represent the value of a product name and product flypage, respectively. VirtueMart uses _ to separate words within a variable name to make the variable name more readable. Actually, many of the variables are passed into the template by the VirtueMart page file. These variables are called available fields. We will have more to say about that in the next subsection. Constants: Variables are changing values. You can assign a new value to it at any time and it will take up the new value. There are times when you want to keep the value unchanged. You can use a constant for that purpose. A constant name is pretty much the same as a variable name, but you don't need the $ character. In line 1 of the sample template, both _VALID_MOS and _JEXEC are constants. You probably recognize that they both use capital letters. This is conventional for Joomla! and VirtueMart so that constants stand out within the code. Constants are values that cannot be changed. If you try to give it another value, PHP will complain and fail. Data type: Any variable will have a data type associated with it. Data type can be a number, a string (that is, a series of characters or text), or other possibilities. Since the major purpose of a VirtueMart template is to produce HTML code, we will find that most of the variables we deal with are strings. Often, we will need to write out a literal string in our coding. To distinguish our string from the rest of the coding, we need to enclose the literal string with quotes. We can use single or double quotes. Single and double quotes actually have subtle differences, but we won't go into the detail for the time being. According to the VirtueMart program standard, a literal string should be enclosed in single quotes such as 'product name'. Note that 'product name' is a literal string containing the text product name. It is different from $product_name, which is a variable and may contain characters like 'circular saw' instead. Operators: You learnt addition and subtraction at school. They are mathematical operations to combine numbers. In PHP, we also have other operations to combine two or more variables. The most important one in our exercises is probably string concatenation, symbolized by . (the dot character). String concatenation combines two or more strings together to form a single string. The operation 'hello'.'world' will give a new string 'helloworld'. Note that there is no space character between the words. To make sure the words are separated by a space, we will need to use two concatenations such as 'hello'.' '.'world', which will give you the new string 'hello world'. Functions: Often, we will find that the same pattern of program code is used repeatedly to produce a given result. In PHP, we can group those code together to form a function. Each function will have a name and can be invoked using the following syntax: function_name (parameters) Here, parameters are values that will need to be passed into the function to evaluate the result. In PHP, we have lots of functions that deal with strings. The function strlen($product_name), for example, will return the number of characters in the string variable $product_name. If $product_name contains the string 'circular saw', strlen($product_name) will return 12. (You probably recognize that strlen is just a short form for string length.) We will learn some more functions along the way. echo statements: This is the most common statement in the template. echo is used to send the value of a string to the output buffer. So echo $product_name literally means "print out the value of the variable $product_name to the output buffer". Sometimes, the echo statement is mistaken to be a function. So you may try to write something like echo($product_name), instead of echo $product_name. While this is acceptable in PHP most of the time, the braces are actually not needed. (You may be aware that sometimes the command print function is used to send data to the output buffer in the place of echo. While print and echo seem interchangeable, echo runs faster than print and so should be the preferred choice to output data.) if statements: The if statement is a construct to test a condition before taking a certain action. The action will be taken only if the condition evaluates to true. The syntax of an if statement is as follows: if (condition) action where the condition is an expression for testing and action is a statement or a series of statements to be performed, if the expression evaluates to true. The expression can be a true-false type condition (such as $i>0), a mathematical expression (such as $i+$j), or some kind of complex operation involving functions. In any case, it will be considered as true, if it evaluates to a nonzero number or a non-empty string. Statement separator: One important PHP construct we usually overlook is the statement separator ; (the semicolon). We need this to separate two or more statements, even if they are on new lines of their own. In the preceding sample code, we have a ";" at the end of line 1 and 2. This ; is very important. Without that, the PHP parser will be confused and will probably refuse to execute and will give you a fatal error. These are just a few constructs in PHP for the time being. We will have more to say about PHP as we encounter more constructs along the way. Available fields Since many of the variables in our template code are passed down from the VirtueMart page file, one natural question to ask is "What variables can we use in our code?". Variables that we can use in a template are known as available fields. The available fields we have inside a template will vary with the template itself. A field which is available in the flypage template may not be available in a browse template. Even among the browse templates, there may be differences. To maximize our customization effort on a template, it is essential to be aware of the available fields in each template. However, there are so many available fields in a template that it may not be wise to list them all here. For now, it will be useful to distinguish four different types of available fields: Database fields: Most of the data we have comes from the database. Often, the VirtueMart page file just passes those fields directly to the template without changing anything. They are called database fields. The same data you put into the database from the backend will be at your fingertips. Examples are $product_id and $product_sku. Formatted database fields: Sometimes the data you stored in the database is raw data. You will need a different format in the presentation. VirtueMart will do some formatting on the data before passing it to the template. An example is $product_available_date, which is stored in the database as an integer. However, you need to display it in a form that is appropriate to your culture such as yyyy-mm-dd, mm-dd-yyyy, and so on. Processed data: Sometimes there may be complex logic before you can produce data that is useful in the template. A typical example is the $product_price. Do not expect this to be a simple number or a formatted number with the currency symbol added. Actually, the product price will depend on a number of factors such as whether the user has logged in, the shopper group, discount, tax, and so on. So the $product_price in the frontend may be different from the value you entered in the backend. Sometimes it is a formatted number and sometimes it is a message such as call for price. Another example is $product_thumb_image. You may expect this to be just the file location you see in the backend, but its value will depend on whether it is an out of site image, whether the image exists, and whether you want the image to be resized from the full image. VirtueMart class object: In certain cases, VirtueMart developers may think there are too many possibilities for the use of a piece of data. So they decided to let the template designer control what to do with the data. In those cases, VirtueMart will simply pass a class object to the template. An example of this is $ps_product. There are lots of opportunities to make good use of these class objects. However, you will need to understand how this can be properly used and bear all the complexities to make it work.   Core browse templates Product listing is unarguably the most important element on the product list page. There are two major factors that will affect the product listing: the product listing style, and the core browse template. Core browse templates are used to define the layout and styles for each product in the product list. There are actually six different core browse templates in the default theme. We can define a default core browse template for general use and also a specific template for each of the product categories. If you take a closer look at the templates, you will find that they are pretty much the same, except the last one which is for creating a PDF file. We already saw the detail coding in the browse_1.php. We don't need to repeat it here again. So, let's start on some exercises with the browse_1 template right away. Exercise 3.1: Adding an Ask-Seller link to the browse page We know that in the product detail page, there is an Ask-Seller link which will bring up a form so that a shopper can ask a question about the product. This link is not available on the product list page. In this exercise, we will add a similar link to the browse page. While we can use the exact same link here, we purposely use a simpler way to do it to make it easier to understand. Steps Open your favorite text editor. Navigate to the VirtueMart frontend root. Open the file themes/default/templates/browse/browse_1.php. Insert the following line of code after line 5: <a href="index.php?option=com_virtuemart&page=shop.ask&product_id=<?php echo $product_id ?>">Ask a question about thisproduct</a><br /> Save the file and upload it to your server. Point your browser to any VirtueMart browse page that uses the browse_1.php template, you should see the Ask-Seller link added to every product. (This exercise is done on the browse_1 template only. If you browse to the product list of an individual category, the new styles will show only if the category is using the browse_1 template. The same applies to most of the following exercises.) Notes The Ask-Seller link is an <a> tag with the href pointing to the Ask Seller page. The href is built using three parameters: option=com_virtuemart points to the VirtueMart component. page=shop.ask points to the actual Ask Seller page. By changing the page parameter, we can point the shopper to any of the VirtueMart pages. product_id=<? echo $product_id ?> provides the product ID to the Ask Seller page so that it knows which product the shopper has questions on. We need to use a variable because the product_id will vary from product to product. In the previous code, we purposely hardcoded the link as a relative URL to make the code simpler. This works unless SEF is enabled. To cater for SEF, a more generic way to create the link will be needed. The text Ask a question about this product is static text. Feel free to change it to anything you think appropriate. This will not affect the function of the link. <br /> is needed to insert a line break after the link. Exercise 3.1 demonstrates the basic technique to modify a template. You can add static text to a template in whatever way you want. If you need variable data, simply insert the appropriate echo statement at the required place.   Exercise 3.2: Changing core browse template CSS One major task of customizing a template is changing the style of HTML elements. In this exercise, we are going to add some CSS styles to the core browse template. Preparation This exercise is built upon the browse_1.php file we modified in Exercise 3.1. If you start from the original template file, the exact line number may differ. Steps Open your favorite text editor. Navigate to the VirtueMart frontend root. Open the file themes/default/templates/browse/browse_1.php. At line 4 (that is, the top of the file), insert the following lines of code: <?php if (!defined(VM_CUSTOM_CSS)) { define ('VM_CUSTOM_CSS',1);?> <style> .browseProductContainer {border:1px solid #999;padding:5px;background:#eee;margin:5px;} </style><?php } ?> Save the file and upload it to your server. Point your browser to any VirtueMart browse page that uses the browse_1.php template. You should see the product list now with the border, margin, and padding added. Notes We added a stylesheet for the class browseProductContainer in the template file. The stylesheet will be included as part of the HTML output to the browser. The core browse template will be applied for each product. So any coding added to it will be repeated for each product. To ensure that the stylesheet is included only once in the HTML, we define a constant named VM_CUSTOM_CSS the first time the stylesheet is included. The if condition at the start of the coding tests for the existence of the constant VM_CUSTOM_CSS. When the code is executed a second time, VM_CUSTOM_CSS is already defined and so the statements within the braces will be skipped. Exercise 3.2 demonstrates another basic technique to modify a template. The technique applies not only to a CSS stylesheet, but to all coding in general. It can be used for JavaScript inclusion, and for other coding that you only need to appear once in the HTML.   Exercise 3.3: Moving and modifying data In this exercise, we are going to experiment with moving data around and adding some new data fields that are available for the template. Preparation This exercise is built upon the browse_1.php file we modified in Exercise 3.2. If you start from the original template file, the exact line numbers may differ. Steps Open your favorite text editor. Navigate to the VirtueMart frontend root. Open the file themes/default/templates/browse/browse_1.php. At line 40, insert the following line of code: <br />Weight: <?php echo number_format($product_weight,1) .' ' . $product_weight_uom ?><br /> Move the Ask-Seller link from line 13 to line 47, that is, after the closing </span> tag for form_addtocart. Move the <br /> tag from the end of line 47 to the beginning of the line, that is, the line will become: <br /><a href="index.php?option=com_virtuemart&page=shop.ask&product_id=<?php echo $product_id ?>">Ask a question about thisproduct</a> Save the file and upload it to your server. Point your browser to any VirtueMart browse page that uses the browse_1.php template and you should see that the Ask-Seller link has moved to the end of the display, and the product weight and unit has been added to every product. Notes In this exercise, we have performed two modifications. We moved the Ask-Seller link to the bottom instead of the top and added the product_weight field to the browse template. Actually, the order of appearance of the product fields can be changed at will. You can move it around to fit your requirement similar way. To add new data to the display, you first need to determine what you want to show and whether the data is within the list of available fields. Since we know $product_weight and $product_weight_uom (uom stands for unit of measure) are available, we can simply use concatenation to build the final text for the output. The weight is rounded off to 1 decimal place using the number_format() function to make it look nicer. You can change the number of decimal places by changing the second parameter to the number_format() function.  
Read more
  • 0
  • 0
  • 3281
Modal Close icon
Modal Close icon