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-moodle-20-multimedia-creating-and-integrating-screencasts-and-videos
Packt
23 May 2011
8 min read
Save for later

Moodle 2.0 Multimedia: Creating and Integrating Screencasts and Videos

Packt
23 May 2011
8 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 Moodle 2.0 offers new features, which make it easier to insert videos, especially from the http://www.youtube.com website. You can find them easily from the file picker, provided you have administrative access to the course. You have to bear in mind that you need to be an administrator in order to enable this option. This article covers different ways to create and interact using either screencasts or videos. We will work with several multimedia assets, which will concern the baseline topic of Wildlife. This topic has many resources, which can be integrated with screencasts and videos available on the Web. Creating screencasts using several free and open source software available on the Web is one of the main goals of this chapter. There is plenty of commercial software, which can be used to create screencasts. We will not focus on them though. We add some special features to the screencasts in order to enhance them. Videos can be recorded in several ways. You may use your cell phone, camera, or the webcam of your computer. We are to focus on the way of creating them and uploading into our Moodle course. We can also use a recorded video from YouTube and upload it directly from the file picker in Moodle 2.0. You can also design a playlist in order to combine several videos and let your students watch them in a row. We do it by creating an account in YouTube. The channel in YouTube can be either public or private; it depends on how we want to carry it out. You can create some screencasts in order to present information to your students instead of showing presentations made using Open Office, PowerPoint, or Microsoft Word. Changing any of these into a screencast is more appealing to the students and not such a difficult task to carry out either. We can create an explanation by recording our voice, for which we will create a virtual board that we can choose to be visible to the audience; in the second case, our explanations can only be heard with no visualization. This is quite an important aspect to be taken into account, especially in teaching because students need a dynamic explanation by their teacher. There are several software available that can be used to create screencasts. One of them is Cam Studio. This software captures AVI files and it is open source. It captures onscreen video and audio. Its disadvantage is that only Windows users can use it. You can download it from http://camstudio.com/. It is time for Mac users. There is also a free program for Mac users that focuses on making quick films by saving the recorded video to get a quick access. It does not record audio. This is Copernicus and you can download it from http://danicsoft.com/software/copernicus/. We need a tool for both Mac and Windows, which is free and open source as well. So, JingProject.com is the software. It does not only record video, but also allows you to take a picture, draw, or add a message on it, and upload the media to a free hosting account. A URL is provided in order to watch the video or the image. You can download it from the following website: http://www.techsmith.com/download/jing/. Screencast-o-matic is another tool that is based on Java that does not need to be downloaded at all. It allows you to upload in an automatic way. It works well with both Mac and Windows machines. You can use this at http://www.screencast-o-matic.com/. This is the tool that we are to work with in the creation of a screencast. We may also modify the videos to make them suitable for learning. We can add annotations in different ways so as to interact through the video with our students. That is to say, we add our comments instead of adding our voice so that students read what we need to tell them. Creating a screencast In this recipe, we create a screencast and upload it to our Moodle course. The baseline topic is Wildlife. Therefore, in this recipe, we will explain to our students where wild animals are located. We can paste in a world map of the different animals, while we add extra data through the audio files. Thus, we can also add more information using different types of images that are inserted in the map. Getting ready Before creating the screencast, plan the whole sequence of the explanation that we want to show to our students, therefore, we will use a very useful Java applet available at http://www.screencast-o-matic.com/. Screencast-o-matic requires the free Java Run-time Environment (also known as JRE) for both the teacher and the students' computers. You can download and install its latest version from http://java.sun.com. How to do it... First of all, design the background scene of the screencast to work with. Afterwards, enter the website http://www.screencast-o-matic.com/. Follow these to create the screencast: Click on Start recording. Another pop-up window appears that looks as shown in the following screenshot: Resize the frame to surround the recording area that you want to record. Click on the recording button (red button). If you want to make a pause, click on the pause button or Alt + P, as shown in the following screenshot: If you want to integrate the webcam or a bluetooth video, click on the upwards arrow in this icon, as shown in the following screenshot: When the screencast is finished, click on Done. You can preview the screencast after you finish designing it. If you need to edit it, click on Go back to add more. If you are satisfied with the preview, click on Done with this screencast, as shown in the following screenshot: When the screencast is finished, our next task is to export it because we need to upload it to our Moodle course. Click on Export Movie. Click on the downwards arrow in Type and choose Flash (FLV), as shown in the following screenshot: Customize the Size and Options blocks, as shown in the previous screenshot or as you wish. When you finish, click on Export, as shown in the previous screenshot. Write a name for this file and click on Save. When the file is exported, click on Go back and do more with this screencast if you want to edit it. Click on Done with this screencast if you are satisfied with the result. A pop-up window appears, click on OK. How it works... We have just created the screencast teaching about wild animals, which students have to watch to learn about the places where wild animals live around the world. We need to upload it to our Moodle course. It is a passive resource; therefore, we can add a resource or design an activity out of it. In this case, we design an activity. Choose the weekly outline section where you want to insert it, and follow these steps: Click on Add an activity | Online text within Assignments. Complete the Assignment name and Description blocks. Click on the Moodle Media icon | Find or upload a sound, video or applet ... | Upload a file | Browse | look for the file that you want to upload and click on it. Click on Open | Upload this file | Insert. Click on Save and return to course. Click on the activity. It looks as shown in the following screenshot: There's more... In the case that we create a screencast, which lasts for around 30 minutes or longer, it will take a long time to upload it to our Moodle course. Therefore, it will be advisable to watch the screencast using a free and open source media player, that is to say VLC Media Player. VLC Media Player You can download the VLC Media Player from the following website: http://www.videolan.org/vlc/. It works with most popular video files formats such as AVI, MP4, and Flash, among others. Follow these steps in order to watch the screencast: Click on Media | Open File | browse for the file that you want to open and click on it. Click on Open. The screencast is displayed, as shown in the following screenshot: See also Enhancing a screencast with annotations  
Read more
  • 0
  • 0
  • 4430

article-image-getting-started-internet-explorer-mobile
Packt
23 May 2011
13 min read
Save for later

Getting Started with Internet Explorer Mobile

Packt
23 May 2011
13 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 To get started with Internet Explorer Mobile let's look at basic web page architecture.   Web page architecture Web pages on the client side mainly consist of three vital components: HTML, CSS, and JavaScript. The exact version of each of these varies, but in the end it all comes down to these three pieces. HyperText Markup Language (HTML) HyperText Markup Language (HTML) is the container for the page content. The page should contain just that content and nothing else. A properly coded site would leave the presentation and functionality portions of the page to CSS and JavaScript. In addition, the content should be constructed in a manner that makes logical sense for the content that is being delivered. This is called semantic HTML. People with disabilities use devices, such as a screen reader, to get the content of a site. These screen readers can only gather information from the actual markup of the site. If we have a PNG image with text in it, the screen reader cannot "see" that information. In that particular case, we can use the alt attribute of the image to provide a hint to the content, but it would be better to put the content inside a paragraph, unordered list, or some other textual tag and then replace it with an image if absolutely required using JavaScript. The other case that was mentioned earlier was that search engines can better determine the contents of a web page with semantic markup. This will help our page rankings and hopefully drive more visitors to our site. Think about the HTML markup like the script of a movie. Although we'll add lights, actors, and probably special effects later, right now the black and white text on paper has to convey all of the meaning. The same is true of the HTML markup for your site. As you build websites, constantly keep in mind what information you are trying to impart with the page and make that the focus. Cascading Style Sheets (CSS) Cascading Style Sheets (CSS) are documents that describe the way HTML should be displayed. The CSS language allows the web developer to separate the design aspects (layout, colors, fonts, and so on) from the page content. One could easily change the entire look and feel of a page simply by replacing the CSS files. An amazing group of examples of this is available at http://csszengarden.com. The CSS Zen Garden website demonstrates the amazing power that CSS has on the presentation of HTML content. Utilizing a proper style sheet can result in content that will quickly display the relevant information that a Windows Phone 7 user has come to expect from the applications on the phone. When developing websites that are going to be viewed on Internet Explorer Mobile, it is important to keep in mind some very important potential problems. Although float works great on desktop browsers and will work on many mobile browsers, the content within these containers may not look good on a small screen. The CSS float attribute was one of the first tools that allowed web developers to break free from table based layouts, that is, laying out the contents of a page using tables. Float allowed developers to group content in div elements and then float those block elements into position. It is a very powerful tool, but on a mobile device, the limited screen size would hamper the ability for the user to view the content. Instead, they would be constantly scrolling left and right or up and down to find all the content. A better way of handling this would be to utilize float on the desktop version of the site and then leave the div elements in block display allowing the IE Mobile browser to handle the content layout. Along these same lines, the CSS attributes, padding and margin, work great for precise positioning of elements on a desktop browser. However, the limited screen real-estate of a Mobile browser limits the usefulness of this positioning power. Try to limit the use of these attributes on the mobile device and only use them to highlight useful information. Finally, because pixels are absolute values, a pixel is a precise defined scale of measurement with no room for interpretation; the phone has to work more to display those elements that are positioned using pixel measurements. Using points, em, or percentage measurements instead, allow the phone to be more fluid with the layout. Be sure to test the site on Windows Phone 7 devices to ensure the content is legible and the display is fine. JavaScript JavaScript, otherwise known as ECMAScript, is the scripting language that is used to create dynamic user interfaces and allow a page to update "on the fly". Users have come to expect a certain fluidity to their web experiences, and now with the power of Internet Explorer Mobile for Windows Phone 7, they can have that same power in the palm of their hand. Remember that the user is probably looking at a 3.5 inch screen, has fingers that are roughly 40-80 pixels square, and those fingers are incapable of registering a hover command to the browser. If your navigation, for example, requires the user to hover over something, this will not work in Internet Explorer Mobile. Instead, make the navigation an easy to use, unordered list of hyperlinks Putting HTML, CSS, and JavaScript together Windows Phone 7 is about getting the relevant information viewable with minimal fuss. The following are some tips for creating a website for Windows Phone 7's Internet Explorer Mobile: Show only the content that is relevant for the page requested Reduce the use of images and colors Remove the extra-large hero images Hero images are those large images usually at the top of the main content section, but usually used as a graphic headline. Usually, they don't contain any content and only serve to enhance the design of the site. Rearrange the navigation to take up a minimum amount of space Move the navigation to the bottom of the page if possible Remove flashy loading screens Utilizing HTML, CSS, and JavaScript with proper discipline will result in more satisfied customers. Developing websites is not a trivial task. Mastering each of these three components is a great task. It is important, while developing websites, to try and minimize as much duplication as possible, not only in the JavaScript code that so many developers tended to focus on, but also in the CSS and the HTML content. Reducing duplication will allow for maintainable, upgradable, and understandable code. Also, by reducing duplication, the amount of data sent to the browser is also reduced. This is helpful when dealing with a browser that is connecting from a patchy cellular network. Historically, building a mobile version of a website meant a completely different team of designers and web developers built a totally separate web application from the desktop version of the site. Then, using the server side code, the mobile browsers were detected and redirected to the mobile version. SharePoint does this by redirecting mobile browsers to {server}/_layout/mobile/mblwiki.aspx?Url=%2FSitePages%2FHome%2Easpx as an example. When starting a new web application, a general rule of thumb is to use content adaptation techniques for the application. However, for a baseline you must have at least: ECMAScript 3 W3C DOM Level 1 W3C standard box model support CSS2 rendering Client-side cookies support XMLHttpRequest object support By targeting this lowest common denominator of browser, we will ensure that our web applications will run well on most browsers on the web. Remember that common practices on desktop browsers may end up being annoyances on a mobile device. Try not to open modal dialog boxes, or even open pop-ups. Opening a pop-up window will cause a whole new tab to appear. This may even close a tab that the user had previously opened if they already had six tabs open. When designing the user interaction for a website, always keep the user in mind. They are busy people coming to your website. Be kind to them. Give them the information they are looking for without hassle.   Internet Explorer Mobile Windows Phone 7 comes with a new browser that is based on the rendering engine of Internet Explorer 7 and some JavaScript improvements from Internet Explorer 8. Additionally, it includes some enhancements that aren't found in either of those desktop browsers. Internet Explorer Mobile User Agent The Internet Explorer Mobile User Agent string is as follows: Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0; <DeviceManufacturer>; <DeviceModel>) This UA String allows the device manufacturer to insert their name and the model of the phone in the string. Knowing the User Agent string is helpful when reviewing server logs to determine what browsers are coming to your website. This will help you optimize your site for the people who actually are viewing your content. Like previous versions of Internet Explorer Mobile, the user can select either a Mobile version or a Desktop version display engine. When the Desktop version is selected, the User Agent string changes to the following: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; XBLWP7; ZuneWP7) Changing the display engine mode can be accomplished on the Internet Explorer SETTINGS screen, as shown in the following screenshot: Although this choice could complicate things, as we develop our sites, we should make careful consideration of how we are going to treat the mobile version, but try not to detect the desktop version. If the user makes a conscious choice to view the desktop version, we should not force them to view something different from what they would see on a real desktop browser. Client side browser detection Many people use the user agent string to detect at runtime what to display on the browser. Although this works, there are better techniques to find out if the browser is mobile. Those techniques should be used instead of User Agent detection. Using property detection instead of browser detection will allow your site to be forward compatible. Forward compatibility isn't a very complex idea. It is just thinking about programming so that as new browsers come along with new capabilities, we won't have to rewrite our applications to take advantage of these capabilities. The application just takes advantage of whatever functionality is available to it in whatever browser in which it is currently running. An example of property detection is as follows: function hasAdvancedDOM() { // check for a feature that is known to be advanced if(document.getElementsByClassName) return true; return false } Downloading the example code You can download the example code files from here The preceding code simply detects if the DOM function document.getElementsByClassName() exists or not. Internet Explorer Mobile has this function, as does Firefox 2+, Safari, Chrome, and Internet Explorer 9. However, previous versions of Internet Explorer Mobile did not have this function. If we had this in a previous version of a website, we wouldn't have to do anything special to get this to work in Windows Phone 7's Internet Explorer Mobile. Although, the code we would actually write in a web page would be much more complicated, this example demonstrates a starting point. Server-side detection Server-side detection usually uses the User Agent string along with a large list of mobile device User Agent strings to determine the capabilities of the browsers requesting a page. This list of mobile devices and their capabilities are kept in a .browser file. There are some projects on the web to keep and maintain this .browser file. The best known of these, "Mobile Device Browser File", available at http://mdbf.codeplex.com, lost funding from Microsoft. There is another one that can be found at http://aspnet.codeplex.com/releases/view/41420. The main topic of this article is SharePoint 2010 development for Windows Phone 7. However, ASP.NET 3.5 SP1 is the framework that SharePoint 2010 development is based on. This framework has a smaller list of browsers in the .browser file than the more current ASP.NET 4. One of the omissions is IEMobile. What this means is that in ASP.NET 4, you can use the following code to detect a mobile browser: Request.Browser.IsMobileDevice This code will work in ASP.NET 3.5 SP1, but it will not return true for Windows Phone 7's Internet Explorer Mobile by default. The simplest solution is to use code like this to detect the IE Mobile browser: Request.UserAgent.ToString().Contains("IEMobile") We could probably do better here. In the first place, we could update SharePoint's compat.browser file to include Windows Phone 7. The compat.browser can be found here: <drive>:inetpubwwwrootwssVirtualDirectories<site>80App_Browserscompat.browser The structure of this file can be found at the following URL: http://msdn.microsoft.com/en-us/library/ms228122.aspx If you look at SharePoint's compat.browser file, the fourth browser listed looks like it might be for the Windows Phone 7 Internet Explorer Mobile. However, a closer examination will show that this browser is actually for the Office Hub in Windows Phone 7. To add the Internet Explorer Mobile browser, copy the browser elements for Internet Explorer Mobile for Windows Mobile 6.5 and edit it like this: <browser id="IE7MobileDesktopMode" parentID="IE6to9"> <identification> <userAgent match="XBLWP7" /> </identification> <capabilities> <capability name="supportsTouchScreen" value="true" /> </capabilities> </browser> <browser id=”IE7MobileMobileMode” parentID=”Mozilla”> <identification> <userAgent match="(?i)Windows Mobile OSs7.d.*IEMobile/ (?'version'd+).(?'minor'd+)" /> </identification> <capabilities> <capability name="browser" value="IE Mobile" /> <capability name="canInitiateVoiceCall" value="true" /> <capability name="isMobileDevice" value="true" /> <capability name="javascript" value="true" /> <capability name="optimumPageWeight" value="1500" /> <capability name="tables" value="true" /> <capability name="version" value="${version}" /> <capability name="supportsTouchScreen" value="true" /> </capabilities> </browser> This will make our code easier to manage later by allowing us to use the Request.Browser.IsMobileDevice property. The change here, besides changing the browser ID, is in the regular expression which is used to detect the browser. In the desktop mode, we look for the text, XBLWP7, as this is a very obvious change in the User Agent in this state. For the mobile mode, we copied the IE Mobile 6 plus browser section. Microsoft changed the User Agent slightly between IE Mobile 6 and IE Mobile 7. The change comes in the User Agent, IE Mobile 7 doesn't have a space between the browser name IEMobile and the start of the version number. Instead, it has a forward slash. IE Mobile 6 had a space between the browser name and the version number.  
Read more
  • 0
  • 0
  • 2521

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

HTML5: Developing Rich Media Applications using Canvas

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

article-image-python-3-building-wiki-application
Packt
19 May 2011
17 min read
Save for later

Python 3: Building a Wiki Application

Packt
19 May 2011
17 min read
Python 3 Web Development Beginner's Guide Nowadays, a wiki is a well-known tool to enable people to maintain a body of knowledge in a cooperative way. Wikipedia (http://wikipedia.org) might be the most famous example of a wiki today, but countless numbers of forums use some sort of wiki and many tools and libraries exist to implement a wiki application. In this article, we will develop a wiki of our own, and in doing so, we will focus on two important concepts in building web applications. The first one is the design of the data layer. The second one is input validation. A wiki is normally a very public application that might not even employ a basic authentication scheme to identify users. This makes contributing to a wiki very simple, yet also makes a wiki vulnerable in the sense that anyone can put anything on a wiki page. It's therefore a good idea to verify the content of any submitted change. You may, for example, strip out any HTML markup or disallow external links. Enhancing user interactions in a meaningful way is often closely related with input validation. Client-side input validation helps prevent the user from entering unwanted input and is therefore a valuable addition to any application but is not a substitute for server-side input validation as we cannot trust the outside world not to try and access our server in unintended ways. The data layer A wiki consists of quite a number of distinct entities we can indentify. We will implement these entities and the relations that exist between them by reusing the Entity/Relation framework developed earlier. Time for action – designing the wiki data model As with any application, when we start developing our wiki application we must first take a few steps to create a data model that can act as a starting point for the development: Identify each entity that plays a role in the application. This might depend on the requirements. For example, because we want the user to be able to change the title of a topic and we want to archive revisions of the content, we define separate Topic and Page entities. Identify direct relations between entities. Our decision to define separate Topic and Page entities imply a relation between them, but there are more relations that can be identified, for example, between Topic and Tag. Do not specify indirect relations: All topics marked with the same tag are in a sense related, but in general, it is not necessary to record these indirect relations as they can easily be inferred from the recorded relation between topics and tags. The image shows the different entities and relations we can identify in our wiki application. In the diagram, we have illustrated the fact that a Topic may have more than one Page while a Page refers to a single User in a rather informal way by representing Page as a stack of rectangles and User as a single rectangle. In this manner, we can grasp the most relevant aspects of the relations at a glance. When we want to show more relations or relations with different characteristics, it might be a good idea to use more formal methods and tools. A good starting point is the Wikipedia entry on UML: http://en.wikipedia.org/wiki/Unified_Modelling_Language. What just happened? With the entities and relations in our data model identified, we can have a look at their specific qualities. The basic entity in a wiki is a Topic. A topic, in this context, is basically a title that describes what this topic is about. A topic has any number of associated Pages. Each instance of a Page represents a revision; the most recent revision is the current version of a topic. Each time a topic is edited, a new revision is stored in the database. This way, we can simply revert to an earlier version if we made a mistake or compare the contents of two revisions. To simplify identifying revisions, each revision has a modification date. We also maintain a relation between the Page and the User that modified that Page. In the wiki application that we will develop, it is also possible to associate any number of tags with a topic. A Tag entity consists simply of a tag attribute. The important part is the relation that exists between the Topic entity and the Tag entity. Like a Tag, a Word entity consists of a single attribute. Again, the important bit is the relation, this time, between a Topic and any number of Words. We will maintain this relation to reflect the words used in the current versions (that is, the last revision of a Page) of a Topic. This will allow for fairly responsive full text search facilities. The final entity we encounter is the Image entity. We will use this to store images alongside the pages with text. We do not define any relation between topics and images. Images might be referred to in the text of the topic, but besides this textual reference, we do not maintain a formal relation. If we would like to maintain such a relation, we would be forced to scan for image references each time a new revision of a page was stored, and probably we would need to signal something if a reference attempt was made to a non-existing image. In this case, we choose to ignore this: references to images that do not exist in the database will simply show nothing: Chapter6/wikidb.py from entity import Entity from relation import Relation class User(Entity): pass class Topic(Entity): pass class Page(Entity): pass class Tag(Entity): pass class Word(Entity): pass class Image(Entity): pass class UserPage(Relation): pass class TopicPage(Relation): pass class TopicTag(Relation): pass class ImagePage(Relation): pass class TopicWord(Relation): pass def threadinit(db): User.threadinit(db) Topic.threadinit(db) Page.threadinit(db) Tag.threadinit(db) Word.threadinit(db) Image.threadinit(db) UserPage.threadinit(db) TopicPage.threadinit(db) TopicTag.threadinit(db) ImagePage.threadinit(db) TopicWord.threadinit(db) def inittable(): User.inittable(userid="unique not null") Topic.inittable(title="unique not null") Page.inittable(content="", modified="not null default CURRENT_TIMESTAMP") Tag.inittable(tag="unique not null") Word.inittable(word="unique not null") Image.inittable(type="",data="blob",title="", modified="not null default CURRENT_TIMESTAMP", description="") UserPage.inittable(User,Page) TopicPage.inittable(Topic,Page) TopicTag.inittable(Topic,Tag) TopicWord.inittable(Topic,Word) Because we can reuse the entity and relation modules we developed earlier, the actual implementation of the database layer is straightforward (full code is available as wikidb.py). After importing both modules, we first define a subclass of Entity for each entity we identified in our data model. All these classes are used as is, so they have only a pass statement as their body. Likewise, we define a subclass of Relation for each relation we need to implement in our wiki application. All these Entity and Relation subclasses still need the initialization code to be called once each time the application starts and that is where the convenience function initdb() comes in. It bundles the initialization code for each entity and relation (highlighted). Many entities we define here are simple but a few warrant a closer inspection. The Page entity contains a modified column that has a non null constraint. It also has a default: CURRENT_TIMESTAMP (highlighted). This default is SQLite specific (other database engines will have other ways of specifying such a default) and will initialize the modified column to the current date and time if we create a new Page record without explicitly setting a value. The Image entity also has a definition that is a little bit different: its data column is explicitly defined to have a blob affinity. This will enable us to store binary data without any problem in this table, something we need to store and retrieve the binary data contained in an image. Of course, SQLite will happily store anything we pass it in this column, but if we pass it an array of bytes (not a string that is), that array is stored as is. The delivery layer With the foundation, that is, the data layer in place, we build on it when we develop the delivery layer. Between the delivery layer and the database layer, there is an additional layer that encapsulates the domain-specific knowledge (that is, it knows how to verify that the title of a new Topic entity conforms to the requirements we set for it before it stores it in the database): Each different layer in our application is implemented in its own file or files. It is easy to get confused, so before we delve further into these files, have a look at the following table. It lists the different files that together make up the wiki application and refers to the names of the layers. We'll focus on the main CherryPy application first to get a feel for the behavior of the application. Time for action – implementing the opening screen The opening screen of the wiki application shows a list of all defined topics on the right and several ways to locate topics on the left. Note that it still looks quite rough because, at this point, we haven't applied any style sheets: Let us first take a few steps to identify the underlying structure. This structure is what we would like to represent in the HTML markup: Identify related pieces of information that are grouped together. These form the backbone of a structured web page. In this case, the search features on the left form a group of elements distinct from the list of topics on the right. Identify distinct pieces of functionality within these larger groups. For example, the elements (input field and search button) that together make up the word search are such a piece of functionality, as are the tag search and the tag cloud. Try to identify any hidden functionality, that is, necessary pieces of information that will have to be part of the HTML markup, but are not directly visible on a page. In our case, we have links to the jQuery and JQuery UI JavaScript libraries and links to CSS style sheets. Identifying these distinct pieces will not only help to put together HTML markup that reflects the structure of a page, but also help to identify necessary functionality in the delivery layer because each of these functional pieces is concerned with specific information processed and produced by the server. What just happened? Let us look in somewhat more detail at the structure of the opening page that we identified. Most notable are three search input fields to locate topics based on words occurring in their bodies, based on their actual title or based on tags associated with a topic. These search fields feature auto complete functionality that allows for comma-separated lists. In the same column, there is also room for a tag cloud, an alphabetical list of tags with font sizes dependent on the number of topics marked with that tag. The structural components The HTML markup for this opening page is shown next. It is available as the file basepage.html and the contents of this file are served by several methods in the Wiki class implementing the delivery layer, each with a suitable content segment. Also, some of the content will be filled in by AJAX calls, as we will see in a moment: Chapter6/basepage.html <html> <head> <title>Wiki</title> <script src= "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"> </script> <script src= "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.3/jquery-ui.min.js" type="text/javascript"> </script> <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/ jqueryui/1.8.3/themes/smoothness/jquery-ui.css" type="text/css" media="all" /> <link rel="stylesheet" href="/wiki.css" type="text/css" media="all" /> </head> <body> <div id="navigation"> <div class="navitem"> <a href="./">Wiki Home</a> </div> <div class="navitem"> <span class="label">Search topic</span> <form id="topicsearch"> <input type="text" > <button type="submit" >Search</button> </form> </div> <div class="navitem"> <span class="label">Search word</span> <form id="wordsearch"> <input type="text" > <button type="submit" >Search</button> </form> </div> <div class="navitem"> <span class="label">Search tag</span> <form id="tagsearch"> <input type="text" > <button type="submit" >Search</button> </form> </div> <div class="navitem"> <p id="tagcloud">Tag cloud</p> </div> </div> <div id="content">%s</div> <script src="/wikiweb.js" type="text/javascript"></script> </body> </html> The <head> element contains both links to CSS style sheets and <script> elements that refer to the jQuery libraries. This time, we choose again to retrieve these libraries from a public content delivery network. The highlighted lines show the top-level <div> elements that define the structure of the page. In this case, we have identified a navigation part and a content part and this is reflected in the HTML markup. Enclosed in the navigation part are the search functions, each in their own <div> element. The content part contains just an interpolation placeholder %s for now, that will be filled in by the method that serves this markup. Just before the end of the body of the markup is a final <script> element that refers to a JavaScript file that will perform actions specific to our application and we will examine those later. The application methods The markup from the previous section is served by methods of the Wiki class, an instance of which class can be mounted as a CherryPy application. The index() method, for example, is where we produce the markup for the opening screen (the complete file is available as wikiweb.py and contains several other methods that we will examine in the following sections): Chapter6/wikiweb.py @cherrypy.expose def index(self): item = '<li><a href="show?topic=%s">%s</a></li>' topiclist = "n".join( [item%(t,t)for t in wiki.gettopiclist()]) content = '<div id="wikihome"><ul>%s</ul></div>'%( topiclist,) return basepage % content First, we define the markup for every topic we will display in the main area of the opening page (highlighted). The markup consists of a list item that contains an anchor element that refers to a URL relative to the page showing the opening screen. Using relative URLs allows us to mount the class that implements this part of the application anywhere in the tree that serves the CherryPy application. The show() method that will serve this URL takes a topic parameter whose value is interpolated in the next line for each topic that is present in the database. The result is joined to a single string that is interpolated into yet another string that encapsulates all the list items we just generated in an unordered list (a <ul> element in the markup) and this is finally returned as the interpolated content of the basepage variable. In the definition of the index() method, we see a pattern that will be repeated often in the wiki application: methods in the delivery layer, like index(), concern themselves with constructing and serving markup to the client and delegate the actual retrieval of information to a module that knows all about the wiki itself. Here the list of topics is produced by the wiki.gettopiclist() function, while index() converts this information to markup. Separation of these activities helps to keep the code readable and therefore maintainable. Time for action – implementing a wiki topic screen When we request a URL of the form show?topic=value, this will result in calling the show() method. If value equals an existing topic, the following (as yet unstyled) screen is the result: Just as for the opening screen, we take steps to: Identify the main areas on screen Identify specific functionality Identify any hidden functionality The page structure is very similar to the opening screen, with the same navigational items, but instead of a list of topics, we see the content of the requested topic together with some additional information like the tags associated with this subject and a button that may be clicked to edit the contents of this topic. After all, collaboratively editing content is what a Wiki is all about. We deliberately made the choice not to refresh the contents of just a part of the opening screen with an AJAX call, but opted instead for a simple link that replaces the whole page. This way, there will be an unambiguous URL in the address bar of the browser that will point at the topic. This allows for easy bookmarking. An AJAX call would have left the URL of the opening screen that is visible in the address bar of the browser unaltered and although there are ways to alleviate this problem, we settle for this simple solution here. What just happened? As the main structure we identified is almost identical to the one for the opening page, the show() method will reuse the markup in basepage.html. Chapter6/wikiweb.py @cherrypy.expose def show(self,topic): topic = topic.capitalize() currentcontent,tags = wiki.gettopic(topic) currentcontent = "".join(wiki.render(currentcontent)) tags = ['<li><a href="searchtags?tags=%s">%s</a></li>'%( t,t) for t in tags] content = ''' <div> <h1>%s</h1><a href="edit?topic=%s">Edit</a> </div> <div id="wikitopic">%s</div> <div id="wikitags"><ul>%s</ul></div> <div id="revisions">revisions</div> ''' % ( topic, topic, currentcontent,"n".join(tags)) return basepage % content The show() method delegates most of the work to the wiki.gettopic() method (highlighted) that we will examine in the next section and concentrates on creating the markup it will deliver to the client. wiki.gettopic() will return a tuple that consists of both the current content of the topic and a list of tags. Those tags are converted to <li> elements with anchors that point to the searchtags URL. This list of tags provides a simple way for the reader to find related topics with a single click. The searchtags URL takes a tags argument so a single <li> element constructed this way may look like this: <li><a href="searchtags?tags=Python">Python</a></li>. The content and the clickable list of tags are embedded in the markup of the basepage together with an anchor that points to the edit URL. Later, we will style this anchor to look like a button and when the user clicks it, it will present a page where the content may be edited.  
Read more
  • 0
  • 0
  • 22449

article-image-installation-silverstripe-24
Packt
13 May 2011
11 min read
Save for later

Installation of SilverStripe 2.4

Packt
13 May 2011
11 min read
  SilverStripe 2.4 Module Extension, Themes, and Widgets: Beginner's Guide Create smashing SilverStripe applications by extending modules, creating themes, and adding widgets         Read more about this book       (For more resources on SilverStripe, see here.) Setting up the environment There are many possible scenarios and environments you might require, depending on the complexity of your project. However, we'll keep this short and simple: We'll set up a development environment, which is based on Windows (Windows XP or newer) as it is the most common operating system on desktops and laptops. We'll also set up one live or deployment environment, which is based on Linux as it is the most common operating system for web servers. We'll use Ubuntu in our example as it is freely available and widely used. If you prefer a different distribution some paths and commands will vary, but the general approach should be very similar. In case you want to use a testing or staging environment as well, we'll assume that you simply reuse the previous setup—so we don't need to configure another system. Now that we've decided on the general purpose of the systems and their operating systems, we'll need to choose between different implementations for setting up the web server and database. Specifically, whether to use prebuilt packages or select the components ourselves. To demonstrate both approaches we'll use a prebuilt package on our development machine (as we want to get up and running quickly) and handpick the components on our live site, where we want to have maximum control. To keep our development and live environments closely related, we'll use the same applications for both—disqualifying Windows-only solutions: For the web server we'll use the Apache HTTP Server (http://httpd.apache.org) as it's the most widely used, cross-platform server. Alternatives would be Microsoft's Internet Information Services (http://www.iis.net), which are only available on Windows, and Lighttpd (http://www.lighttpd.net) or Nginx (http://nginx.org), which are both fast, but not as widely used as the Apache web server, and are a little trickier to set up. For the database we'll use the popular MySQL (http://www.mysql.com). Alternatively you could use Microsoft SQL Server (https://www.microsoft.com/sqlserver/2008/en/us/default.aspx), which requires Windows; PostgreSQL (http://www.postgresql.org), SQLite (http://www.sqlite.org), or an Oracle database (http://www.oracle.com/us/products/database/index.html). However, each of these alternatives requires an additional SilverStripe module to support its specific SQL dialect, which generally receive less attention than MySQL. Unless you have a good reason for changing the database, like you're already using MS SQL for everything else, stick with MySQL. For a change the programming language PHP (http://www.php.net) doesn't require any decisions as there are no alternative implementations. For the prebuilt package we'll use XAMPP (http://www.apachefriends.org/en/xampp.html), which matches our requirements. It uses the Apache HTTP Server and MySQL and is available on Windows, Linux, Mac OS X, and Solaris. If your development machine doesn't use Windows, you should still be able to follow the installation steps with minor variations. On Windows there's also Microsoft's Web Platform Installer (http://www.microsoft.com/web/downloads/platform.aspx). It doesn't only include the web server, database and PHP, but also SilverStripe itself (http://www.microsoft.com/web/gallery/silverstripecms.aspx)—which can be downloaded on demand among many other web applications. However, as this is very different to our live site, we won't cover it. If you're looking for a, Windows-only solution this is nevertheless an interesting option as it is very easy to set up. The Windows development system Let's start off by setting up our development system, based on the freely available XAMPP package. Time for action - installing XAMPP We'll assume that the operating system is Windows XP or newer—for Linux, Mac OS X, and Solaris you should only need to get a different download file and do some minor variations of the steps described: Download the XAMPP package at http://www.apachefriends.org/en/xampp-windows.html. We're using the 7zip package as it doesn't require an installation, is compact to download and also portable: you can copy it to a USB drive and use the environment on any Windows computer. Extract the archive to a top-level folder on your internal drive (C: for example), or your portable external drive (U: for example). To do this, you'll need the free 7zip archive utility, which you can download at http://www.7-zip.org. Open up the file xampp/mysql/bin/my.ini and add the following line in the [mysqld] section: lower_case_table_names=2 This setting is important for exchanging database dumps between Windows and Linux systems. As Windows paths are case insensitive, MySQL lowercases database and table names by default (as they are internally stored as folders and files), but only on Windows. On Linux proper cases are preserved, which leads to problems when using dumps on different platforms. The previous statement forces MySQL on Windows to behave like on Linux. Inside the XAMPP folder, start the file xampp-control.exe and use it to Start Apache, MySql and Mercury. XAMPP's control panel should look like this after starting the three applications: If a service doesn't start, check that its port is not already in use—this is the main reason for problems. To do this, open the command line tool and enter netstat-ao. This will show you the ports currently in use and the process IDs (PIDs) of the processes using them. Using Window's Task-Manager you can then find out the name of the process causing the problem, and stop or reconfigure it. The following screenshot illustrates this scenario—the web server cannot be started as Skype is already using port 80: After successfully starting all three services, navigate to http://localhost in your browser. This should redirect you to XAMPP's welcome page. In case you need to send e-mails for testing purposes, you'll need to perform two additional steps to configure your SMTP server: Enable SMTP relaying of non-local mail. However, ensure that no one can access your mail server from outside or you might be abused as a spam relay (your router or firewall will protect you). In XAMPP's control panel, click on Admin... next to the Mercury label. Next go to Configuration, MercuryS SMTP Server and on the Connection control tab uncheck Do not permit SMTP relaying of non-local mail. Provide a DNS server so domain names can be looked up: Under Configuration, MercuryE SMTP Client fill in the field Name server with your provider's DNS server. That's it for our general purpose development machine. In case you want to run automatic tests or generate translation files, you'll also need to install PHPUnit through PEAR: While XAMPP includes PEAR and PHPUnit, the bundled versions are hopelessly outdated. Furthermore the update process doesn't work reliably, so we'll better start anew. First remove xampp/php/PEAR/, xampp/php/pear.bat, xampp/php/pear.ini, xampp/php/peardev.bat and xampp/php/pear-update.bat. Next enable PHP's cURL extension: Open xampp/php/php.ini, find the line ;extension=php_curl.dll and remove the leading semicolon. Then download http://pear.php.net/go-pear.phar into xampp/php/. Next install PEAR on the command line (start it as an admin user). Note that you must be in the folder xampp/php/ for the following commands to work: php go-pear.phar Now we can use PEAR to update its channels and upgrade all packages: pear update-channelspear upgrade --alldeps Finally you can install PHPUnit and all of its dependencies: pear channel-discover pear.phpunit.depear channel-discover components.ez.nopear channel-discover pear.symfony-project.compear install phpunit/PHPUnit That's it, you've successfully installed PHPUnit! The Linux live system Next we'll set up our live system. Thanks to package managers this isn't much harder—you just shouldn't be afraid of the shell. Time for action - installing the requirements by hand In our example we're using Ubuntu, so we'll rely on its package manager Apt, abbreviation of Advanced Package Tool. Note that we won't only install the bare necessities, but also some more tools to make our system ready for production. Open the terminal and install the Apache HTTP Server together with PHP and PHP's GD library (needed for image manipulation) through the following commands. Note that all required dependencies are added automatically, though you may need to manually accept them: sudo apt-get install apache2 php5 php5-gd Next we'll install MySQL and its binding to PHP, again through the terminal. You'll be prompted for a password, which we'll need again later on. sudo apt-get install mysql-server php5-mysql Enable Apache's rewrite module, which SilverStripe requires to use pretty URLs: sudo a2enmod rewrite Edit the file /etc/apache/sites-available/default and replace the line AllowOverride None with AllowOverride All inside the <Directory /var/www/> block. This enables the rewrite module inside the /var/www/ folder. Install Alternative PHP Cache (APC), which will accelerate PHP programs—SilverStripe benefits a lot from this. While there are some alternatives, it is currently planned that APC will be included in PHP 6, which makes it sound like a future-proof decision for our installation: sudo apt-get install php-apc If you want to see APC in action, you'll need its management tool. By default it is located in the file /usr/share/doc/php-apc/apc.php.gz. Unpack and copy it to your web-root to see detailed statistics on how well it's working for you, but protect it against unauthorized access (you can set credentials inside the file). Edit the file /etc/php5/apache2/php.ini, using whatever text-editor you prefer (this can be quite a sensitive topic with programmers). Replace the line ;date.timezone = with date.timezone = US/New_York or your current location. See http://php.net/manual/en/timezones.php for all possible values. Note that removing the semicolon at the beginning is important, otherwise the line will be considered a comment. Restart the web server to apply all the settings we've just made: sudo /etc/init.d/apache2 reload Now it's time to test our installation. Go to the directory /var/www/ which is the default web-root directory: cd /var/www/ It should already contain a file index.html, which you can view if you visit http://127.0.0.1 in your browser (or whichever IP address you can access your server under). However, this is only a static HTML file. To see if PHP is also working, first set the file permissions, assuming our current user is ubuntu (which we'll use to edit files) and the web server is run as www-data (which is the default). So we'll make our user the owner of the files with full permissions, and set the group to the one of the web server with read and execute permissions only: sudo chown ubuntu:www-data -R /var/www/sudo chmod 0755 -R /var/www/ After adding new files, you'll need to rerun these two commands. Next create a file index.php in /var/www/: touch index.php Add the following code to it: <?php phpinfo();?> In your browser load the page http://127.0.0.1/index.php (again use your specific IP address). The output should look something like this: This shows that PHP is working. Also check that you can find mod_rewrite and a full section on APC in the output to be sure they are enabled. That's it, our live system is now ready for action. We haven't installed PEAR as we'll assume that testing and translating is done in the development environment, not on the live server. We've also left out how to install and configure an SMTP server. Unfortunately this is pretty complicated and beyond the scope of this article—especially since you don't want to become a spam relay. If your provider or distribution hasn't already set this up for you, take a look at a specific SMTP server how-to and documentation—Postfix (http://www.postfix.org) is widely used for example.
Read more
  • 0
  • 0
  • 2235

article-image-integrating-yahoo-user-interface-library-yui-moodle
Packt
13 May 2011
6 min read
Save for later

Integrating Yahoo! User Interface Library (YUI) with Moodle

Packt
13 May 2011
6 min read
  Moodle JavaScript Cookbook Over 50 recipes for making your Moodle system more dynamic and responsive with JavaScript In this article, we will cover: Initializing the YUI 3 library Loading YUI 3 modules Loading YUI 2 modules from YUI 3 Attaching basic event handlers Attaching advanced DOM event handlers Implementing Event Delegation Debugging with the YUI console Introduction There are a lot of common tasks that need to be performed when writing JavaScript. A large proportion of this simply involves dealing with differences between web browsers. The need for a way to hide or abstract the specifics of each browser into a standard interface gave rise to sets of tools known as JavaScript libraries. One of the leading libraries in use on the web today is the Yahoo! User Interface Library (YUI). Moodle includes a copy of the YUI as its preferred JavaScript library. YUI provides developers with access to a wide range of tools for enhancing their web applications: The YUI Library is a set of utilities and controls, written with JavaScript and CSS, for building richly interactive web applications using techniques such as DOM scripting, DHTML and AJAX. YUI is available under a BSD license and is free for all uses. YUI is proven, scalable, fast, and robust. Built by frontend engineers at Yahoo! and contributors from around the world, it's an industrial-strength JavaScript library for professionals who love JavaScript. Yahoo! Developer Network http://developer.yahoo.com/yui/ In this article, we will learn the basics of working with YUI. We will learn how to initialize the YUI and make it ready for use within our code and load additional modules from versions 2 and 3 of the YUI. We will also learn how to manage the execution of code by attaching events to our controls, and finally how to debug our code with YUI logging tools. Initializing the YUI 3 library In this recipe, we will learn how to initialize the YUI 3 environment within Moodle, which will get us ready to start using YUI 3 features. Moodle takes care of most of the initial setup, namely loading the required CSS and JavaScript files, so all we need to be concerned with is activating the YUI environment. This example will show how to execute JavaScript code from within the YUI environment. We will set up a small YUI script which will simply display a message including the version number of the active YUI environment in a JavaScript alert box. This provides a simple view of what is required to get YUI up and running that we will build on further in the subsequent recipes. Getting ready We begin by setting up a new PHP file yui_init.php in the cook directory with the following content: <?php require_once(dirname(__FILE__) . '/../config.php'); $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); $PAGE->set_url('/cook/yui_init.php'); $PAGE->requires->js('/cook/yui_init.js'); echo $OUTPUT->header(); echo $OUTPUT->footer(); ?> Notice that the preceding code references a JavaScript file yui_init.js, which has the following content: YUI().use ( function(Y) { alert('Hello from YUI ' + Y.version); } ); How to do it... We have created a PHP file that sets up a Moodle programming environment and includes a JavaScript file, in a way now familiar to us from previous recipes. What is new here is the content of the JavaScript file, which is where we will make ready the YUI 3 environment. Moodle has already included all the JavaScript files required for YUI (this happened when we output the value returned from $OUTPUT->header();). This means we now have a global object named YUI available within our JavaScript code. We create a new instance of the YUI object with the statement YUI() and then immediately call the use method. The only parameter we will pass to the use method is an anonymous function. This is just like a regular JavaScript function, except that it has no name specified; hence it is "anonymous". A name is not required, as it is not referred to again, but it is simply passed directly to the use method. This function itself accepts a single input parameter Y, which will be a reference to the new instance of the YUI object. (Note that the use method is also used to load additional YUI modules; this is the subject of the next recipe.) The anonymous function just created is the most important part of the code to take note of as this is where we will be putting our entire code that will be making use of the YUI features. In this example, you can see that we are just creating a JavaScript alert with a short message including the value of Y.version, which is simply a string containing the version number of YUI that has been loaded as seen in the following screenshot: Here, we can see that our code has successfully initialized the YUI 3.2.0 environment and is ready for us to start using the features available within the YUI and its additional modules. How it works... We have created a new instance of the global object YUI, and called the use method, passing in an anonymous function that contains the code we wish to run. When the new instance of the YUI object is fully loaded, it makes a call to our anonymous function, and our code is executed. In this example, our code displays a short message containing the version number of the YUI instance we created, confirming that we have a fully functional YUI 3 environment as a basis to implement further YUI features. Loading additional YUI modules YUI has a whole host of additional modules providing a very wide range of functionalities. Some examples of commonly used functionalities provided by additional modules include: Animation Drag and drop Manipulating DOM elements Handling DOM events (that is an input button's "click" event) Handling data (JSON/XML) For a current list of all the modules available, please refer to the Yahoo! Developer Network website for YUI 3 at the URL: http://developer.yahoo.com/yui/3/ How to do it... The loading of additional modules is achieved via the use method of the YUI object. In the previous recipe we learned how to run code via the use method with the following syntax: YUI().use ( function(Y) { /* <code to execute> */ } ); Note that the use method takes an arbitrarily long number of arguments (one or more) and only the last argument must be the anonymous function described in the previous recipe. The preceding arguments are a list of one or more modules you wish to load. So for example, to load the Animation module (anim) and the DOM Event Utility module (event), we would use the following syntax in place of the preceding one: YUI().use ( "anim", "event", function(Y) { /* <code to execute> */ } ); Now all of the features of these two additional modules (anim and event) will be available within the anonymous function that contains the code we want to execute. This technique will be used to load the modules we require in the examples contained in the subsequent recipes.
Read more
  • 0
  • 0
  • 2262
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-silverstripe-24-creating-our-own-theme
Packt
12 May 2011
8 min read
Save for later

SilverStripe 2.4: Creating our Own Theme

Packt
12 May 2011
8 min read
Time for action - files and folders for a new theme We could start off from scratch, but let's not make it more complicated than necessary: Simply copy the BlackCandy theme to a new folder in the same directory. We'll just call it bar as the page should be for a bar business. Now reload the CMS backend and you should be able to switch to the new bar theme. As we won't use any of the available images we can delete all image files, but leave the folder intact—we'll add our own pictures later on. Basic layout Next, we'll create our page's general layout. Time to put our template skills into action! Here's the basic layout we want to create: So far it's a pretty basic page. We'll take a good look at the templates and basic structure but won't spend much time on the HTML and CSS specifics. Do, however pay attention on how to set up the different CSS files to make the most out of them. We won't list every line of code involved. If you'd prefer, you can simply copy the missing parts from the code provided here (Ch:2) File themes/bar/templates/Page.ss This page is pretty empty. We'll later add an intro page with a different structure, so the code these templates will share is rather limited. Time for action - the base page Add the following code to the file themes/bar/templates/Page.ss: <!doctype html> <html lang="$ContentLocale"> <head> <meta charset="utf-8"/> <% base_tag %> <title> <% if MetaTitle %> $MetaTitle <% else %> $Title <% end_if %> </title> $MetaTags(false) <link rel="shortcut icon" href="favicon.ico"/> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"> </script> <![endif]--> </head> <body> $Layout <noscript> <br/>&nbsp;<br/>&nbsp;<br/>&nbsp;<br/>&nbsp;<br/>&nbsp;<br/>&nbsp; <div><p> <b>Please activate JavaScript.</b><br/> Otherwise you won't be able to use all available functions properly... </p></div> </noscript> </body> </html> What just happened? The highlighted parts are SilverStripe specific: First, we set the language of our content. Depending on what you've selected during the installation process this can vary. By default, it will be: <html lang="en-US"> Setting the page's base; this can be useful when referencing images and external files. Depending on how you set up your system this will vary. Setting the title just like in the BlackCandy theme. Next, adding meta tags without the title element. These are only set if you actually enter them in the CMS on the Metadata tab on the desired page's Content tab. Empty fields are simply left out in the output. Only the SilverStripe note is set in any case. Finally, including the page's specific layout. The JavaScript we include for Internet Explorer versions before 9 fixes their inability to correctly render HTML5 tags. To learn more about the specific code, head over to https://code.google.com/p/html5shim/. Why HTML5? The motivation behind it isn't to stay buzz-word compliant. While HTML5 is not a finished standard yet, it already adds new features and makes the development a little easier. Take a look at the doctype declaration for example: that's much shorter than XHTML. Now there's a real chance of actually remembering it and not needing to copy it every time you start from scratch. New features include some very handy tags, but we'll come to those in the next code sample. The output on the final HTML page for the second and third elements (we've already taken a look at the first) in the header looks like the following listing. Which part in the template is responsible for which line or lines? <title>home</title> <meta name="generator" content="SilverStripe - http://silverstripe.org" /> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <meta name="keywords" content="some keyword" /> <meta name="description" content="the description of this page" /> Did you notice that there is no reference to a CSS file and the styling is still applied? Remember that CSS files are automagically included if you stick to the naming convention we've already discussed. File themes/bar/templates/Layout/Page.ss Now let's move beyond the basics and do something a bit more interesting. Time for action - the layout page Add the following code to the file themes/bar/templates/Layout/Page.ss: <div> <img src="$ThemeDir/images/background.jpg" alt="Background" id="background"/> </div> <section id="content" class="transparent rounded shadow"> <aside id="top"> <% include BasicInfo %> </aside> <% include Menu %> <section class="typography"> $Content $Form </section> </section> <% include Footer %> We rely on just three includes which are very easy to reuse on different pages. We then reference the page's content and possible forms (no comments will be required). The only template part we've not yet covered is the $ThemeDir. This is replaced by the path to our theme, in our case themes/bar/. So you don't need to worry about hard-coded paths when copying template files between different themes. You only need to take care of paths in the CSS files as they are not processed by the template engine. The includes: BasicInfo.ss, Menu.ss, and Footer.ss In the previous code segment, we've referenced three includes. Let's not forget to create them. Time for action - the includes The includes we're yet to explore are Menu.ss, BasicInfo.ss, and Footer.ss. The menu is very simple, we only include the first level, highlighting the currently active item, as we won't have more subpages: <nav id="menu"> <ul> <% control Menu(1) %> <li class="$Linkingmode"> <a href="$Link">$MenuTitle</a> </li> <% end_control %> </ul> </nav> BasicInfo.ss only contains the $ThemeDir placeholder besides good old HTML: <a href="home"> <img src="$ThemeDir/images/logo.png" alt="Logo" id="logo"/> </a> <ul id="details-first"> <li>Phone: <b>01 23456789</b></li> <li>Contact: <a href="contact">contact@bar.com</a></li> <li>Address: <a href="location">Bar Street 123</a></li> </ul> <div id="details-second"> <div class="left">Opening hours:</div> <div class="right"><p> <b>Mon - Thu 2pm to 2am</b><br/> <b>Fri - Sat 2pm to 4am</b> </p></div> </div> <a href="http://www.facebook.com/pages/"> <img src="$ThemeDir/images/facebook.png" alt="Facebook" id="facebook"/> </a> Be sure to replace bar.com with your own domain. However, using it here is quite fitting because we're making a page for a bar and http://www.bar.com is only a placeholder itself. It's derived from foobar or foo bar, a placeholder name often used in computer programming. But take a look at the site yourself for more information. Finally, the footer makes use of the $Now placeholder and the date formatter .Year to retrieve the current year: <footer> <span><a href="imprint">Imprint</a></span> <span>&copy; Bar $Now.Year</span> </footer> Have a go hero - create the layout and pages Now that we've gone over all of the content, it's time to build the page. Feel free to copy some code as we're not a typing class, but take careful note of every SilverStripe specific part, so you understand what you're doing. We use three includes, so create these files and remove the rest still available from BlackCandy as well as the unused templates/Layout/Page_results.ss. And don't forget to flush the cache by appending ?flush=all to the page's URL! When working with includes it will save you a lot of trouble. We've hardcoded some links to different pages in the template files. Make sure you add all necessary pages including the imprint, but don't add it to the menu.
Read more
  • 0
  • 0
  • 2646

article-image-ibm-lotus-domino-creating-action-buttons-and-adding-style-views
Packt
11 May 2011
7 min read
Save for later

IBM Lotus Domino: Creating Action Buttons and Adding Style to Views

Packt
11 May 2011
7 min read
IBM Lotus Domino: Classic Web Application Development Techniques A step-by-step guide for web application development and quick tips to enhance applications using Lotus Domino Provide view navigation buttons Simple views intended to provide information (for example, a table of values) or links to a limited number of documents can stand alone quite nicely, embedded on a page or a view template. But if more than a handful of documents display in the view, you should provide users a way to move forward and backward through the view. If you use the View Applet, enable the scroll bars; otherwise add some navigational buttons to the view templates to enable users to move around in it. Code next and previous navigation buttons If you set the line count for a view, only that number of rows is sent to the browser. You need to add Action buttons or hotspots on the view template to enable users to advance the view to the next set of documents or to return to the previous set of documents—essentially paging backward and forward through the view. Code a Next button with this formula: @DbCommand("Domino"; "ViewNextPage") Code a Previous button with this formula: @DbCommand("Domino"; "ViewPreviousPage") Code first and last buttons Buttons can be included on the view template to page to the first and last documents in the view. Code an @Formula in a First button's Click event to compute and open a relative URL. The link reopens the current view and positions it at the first document: @URLOpen("/"+@WebDbName+"/"+@Subset(@ViewTitle;-1) + "?OpenView&Start=1") For a Last button, add a Computed for Display field to the view template with this @Formula: @Elements(@DbColumn("":"NoCache"; "" ; @ViewTitle; 1)) The value for the field (vwRows in this example) is the current number of documents in the view. This information is used in the @Formula for the Last button's Click event: url := "/" + @WebDbName + "/" + @Subset(@ViewTitle;-1) ; @URLOpen(url + "?OpenView&Start=" + @Text(vwRows)) When Last is clicked, the view reopens, positioned at the last document. Please note that for very large views, the @Formula for field vwRows may fail because of limitations in the amount of data that can be returned by @DbColumn. Let users specify a line count As computer monitors today come in a wide range of sizes and resolutions, it may be difficult to determine the right number of documents to display in a view to accommodate all users. On some monitors the view may seem too short, on others too long. Here is a strategy you might adapt to your application, that enables users to specify how many lines to display. The solution relies on several components working together: Several Computed for display fields on the view template A button that sets the number of lines with JavaScript Previous and Next buttons that run JavaScript to page through the view The technique uses the Start and Count parameters, which can be used when you open a view with a URL. The Start parameter, used in a previous example, specifies the row or document within a view that should display at the top of the view window on a page. The Count parameter specifies how many rows or documents should display on the page. The Count parameter overrides the line count setting that you may have set on an embedded view element. Here are the Computed for display fields to be created on the view template. The Query_String_Decoded field (a CGI variable) must be named as such, but all the other field names in this list are arbitrary. Following each field name is the @Formula that computes its value: Query_String_Decoded: Query_String_Decoded vwParms: @Right(@LowerCase(Query_String_Decoded); "&") vwStart: @If(@Contains(vwParms; "start="); @Middle(vwParms; "start="; "&"); "1") vwCount: @If(@Contains(vwParms; "count="); @Middle(vwParms; "count="; "&"); "10") vwURL: "/" + @WebDbName + "/"+ @Subset(@ViewTitle;1) + "?OpenView" vwRows: @Elements(@DbColumn("":"NoCache"; ""; @ViewTitle; 1)) countFlag "n" newCount: "1" Add several buttons to the view template. Code JavaScript in each button's onClick event. You may want to code these scripts inline for testing, and then move them to a JavaScript library when you know they are working the way you want them to. The Set Rows button's onClick event is coded with JavaScript that receives a line count from the user. If the user-entered line count is not good, then the current line count is retained. A flag is set indicating that the line count may have been changed: var f = document.forms[0] ; var rows = parseInt(f.vwRows.value) ; var count = prompt("Number of Rows?","10") ; if ( isNaN(count) | count < 1 | count >= rows ) { count = f.vwCount.value ; } f.newCount.value = count ; f.countFlag.value = "y" ; The Previous button's onClick event is coded to page backward through the view using the user-entered line count: var f = document.forms[0] ; var URL = f.vwURL.value ; var ctFlag = f.countFlag.value ; var oCT = parseInt(f.vwCount.value) ; var nCT = parseInt(f.newCount.value) ; var oST = parseInt(f.vwStart.value) ; var count ; var start ; if ( ctFlag == "n" ) { count = oCT ; start = oST - oCT ; } else { count = nCT ; start = oST - nCT ; } if (start < 1 ) { start = 1 ; } location.href = URL + "&Start=" + start + "&Count=" + count ; The Next button pages forward through the view using the user-entered line count: var f = document.forms[0] ; var URL = f.vwURL.value ; var ctFlag = f.countFlag.value ; var oCT = parseInt(f.vwCount.value) ; var nCT = parseInt(f.newCount.value) ; var start = parseInt(f.vwStart.value) + oCT ; if ( ctFlag == "n" ) { location.href = URL + "&Start=" + start + "&Count=" + oCT ; } else { location.href = URL + "&Start=" + start + "&Count=" + nCT ; } Finally, if First and Last buttons are included with this scheme, they need to be recoded as well to work with a user-specified line count. The @formula in the First button's Click event now looks like this: count := @If(@IsAvailable(vwCount); vwCount; "10") ; parms := "?OpenView&Start=1&Count=" + count ; @URLOpen("/" + @WebDbName + "/" + @Subset(@ViewTitle;-1) + parms) ;7 The @formula in the Last button's Click event is also a little more complicated. Note that if the field vwRows is not available, then the Start value is set to 1,000. This is really more for debugging since the Start parameter should always be set to the value of vwRows: start := @If(@IsAvailable(vwRows); @Text(vwRows); "1000") ; count := @If(@IsAvailable(vwCount); vwCount; "10") ; parms := "?OpenView&Start=" + start + "&Count=" + count ; url := "/" + @WebDbName + "/" + @Subset(@ViewTitle;-1) ; @URLOpen(url + parms) ; Code expand and collapse buttons for categorized views Two other navigational buttons should be included on the view template for categorized views or views that include document hierarchies. These buttons expand all categories and collapse all categories respectively: The Expand All button's Click event contains this @Command: @Command([ViewExpandAll]) The Collapse All button's Click event contains this @Command: @Command([ViewCollapseAll]) Co-locate and define all Action buttons Action Bar buttons can be added to a view template as well as to a view. If Action buttons appear on both design elements, then Domino places all the buttons together on the same top row. In the following image, the first button is from the view template, and the last three are from the view itself: If it makes more sense for the buttons to be arranged in a different order, then take control of their placement by co-locating them all either on the view template or on the view. Create your own Action buttons As mentioned previously, Action Bar buttons are rendered in a table placed at the top of a form. But on typical Web pages, buttons and hotspots are located below a banner, or in a menu at the left or the right. Buttons along the top of a form look dated and may not comply with your organization's web development standards. You can replace the view template and view Action buttons with hotspot buttons placed elsewhere on the view template: Create a series of hotspots or hotspot buttons on the view template, perhaps below a banner. Code @formulas for the hotspots that are equivalent to the Action Bar button formulas. Define a CSS class for those hotspots, and code appropriate CSS rules. Delete or hide from the Web all standard Action Bar buttons on the view template and on the view.
Read more
  • 0
  • 0
  • 5684

article-image-ibm-lotus-domino-exploring-view-options-web
Packt
11 May 2011
8 min read
Save for later

IBM Lotus Domino: exploring view options for the web

Packt
11 May 2011
8 min read
Views are important to most Domino applications. They provide the primary means by which documents are located and retrieved. But working with views on the Web is often more complicated or less satisfactory than using views with the Notes client. Several classic view options are available for web applications, all of which have draw-backs and implementation issues. A specific view can be displayed on the Web in several different ways. So it is helpful to consider view attributes that influence design choices, in particular: View content View structure How a view is translated for the Web How a view looks in a browser Whether or not a view template is used View performance Document hierarchy In terms of content, a view contains: Data only Data and HTML tags In terms of structure, views are: Uncategorized Categorized In terms of the techniques used by Domino to translate views for the Web, there are four basic methods: Domino-generated HTML (the default) Developer-generated HTML (the view contains data and HTML tags) View Applet (used with data only views) XML (the view is transmitted to the browser as an XML document) The first three of these methods are easier to implement. Two options on the Advanced tab of View Properties control which of these three methods is used: Treat view contents as HTML Use applet in the browser If neither option is checked, then Domino translates the view into an HTML table and then sends the page to the browser. If Treat view contents as HTML is checked, then Domino sends the view to the browser as is, assuming that the developer has encoded HTML table tags in the view. If Use applet in the browser is checked, then Domino uses the Java View Applet to display the view. (As mentioned previously, the Java Applets can be slow to load, and they do require a locally installed JVM (Java Virtual Machine)). Using XML to display views in a browser is a more complicated proposition, and we will not deal with it here. Pursue this and other XML-related topics in Designer Help or on the Web. Here is a starting point: http://www.ibm.com/developerworks/xml/ In terms of how a view looks when displayed in a browser, two alternatives can be used: Native styling with Designer Styling with Cascading Style Sheets In terms of whether or not a view template is used, there are three choices: A view template is not used The default view template is used A view template created for a specific view is used Finally, view performance can be an issue for views with many: Documents Columns Column formulas Column sorting options Each view is indexed and refreshed according to a setting on the Advanced tab of View Properties. By default, view indices are set to refresh automatically when documents are added or deleted. If the re-indexing process takes longer, then application response time can suffer. In general, smaller and simpler views with fewer column formulas perform better than long, complicated and computationally intensive views. The topics in this section deal with designing views for the Web. The first few topics review the standard options for displaying views. Later topics offer suggestions about improving view look and feel. Understand view Action buttons As you work with views on the Web, keep in mind that Action buttons are always placed at the top of the page regardless of how the view is displayed on the Web (standard view, view contents as HTML) and regardless of whether or not a view template is used. Unless the Action Bar is displayed with the Java applet, Action buttons are rendered in a basic HTML table; a horizontal rule separates the Action buttons from the rest of the form. Bear in mind that the Action buttons are functionally connected to but stylistically independent of the view and view template design elements that display lower on the form. Use Domino-generated default views When you look at a view on the Web, the view consists only of column headings and data rows. Everything else on the page (below any Action buttons) is contained on a view template form. You can create view templates in your design, or you can let Domino provide a default form. If Domino supplies the view template, the rendered page is fairly basic. Below the Action buttons and the horizontal rule, standard navigational hotspots are displayed; these navigational hotspots are repeated below the view. Expand and Collapse hotspots are included to support categorized views and views that include documents in response hierarchies. The view title displays below the top set of navigational hotspots, and then the view itself appears. If you supply a view template for a view, you must design the navigational hotspots, view title, and other design elements that may be required. View contents are rendered as an HTML table with columns that expand or contract depending upon the width of cell contents. If view columns enable sorting, then sorting arrows appear to the right of column headings. Here is an example of how Domino displays a view by default on the Web: In this example, clicking the blue underscored values in the left-most Last Name column opens the corresponding documents. By default, values in the left-most column are rendered as URL links, but any other column—or several columns—can serve this purpose. To change which column values are clickable, enable or disable the Show values in this column as links option on the Advanced tab of Column Properties: Typically a title, subject, or another unique document attribute is enabled as the link. Out of the box default views are a good choice for rapid prototyping or for one-time needs where look-and-feel are less important. Beyond designing the views, nothing else is required. Domino merges the views with HTML tags and a little JavaScript to produce fully functional pages. On the down side, what you see is what you get. Default views are stylistically uninspiring, and there is not a lot that can be done with them beyond some modest Designer-applied styling. Many Designer-applied styles, such as column width, are not translated to the Web. Still, some visual improvements can be made. In this example, the font characteristics are modified, and an alternate row background color is added: Include HTML tags to enhance views Some additional styling and behavior can be coded into standard views using HTML tags and CSS rules. Here is how this is done: In this example, <font> tags surround the column Title. Note the square brackets that identify the tags as HTML: Tags can also be inserted into column value formulas: "[<font color='darkblue'>]" + ContactLast + "[</font>]" When viewed with a browser, the new colors are displayed as expected. But when the view is opened in Notes, it looks like this: (Move the mouse over the image to enlarge it.) The example illustrates how to code the additional tags, but frankly the same effects can be achieved using Designer-applied formatting, so there is no real gain here. The view takes longer to code and the final result is not very reader-friendly when viewed with the Notes client. That being said, there still may be occasions when you want to add HTML tags to achieve a particular result. Here is a somewhat more complicated application of the same technique. This next line of code is added to the Title of a column. Note the use of <sup> and <font> tags. These tags apply only to the message See footnote 1: Last Name[<sup><font color='red'>]See footnote 1[</font></sup>] The result achieves the desired effect: More challenging is styling values in view columns. You do not have access to the <td> or <font> tags that Domino inserts into the page to define table cell contents. But you can add <span> tags around a column value, and then use CSS rules to style the span. Here is what the column formula might look like: "[<span class='column1'>]" + ContactLast + "[</span>]" Here is the CSS rule for the column1 class: .column1 { background-color: #EEE; cursor: default; display: block; font-weight: bold; text-decoration: none; width: 100%; } These declarations change the background color of the cell to a light gray and the pointer to the browser default. The display and width declarations force the span to occupy the width of the table cell. The text underscoring (for the link) is removed and the text is made bold. Without the CSS rule, the view displays as expected: With the CSS rule applied, a different look for the first column is achieved:
Read more
  • 0
  • 0
  • 9010

article-image-cms-made-simple-application-user-defined-tags
Packt
10 May 2011
9 min read
Save for later

CMS Made Simple: Application of User-Defined Tags

Packt
10 May 2011
9 min read
CMS Made Simple Development Cookbook Over 70 simple but incredibly effective recipes for extending CMS Made Simple with detailed explanations – useful for beginners and experts alike! These recipes have been specially selected to demonstrate capabilities. While they may be useful as provided, they are designed to show the range of what can be done with tags, and to provide examples of useful operations such as setting Smarty variables, interfacing with the database, interacting with modules, and consuming data from remote web services. You are encouraged to use these recipes as starting points for your own projects. Introduction One of the most popular uses of CMS Made Simple involves an administrator who creates a basic site structure and template, and one or more editors who maintain page content without having to worry about the site layout. In this configuration, you can think of the CMS essentially as a big template engine with some utilities to add content. Each page of the site comprises a page template with areas that get populated with various kinds of content. These areas are either tags or variables, where the distinction is that a tag involves the execution of code, while a variable is a simple substitution of values. The CMS comes with a large assortment of built-in tags, including the fundamental "content" tag and a variety of useful supporting tags for building navigation, links, including images, and so forth. Because CMS Made Simple can be seen as being built around tags, it is not surprising that there are facilities for creating your own tags. You can create tags directly through the Admin panel—these are called User-Defined Tags or UDTs. If you want even more extensive capabilities in your tag, you can have those capabilities by creating a file that follows a few basic conventions. The template engine used by CMS Made Simple comes from the Smarty project. Pages are Smarty templates, and the built-in CMS tag types are all Smarty tags. Behind the scenes, both UDTs and file-based tags also become Smarty tags. For additional information on Smarty, the documentation provided by the Smarty project is invaluable. You can read more at http://www.smarty.net/docsv2/en/ Displaying the User's IP address from a User-Defined Tag This recipe demonstrates creating a very simple User-Defined Tag, and using it to display information, that it gets from PHP globally-defined variables. Getting ready For this recipe, you will need to have CMS Made Simple installed and working. You will need login access to the site's Administration area as a member of the "admin" group, or as a member of a group with permissions to "Modify User-Defined Tags" and "Manage All Content". How to do it... Log in to your CMS Administration area. Using the top menu, go to "Extensions" and click on "User Defined Tags". Click on the "Add User Defined Tag" button. In the "Name" field type "user_ip". In the "Code" text area, type the following code: echo 'Welcome user from '.$_SERVER['REMOTE_ADDR'].' -- enjoy your visit!'; Click on the "Submit" button. Using the top menu, go to "Content" and click on "Pages". Click on the "Add New Content" button. In the "Title" and "Menu Text" fields, type "Tag Test". In the "Content" text area, type the following code: {user_ip} Click on the "Submit" button. View your site from the user side. Click on the new "Tag Test" page. How it works... User-Defined Tags work by linking a piece of PHP code to a tag which is recognized by Smarty. When Smarty parses a template and encounters that tag, it executes the code in question, and substitutes the tag markup with any output from that PHP code. When we create a UDT in the CMS Made Simple admin area, the name we enter into the text field becomes the tag which Smarty will look for, and the code we enter into the text area is the PHP associated with the tag. This recipe is an example of outputting text directly from a User-Defined Tag. It works by echoing a string, that then replaces the {user_ip} tag in the content. This substitution of the tag can take place either in a page template or in the page content, which might seem a little confusing since it's stated earlier that Smarty processes tags that it finds in templates. The confusion, though, is mostly due to terminology; CMS Made Simple processes both layout templates and page content through Smarty, so while it is being processed, page content serves as a template from Smarty's perspective. The User-Defined Tag we create accesses one of the PHP "superglobals"—the $_SERVER variable . This variable contains information about the HTTP request and some environmental information about the PHP server. In this case, we're getting the user's IP address information to display. Using the CmsObject and the current content object in a User-Defined Tag This recipe shows you how to access the Page Content object via the CmsObject in a User-Defined Tag. The primary technique that it demonstrates—getting a reference to the CmsObject and using the CmsObject to get a reference to other important CMS runtime objects—is one that you will use to solve many different kinds of problems. In this recipe, we use the CmsObject to get a reference to the Page Content object. Once we have a reference to this object, we can call upon its methods to report all kinds of interesting information about the current page content. Getting ready For this recipe, you will need login access to your site's Administration area with permission to "Modify User-Defined Tags" and "Manage All Content". How to do it... Log in to your CMS Administration area. Using the top menu, go to "Extensions" and click on "User Defined Tags". Click on the "Add User Defined Tag" icon. In the "Name" field, type "content_description". In the "Code" field, type the following code: $gCms = cmsms(); $contentops = $gCms->GetContentOperations(); $content_obj = $contentops->getContentObject(); echo 'Current content object is "'.$content_obj->Name().'"<br />'; echo 'which was created on '.$content_obj->GetCreationDate().'<br />'; echo 'its alias is "'.$content_obj->Alias().'"<br />'; echo 'and its URL is "'.$content_obj->GetURL().'"<br />'; Click on the "Submit" button. Using the top menu, select "Content" and click on "Pages". Click on the "Add New Content" button. Enter "New Content Page" into the "Title" and "Menu Text" fields. In the "Content" field, enter: {content_description} Click on the "Submit" button. View your site from the user side. Click on the new "Content Page" page. How it works... CMS Made Simple uses an internal object called "CmsObject" to keep track of a great deal of what it needs to serve content. This information includes the site hierarchy, the installed and active modules, references to the database, and more. The CmsObject is available to Modules, Tags, and User-Defined Tags via the cmsms() function. In this recipe, we want to display information from the current Content object. However, this object is not directly accessible. To get access to this object, we need to make a static call to the ContentOperations object, but this object is also not directly accessible from our code. To get access to these objects, we need to get references to them. We start by gaining access to the CmsObject by calling the global cmsms() function. From our reference to the CmsObject, we request a reference to the ContentOperations object, that we then use to request a reference to the current content object. Once we have the current content object, we can call assorted methods on it to retrieve information about the current content. In this recipe, we get the content's name, when it was last modified, its alias, and its URL. Since this recipe is an example, we don't format these various pieces of information or use a template, but simply echo them. In a production UDT or one in which there's any complexity to what is being displayed, it would be more advisable to use the values to populate Smarty variables for later display, or use a template for formatting them. There's more... There are a number of interesting objects, that CmsObject manages. References can be requested to: BookmarkOperations— used in the Admin area ContentOperations—which has methods to handle Content and content metadata Db— which wraps the ADODB database API GlobalContentOperations— which has methods to handle Global Content Blocks GroupOperations— which has methods to handle Admin Groups HierarchyManager— which has methods for handling site content hierarchies ModuleOperations— which has methods for managing Modules Smarty— which wraps the Smarty template engine StylesheetOperations—which has methods for handling TemplateOperations— which has methods for handling Smarty templates UserOperations— which has methods for handling Admin Users UserTagOperations— which has methods for handling User-Defined Tags Getting attributes using page_attr If you're looking to display information about the current content object, CMS Made Simple has a custom Smarty tag that provides some attributes: {page_attr}. You can use this tag to display page attribute information—simply by specifying a key to the information you're requesting. For example, to get the page's "image" attribute, you could use the tag {page_attr key="image"}. Other keys that are supported include: target image thumbnail extra1 extra2 extra3 searchable pagedata disable_wysiwyg content_en As you can see, this is not as rich a collection of information as you can get from the content object directly using your own UDT. Old code and the use of globals If you look at old modules or User-Defined Tags that have been posted in the CMS Made Simple forum, you may see the following code: global $gCms; instead of the $gCms = cmsms() used here. For a long time, the use of the global declaration was the preferred way to access the CmsObject. This approach is now deprecated for a number of reasons, most important of which is a security issue and also including portability of code between CMS Made Simple 1.x and the upcoming 2.x versions. While use of the global declaration to access the CmsObject will likely still work, it is strongly discouraged.  
Read more
  • 0
  • 0
  • 4733
article-image-wordpress-3-building-widget
Packt
06 May 2011
10 min read
Save for later

WordPress 3: Building a Widget

Packt
06 May 2011
10 min read
  WordPress 3 Plugin Development Essentials Create your own powerful, interactive plugins to extend and add features to your WordPress site         Read more about this book       (For more resources on WordPress, see here.) The plan What exactly do we want this plugin to do? Our widget will display a random bit of text from the database. This type of plugin is frequently used for advertisement rotations or in situations where you want to spruce up a page by rotating content on a periodic basis. Each instance of our plugin will also have a "shelf life" that will determine how frequently its content should be randomized. Let's take a moment to come up with some specifications for this plugin. We want it to do the following: Store multiple chunks of content, such as bits of Google Adsense code Be able to randomly return one of the chunks Set a time limit that defines the "shelf life" of each chunk, after which the "random" chunk will be updated Widget overview Even if you are already familiar with widgets, take a moment to look at how they work in the WordPress manager under Appearance | Widgets. You know that they display content on the frontend of your site, usually in a sidebar, and they also have text and control forms that are displayed only when you view them inside the manager. If you put on your thinking cap, this should suggest to you at least two actions: an action that displays the content on the frontend, and an action that displays the form used to update the widget settings inside the manager. There are actually a total of four actions that determine the behavior of a standard widget, and you can think of these functions as a unit because they all live together in a single widget object. In layman's terms, there are four things that any widget can do. In programmatic terms, the WP_Widget object class has four functions that you may implement: The constructor: The constructor is the only function that you must implement. When you "construct" your widget, you give it a name, a description, and you define what options it has. Its name is often __ construct(), but PHP still accepts the PHP 4 method of naming your constructor function using the name of the class. widget(): It displays content to users on the frontend. form(): It displays content to manager users on the backend, usually to allow them to update the widget settings. update(): It prepares the updated widget settings for database storage. Override this function if you require special form validation. In order to make your widget actually work, you will need to tell WordPress about it by registering it using the WordPress register_widget() function. If you want to get a bit more information about the process, have a look at WordPress' documentation here. Let's outline this in code so you can see how it works. Preparation As always, we're going to go through the same setup steps to get our plugin outlined so we can get it activated and tested as soon as possible. Create a folder inside the wp-content/plugins/ directory. We are naming this plugin "Content Rotator", so create a new folder inside wp-content/ plugins/ named content-rotator. Create the index.php file. Add the Information Head to the index.php file. If you forgot the format, just copy and modify it from the Hello Dolly plugin like we did in the previous article, Anatomy of a WordPress Plugin. We're giving you bigger sections of code than before because hopefully by now you're more comfortable adding and testing them. Here is what our index.php looks like: <?php/*------------------------------------------------------------------------------Plugin Name: Content RotatorPlugin URI: http://www.tipsfor.us/Description: Sample plugin for rotating chunks of custom content.Author: Everett GriffithsVersion: 0.1Author URI: http://www.tipsfor.us/------------------------------------------------------------------------------*/// include() or require() any necessary files here...include_once('includes/ContentRotatorWidget.php');// Tie into WordPress Hooks and any functions that should run onload.add_action('widgets_init', 'ContentRotatorWidget::register_this_widget');/* EOF */ Add the folders for includes and tpls to help keep our files organized. Add a new class file to the includes directory. The file should be named ContentRotatorWidget.php so it matches the include statement in the index.php file. This is a subclass which extends the parent WP_Widget class. We will name this class ContentRotatorWidget, and it should be declared using the extends keyword. <?php /*** ContentRotatorWidget extends WP_Widget** This implements a WordPress widget designed to randomize chunksof content.*/class ContentRotatorWidget extends WP_Widget { public $name = 'Content Rotator'; public $description = 'Rotates chunks of content on a periodic basis'; /* List all controllable options here along with a default value. The values can be distinct for each instance of the widget. */ public $control_options = array(); //!!! Magic Functions // The constructor. function __construct() { $widget_options = array( 'classname' => __CLASS__, 'description' => $this->widget_desc, ); parent::__construct( __CLASS__, $this->name,$widget_ options,$this->control_options); } //!!! Static Functions static function register_this_widget() { register_widget(__CLASS__); } } /* EOF */ This is the simplest possible widget—we constructed it using only the __ construct() function. We haven't implemented any other functions, but we are supplying enough information here for it to work. Specifically, we are supplying a name and a description, and that's enough to get started. Let's take a moment to explain everything that just happened, especially since the official documentation here is a bit lacking. When we declared the ContentRotatorWidget class, we used the extends keyword. That's what makes this PHP class a widget, and that's what makes object-oriented code so useful. The __construct() function is called when an object is first created using the new command, so you might expect to see something like the following in our index. php file: <?php $my_widget = new ContentRotatorWidget();?> However, WordPress has obscured that from us—we just have to tell WordPress the classname of the widget we want to register via the register_widget() function, and it takes care of rest by creating a new instance of this ContentRotatorWidget. There is a new instance being created, we just don't see it directly. Some of the official documentation still uses PHP 4 style examples of the constructor function— that is to say that the function whose name shares the name of the class. We feel that naming the constructor function __construct is clearer. You may have wondered why we didn't simply put the following into our index.php file: register_widget('ContentRotatorWidget'); // may throw errors if called too soon! If you do that, WordPress will try to register the widget before it's ready, and you'll get a fatal error: "Call to a member function register() on a non-object". That's why we delay the execution of that function by hooking it to the widgets_ init action. We are also tying into the construct of the parent class via the parent::__ construct() function call. We'll explain the hierarchy in more detail later, but "parent" is a special keyword that can be used by a child class in order to call functions in the parent class. In this case, we want to tie into the WP_Widget __ construct() function in order to properly instantiate our widget. Note our use of the PHP __CLASS__ constant—its value is the class name, so in this case, we could replace it with ContentRotatorWidget, but we wanted to provide you with more reusable code. You're welcome. Lastly, have a look at the class variables we have declared at the top of the class: $name, $description, and $control_options. We have put them at the top of the class for easy access, then we have referenced them in the __construct() function using the $this variable. Note the syntax here for using class variables. We are declaring these variables as class variables for purposes of scope: we want their values to be available throughout the class. Please save your work before continuing. Activating your plugin Before we can actually use our widget and see what it looks like, we first have to activate our plugin in the manager. Your widget will never show up in the widget administration area if the plugin is not active! Just to be clear, you will have to activate two things: your plugin, and then your widget. The code is simple enough at this point for you to be able to quickly track down any errors. Activating the widget Now that the plugin code is active, we should see our widget show up in the widget administration area: Appearance | Widgets. Take a moment to notice the correlation between the widget's name and description and how we used the corresponding variables in our constructor function. Drag your widget into the primary widget area to make it active. Once it has been activated, refresh your homepage. Your active widget should print some text in the sidebar. (Move the mouse over the image to enlarge it.) Congratulations! You have created your first WordPress widget! It is printing a default message: function WP_Widget::widget() must be over-ridden in a sub-class, which is not very exciting, but technically speaking you have a functional widget. We still need to enable our widget to store some custom options, but first we should ensure that everything is working correctly. Having problems? No widget? If you have activated your plugin, but you do not see your widget showing up in the widget administration area, make sure you have tied into a valid WordPress action! If you misspell the action, it will not get called! The action we are using in our index.php is widgets_init—don't forget the "s"! White screen? Even if you have PHP error-reporting enabled, sometimes you suddenly end up with a completely white screen in both the frontend and in the manager. If there is a legitimate syntax error, that displays just fine, but if your PHP code is syntactically correct, you end up with nothing but a blank page. What's going on? A heavy-handed solution for when plugins go bad is to temporarily remove your plugin's folder from /wp-content/plugins, then refresh the manager. WordPress is smart enough to deactivate any plugin that it cannot find, so it can recover from this type of surgery. If you are experiencing the "White Screen of Death", it usually means that something is tragically wrong with your code, and it can take a while to track it down because each time you deactivate the plugin by removing the folder, you have to reactivate it by moving the folder back and reactivating the plugin in the WordPress manager. This unenviable situation can occur if you accidentally chose a function name that was already in use (for example, register()—don't use that as a function name). You have to be especially careful of this when you are extending a class because you may inadvertently override a vital function when you meant to create a new one. If you think you may have done this, drop and do 20 push-ups and then have a look at the original parent WP_Widget class and its functions in wp-includes/widgets.php. Remember that whenever you extend a class, it behooves you to look at the parent class' functions and their inputs and outputs. If this sounds like Greek to you, then the next section is for you.
Read more
  • 0
  • 0
  • 2990

article-image-silverstripe-24-customizing-layout
Packt
06 May 2011
10 min read
Save for later

SilverStripe 2.4: Customizing the Layout

Packt
06 May 2011
10 min read
Templates and themes All pages within SilverStripe are rendered using a template, which is basically an HTML/XHTML file with added control code. A template allows you to make conditional statements, create menus, access data stored in the database, and much more. Instead of using PHP for these enhancements, templates rely on a dedicated template engine. When the user accesses a page the engine replaces the control code with PHP. This transformation is then evaluated by the web server to regular markup code, which every browser can display. A theme consists of a collection of template, CSS, and image files. Design-specific JavaScript is also stored here. Together they form the layout of a page. Switching between themes You can have multiple themes and switch between them whenever you like. You're definitely encouraged to give everything described here a try. It helps you in becoming an active developer instead of a passive user. So let's get things started! Time for action - change the default theme Simply perform the following steps in the CMS and you're all set: Log into the CMS by appending /admin to your page's base URL. Provide the credentials you defined during the installation and you should be logged-in. Go to the general configuration page by clicking on the globe within the Page Tree section. The default text of this element is Your Site Name. The Theme is set to (Use default theme) by default; change this to tutorial. Click on the Save button. Go to the base URL / and reload the page. What just happened? We've successfully changed the theme of our website. It's as easy as that. Note that you need to package your theme into a subfolder of themes/ to be able to switch between them. While you can also put the contents of a theme directly into the mysite/ folder, keeping your system modularized is a good practice. Therefore we won't integrate the layout into the site specific folder and will instead always create a dedicated, switchable theme. Getting more themes After unpacking a theme, copy it to the themes/ folder, change the theme in the CMS, and you're good to go. Using a prebuilt theme really is that simple. Next, we'll take a look at the facilities for building our own themes—specifically, the template engine that powers all themes in SilverStripe. By the end of this article and next, you'll even be ready to upload and share your own themes with the rest of the community at the address above. New contributions are always welcome. Template engine As described earlier, the SilverStripe architecture consists of three layers, each serving a specific purpose. The one responsible for the layout is called View, which we'll cover in detail in this article. Another template engine? One might wonder why it is necessary to learn another template language, while there are already so many others available and PHP can do all of it as well. The main reasons behind this are: The template engine and the rest of the system fit perfectly together. After getting the hang of it, it makes the creation of templates and communication with the other layers faster and easier. The available control code is very simple. Designers without a lot of programming knowledge can create feature-rich layouts. It enforces good coding practice. Without the ability to use raw PHP, one cannot by-pass the other layers and undermine the architecture. Only layout and rendering information should be used within templates. Taking a look at BlackCandy First of all, switch back to the BlackCandy theme as we want to take a better look at it. Within your installation, navigate to the folder themes/blackcandy/ and you'll see three folders: css/, images/, and templates/. The images/ folder contains any image used in your theme; if you like, you can create subfolders to keep things organized. The remaining folders are a bit more complicated, so let's break them down. CSS At first this looks a bit messy—five files for the CSS; couldn't we use just a single one? We could, but many developers consider it a good practise splitting the functionality into different parts, making it easier to navigate later on. Sticking to this convention adds functionality as well. This is a common principle, called convention over configuration. If you do things the way they are expected by the system, you don't need to configure them specifically. Once you know the "way" of the system, you'll work much quicker than if you had to configure the same things over and over again. editor.css This file is automagically loaded by SilverStripe's what you see is what you get (WYSIWYG) editor. So if you apply the correct styling via this file, the content in the CMS' backend will look like the final output in the frontend. Additionally you'll have all custom elements available under the Styles dropdown, so the content editors don't need to mess around with pure HTML. As this file is not automatically linked to the frontend, it's common practice to put all frontend styling information into typography.css and reference that file in editor.css: @import "typography.css"; If you want to provide any styling information just for the CMS, you can put it below the @import. layout.css, form.css, and typography.css These files are automagically included in the frontend if they are available in your theme. While layout.css is used for setting the page's basic sections and layout, form.css deals with the form related styling. typography.css covers the layout of content entered into the CMS, generally being imported by editor.css as we've just discussed. Elements you will include here are headers (<h1>, <h2>, and so on), text (for example <p>), lists, tables, and others you want to use in the CMS (aligning elements, <hr>, and so on). ie6.css This file isn't part of the SilverStripe convention, but is a useful idea you might want to adopt. You must include it manually but it will still be a good idea to stick to this naming schema: ie.css for styling elements in any version of Internet Explorer, ie6.css for Internet Explorer 6 specifics, and so on. What about performance? Cutting down on the number of files being loaded is an effective optimization technique for websites. We'll take a look at how to do that. Templates Now that we've discussed the styling, let's take a look at how to put the content together with the help of templates. Learning the very basics Before we continue, some basic facts and features of templates: Templates must use the file extension .ss instead of .html or .php. Templates can be organized alongside their PHP Controllers, so you can use the same powerful mechanism as in the other layers. We'll take a better look at what this means a little later. Page controls consist of placeholders and control structures, which are both placed within the regular markup language. Placeholders start with a $ and are processed and replaced by the template engine. Control structures are written between opening <% and closing %>. They look a bit like HTML tags and they are used the same way. Some consist of a single element, like HTML's <br>, whereas others consist of two or more. Starting to use templates Now that we've covered the basics, let's put them into practice. Time for action - using site title and slogan We shall use placeholders, taking a look at the code level and how to use them in the CMS: Open the file themes/blackcandy/templates/Page.ss in your preferred editor. If the syntax highlighting is disabled due to the unknown file extension, set it to HTML. Find the two placeholders $SiteConfig.Title and $SiteConfig.Tagline in the code. Go to the general configuration page in the CMS, the one where we've changed the theme. Edit the Site title and Site Tagline/Slogan to something more meaningful. Save the page. Go to the base URL and hit refresh. If you view the page's source, you can see that the two placeholders have been replaced by the text we have just entered in the CMS. If you are wondering about the short doctype declaration: there is nothing missing, this is HTML5, which SilverStripe is already using in its default theme. If you prefer XHTML or an older HTML standard, you can freely change it. The CMS happily works with all of them. What just happened? The file we've just edited is the base template. It's used for every page (unless specifically overwritten). You can define your general layout once and don't have to repeat it again. You should always try to avoid repeating code or content. This is generally called don't repeat yourself (DRY) or duplication is evil (DIE). SilverStripe supports you very well in doing this. The site title and slogan are globally available. You can use them on every page and they share the same content across the whole website. These placeholders are prefixed with SiteConfig. as well as a $ sign. In the CMS they are all available on the site's root element, the one with the globe. By default, there are just two, but we'll later see how to add more. Other placeholders are available on specific pages or can be different on each page. We'll come to those next. Layout Looking again at the Page.ss we've just opened, you'll also see a $Layout placeholder. This is replaced by a file from the themes/blackcandy/templates/Layout folder. There are only two files available by default and for every standard page Page.ss is used. When a page is loaded, the template engine first finds the base templates/Page.ss (excluding the theme specific part of the path as this can vary). It's evaluated and the $Layout is replaced by templates/Layout/Page.ss, which is also evaluated for further SilverStripe controls. Ignore Page_results.ss for the moment. It's only used for search queries which we'll cover later. We'll also add more page types so the layout's Page.ss can then be replaced by a more specific template, while the base templates/Page.ss is always used. Includes Both Page.ss files include statements like <% include BreadCrumbs %>. These controls are replaced by files from the themes/blackcandy/templates/Includes/ folder. For example, the above include grabs the themes/blackcandy/templates/Includes/BreadCrumbs.ss file. Note that filenames are case sensitive. Otherwise you're free to select a meaningful name. Try sticking to one naming convention to make your own life easier later on, and also note that you mustn't include the <code>.ss</code> extension. If you're seeing a Filename cannot be empty error, make sure the included file really exists. Have a go hero - using page name, navigation label, and metadata title Now that we've explored all available files and how they are used, let's take a better look at the system. In the CMS backend, go to the Home page. Change the text currently entered into Page name, Navigation label (both in the Main tab), and Title (Metadata tab). Take a look at: Where on the page they are used In which file they are located (take a look at all three possible locations) What template placeholders represent them You might notice $MetaTitle, $Title, and $MenuTitle in your template files (for the moment ignore the appended .XML). We will explore these later on.
Read more
  • 0
  • 0
  • 2456

article-image-core-data-ios-designing-data-model-and-building-data-objects
Packt
05 May 2011
7 min read
Save for later

Core Data: Designing a Data Model and Building Data Objects

Packt
05 May 2011
7 min read
To design a data model with Core Data, we need to create a new project. So, let's start there... Creating a new project To create a new project, perform the following steps: Launch Xcode and create a new project by selecting the File | New Project option. The New Project Assistant window will appear, prompting us to select a template for the new project, as shown in the next screenshot. We will select the Navigation-based Application template. Ensure that the Use Core Data for storage checkbox is checked and click on the Choose... button. On selecting the Choose... button, we will get a dialog box to specify the name and the location of the project. Let us keep the location the same as default (Documents folder) and assign the project name as: prob (any name). Click on Save. Xcode will then generate the project files and the project gets opened in the Xcode project window. The checkbox Use Core Data for storage will ask Xcode to provide all the default code that is required for using Core Data. This option is visible with only two project templates: Navigationbased Application and Window-based Application templates. Designing the data model Designing a data model means defining entities, attributes, and relationships for our application using a special tool. Xcode includes a data modeling tool (also known as Data Model Editor or simply a modeler) that facilitates the creation of entities, defining attributes, and the relationships among them. Data Model Editor The Data Model Editor is a data modeling tool provided by Xcode that makes the job of designing a data model quite easy. It displays the browser as well as a diagram view of the data model. The Browser view displays two panes, the Entity pane and the Properties pane, for defining entities and their respective properties. The diagram view displays rounded rectangles that designate entities and lines to show relationships among the entities. Adding an entity To add an entity to our data model, perform the following steps: Invoke the data modeling tool by double-clicking the prob.xcdatamodel file in the Resources group found in the Xcode Project window. Xcode's data modeling tool will open and we will find that an entity by default is already created for us by the name: Event (as shown in the next image) with an attribute: timeStamp. We can delete or rename the default entity Event as desired. Let us select the default Event entity and delete it by clicking on the minus (-) button in the Entity pane followed by either choosing plus (+) button in the Entity pane or by choosing Design | Data Model | Add Entity option from the menu bar. This will add a blank entity (by the name Entity) to our data model, which we can rename as per our requirements. Let us set the name of the new entity as: Customer. Automatically, an instance of NSManagedObject will be created to represent our newly created Customer entity. The next step is to add attributes to this entity. Adding an attribute property We want to add three attributes by name—name, emailid, and contactno—to the Customer entity. Let's follow the steps mentioned next for the same: Select the entity and choose the Design | Data Model | Add Attribute option from the menu bar or select the + (plus) button in the Property pane. A menu with several options such as Add Attribute, Add Fetched property, Add Relationship, and Add Fetch Request will pop up. We select the Add Attribute option from the popped up menu. We see that a new attribute property is created for our Customer entity by a default name: newAttribute in the inspector. Let us rename our new attribute as: name (as we will be using this attribute to store the names of the customers). Then, we set the type of the name attribute to String as shown in the next screenshot (as names consists of strings): Below the Name field are three checkboxes: Optional, Transient, and Indexed. Though we will be using the Optional checkbox for the name attribute, let us see the usage of all three: Optional: If this checkbox is checked, it means the entity can be saved even if the attribute is nil (empty). If this checkbox is unchecked and we try to save the entity with this attribute set to nil, it will result in a validation error. When used with a relationship, if the checkbox is checked it means that the relationship can be empty. Suppose that we create one more entity say: Credit Card (where information of the customer's credit card is kept). In that case, the relationship from customer to the credit card will be optional (we have to leave this checkbox checked) as a customer may or may not have a credit card. And if we create an entity say: Product—in that case, the relationship from the Customer to the Product cannot be empty as a customer will definitely buy at least a single product (the checkbox has to be unchecked). Transient: This checkbox, if checked, means that the attribute or the relationship is of a temporary nature and we don't want it to be stored (persist) in the persistent store. This checkbox must be unchecked for the attributes or relationship that we want to persist (to be stored on the disk). Indexed: This checkbox has to be checked to apply indexing on the attribute. It is used when we want to perform sorting or searching on some attribute. By checking this checkbox, an index will be created on that attribute and the database will be ordered on that attribute. Types of attributes Using the Type drop-down list control, we select the data type (that is, numerical, string, date, and so on) of the attribute to specify the kind of information that can be stored in the attribute. The following is the list of data types: Integer 16, Integer 32, and Integer 64 data types are for storing signed integers. The range of values that these types are able to store is as follows: Integer 16:-32,768 to 32, 767 Integer 32:-2,147,483,648 to 2,147,483,647 Integer 64:-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Decimal, Double, and Float data types are for storing fractional numbers. The Double data type uses 64 bits to store a value while the Float data type uses 32 bits for storing a value. The only limitation with these two data types is that they round off the values. To avoid any rounding of values, the Decimal data type is preferred. The Decimal type uses fixed point numbers for storing values, so the numerical value stored in it is not rounded off. String data type is used for storing text contents. Boolean data type is used for storing YES or NO values. Date data type is used for storing dates as well as timestamps. Binary data type is used for storing binary data. Transformable data type works along with Value Transformers that help us create attributes based on any Objective-C class, that is, we can create custom data types other than the standard data types. This data type can be used to store an instance of UIColor, UIImage, and so on. It archives objects to instances of NSData. Below the Type drop-down menu, we will see a few more fields in the detail pane, as shown in the next screenshot: Fields applying constraints Min Length: and Max Length: fields are for applying constraints of minimum and maximum number of characters to an attribute. If we exceed the range supplied in these fields, we get a validation error. Meaning, if we enter the string of fewer characters than the value supplied in Min Length: or the string has more characters than the value supplied in Max Length: field, this will result in a validation error while saving managed objects. Reg. Ex: field stands for regular expression and is used for applying validation checks on the data entered in the attribute by making use of regular expressions. Default Value: field is for specifying default value of the attribute. If we create a new managed object, the attribute will automatically be set to the default value specified in this field. Let us add two more attributes to the Customer entity: emailid and contactno (for storing a customer's e-mail address and contact number, respectively). These two attributes will also be of type: String as shown in the next screenshot. Now, save the .xcdatamodel.
Read more
  • 0
  • 0
  • 13768
article-image-enhancing-page-elements-moodle-and-javascript
Packt
04 May 2011
7 min read
Save for later

Enhancing Page Elements with Moodle and JavaScript

Packt
04 May 2011
7 min read
  Moodle JavaScript Cookbook Over 50 recipes for making your Moodle system more dynamic and responsive with JavaScript Introduction The Yahoo! UI Library (YUI) offers a range of widgets and utilities to bring modern enhancements to your traditional page elements. In this chapter, we will look at a selection of these enhancements, including features often seen on modern interactive interfaces, such as: Auto-complete: This feature suggests possible values to the user by searching against a list of suggestions as they start typing. We will look at two different ways of using this. First, by providing suggestions as the user types into a text box, and second, by providing a list of possible values for them to select from a combo list box. Auto-update: This technique will allow us to update an area of the page based on a timed interval, which has many uses as we'll see. In this example, we will look at how to create a clock by updating the time on the page at one second intervals. This technique could also be used, for example, to update a news feed every minute, or update stock information every hour. Resizable elements: A simple enhancement which allows users to dynamically resize elements to suit their needs. This could be applied to elements containing a significant amount of text which would allow the user to control the width of the text to suit their personal preference for ideal readability. Custom tooltips: Tooltips appear when an element is hovered, displaying the associated title or alternative text (that is, a description of an image or the title of a hyperlink). This enhancement allows us to have more control over the look of the tooltips making them more visually appealing and more consistent with the overall look and feel of our page. Custom buttons: This enhancement allows us to completely restyle button elements, modifying their look and feel to be consistent with the rest of our page. This also allows us to have a consistent button style across different platforms and web browsers. We will once again be using mostly YUI Version 2 widgets and utilities within the YUI Version 3 framework. At the time of writing, few YUI2 widgets have been ported to YUI3. This method allows us the convenience of the improvements afforded by the YUI3 environment combined with the features of the widgets from YUI2. Adding a text box with auto-complete A common feature of many web forms is the ability to provide suggestions as the user types, based on a list of possible values. In this example, we enhance a standard HTML input text element with this feature. This technique is useful in situations where we simply wish to offer suggestions to the user that they may or may not choose to select, that is, suggesting existing tags to be applied to a new blog post. They can either select a suggested value that matches one they have started typing, or simply continue typing a new, unused tag. How to do it... First, set up a basic Moodle page in the usual way. In this example, we create autocomplete.php with the following content: <?php require_once(dirname(__FILE__) . '/../config.php'); $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); $PAGE->set_url('/cook/autocomplete.php'); $PAGE->requires->js('/cook/autocomplete.js', true); ?> <?php echo $OUTPUT->header(); ?> <div style="width:15em;height:10em;"> <input id="txtInput" type="text"> <div id="txtInput_container"></div> </div> <?php echo $OUTPUT->footer(); ?> Secondly, we need to create our associated JavaScript file, autocomplete.js, with the following code: YUI().use("yui2-autocomplete", "yui2-datasource", function(Y) { var YAHOO = Y.YUI2; var dataSource = new YAHOO.util.LocalDataSource ( ["Alpha","Bravo","Beta","Gamma","Golf"] ); var autoCompleteText = new YAHOO.widget.AutoComplete("txtInput", "txtInput_container", dataSource); }); How it works... Our HTML consists of three elements, a parent div element, and the other two elements contained within it: an input text box, and a placeholder div element to use to display the auto-complete suggestions. Our JavaScript file then defines a DataSource to be used to provide suggestions, and then creates a new AutoComplete widget based on the HTML elements we have already defined. In this example, we used a LocalDataSource for simplicity, but this may be substituted for any valid DataSource object. Once we have a DataSource object available, we instantiate a new YUI2 AutoComplete widget, passing the following arguments: The name of the HTML input text element for which to provide auto-complete suggestions The name of the container element to use to display suggestions A valid data source object to use to find suggestions Now when the user starts typing into the text box, any matching auto-complete suggestions are displayed and can be selected, as shown in the following screenshot: Adding a combo box with auto-complete In this example, we will use auto-complete in conjunction with a combo box (drop-down list). This differs from the previous example in one significant way—it includes a drop-down arrow button that allows the user to see the complete list of values without typing first. This is useful in situations where the user may be unsure of a suitable value. In this case, they can click the drop-down button to see suggestions without having to start guessing as they type. Additionally, this method also supports the same match-as-you-type style auto-complete as that of the previous recipe. How to do it... Open the autocomplete.php file from the previous recipe for editing, and add the following HTML below the text box based auto-complete control: <div style="width:15em;height:10em;"> <input id="txtCombo" type="text" style="vertical-align:top; position:static;width:11em;"><span id="toggle"></span> <div id="txtCombo_container"></div> </div> Next, open the JavaScript file autocomplete.js, and modify it to match the following code: YUI().use("yui2-autocomplete", "yui2-datasource", "yui2-element", "yui2-button", "yui2-yahoo-dom-event", function(Y) { var YAHOO = Y.YUI2; var dataSource = new YAHOO.util.LocalDataSource ( ["Alpha","Bravo","Beta","Gamma","Golf"] ); var autoCompleteText = new YAHOO.widget.AutoComplete("txtInput", "txtInput_container", dataSource); var autoCompleteCombo = new YAHOO.widget.AutoComplete("txtCombo", "txtCombo_container", dataSource, {minQueryLength: 0, queryDelay: 0}); var toggler = YAHOO.util.Dom.get("toggle"); var tButton = new YAHOO.widget.Button({container:toggler, label:"↓"}); var toggle = function(e) { if(autoCompleteCombo.isContainerOpen()) { autoCompleteCombo.collapseContainer(); } else { autoCompleteCombo.getInputEl().focus(); setTimeout(function() { autoCompleteCombo.sendQuery(""); },0); } } tButton.on("click", toggle); }); You will notice that the HTML we added in this recipe is very similar to the last, with the exception that we included a span element just after the text box. This is used as a placeholder to insert a YUI2 button control. This recipe is somewhat more complicated than the previous one, so we included some extra YUI2 modules: element, button, and yahoo-dom-event. We define the AutoComplete widget in the same way as before, except we need to add two configuration options in an object passed as the fourth argument. Next, we retrieve a reference to the button placeholder, and instantiate a new Button widget to use as the combo box 'drop-down' button. Finally, we define a click handler for the button, and register it. We now see the list of suggestions, which can be displayed by clicking on the drop-down button, as shown in the following screenshot: How it works... The user can type into the box to receive auto-complete suggestions as before, but may now use the combo box style drop-down button instead to see a list of suggestions. When the user clicks the drop-down button, the click event is fired. This click event does the following: Hides the drop-down menu if it is displayed, which allows the user to toggle this list display on/off. If it is not displayed, it sets the focus to the text box (to allow the user to continue typing), and execute a blank query on the auto-complete widget, which will display the list of suggestions. Note that we explicitly enabled this blank query earlier when we defined the AutoComplete widget with the "minQueryLength: 0" option, which allowed queries of length 0 and above.  
Read more
  • 0
  • 0
  • 5449

article-image-animation-effects-aspnet-using-jquery
Packt
03 May 2011
9 min read
Save for later

Animation Effects in ASP.NET using jQuery

Packt
03 May 2011
9 min read
  ASP.NET jQuery Cookbook Over 60 practical recipes for integrating jQuery with ASP.NET   Introduction Some useful inbuilt functions in jQuery that we will explore in this article for achieving animation effects are: animate ( properties, [ duration ], [ easing ], [ complete ] ): This method allows us to create custom animation effects on any numeric css property. The parameters supported by this method are: properties: This is the map of css properties to animate, for e.g. width, height, fontSize, borderWidth, opacity, etc. duration: This is the duration of the animation in milliseconds. The constants slow and fast can be used to specify the durations, and they represent 600 ms and 200 ms respectively. easing: This is the easing function to use. Easing indicates the speed of the animation at different points during the animation. jQuery provides inbuilt swing and linear easing functions. Various plugins can be interfaced if other easing functions are required. complete: This indicates the callback function on completion of the animation. fadeIn ( [ duration ], [ callback ] ): This method animates the opacity of the matched elements from 0 to 1 i.e. transparent to opaque. The parameters accepted are: duration: This is the duration of the animation callback: This is the callback function on completion of the animation fadeOut( [ duration ], [ callback ] ): This method animates the opacity of the matched elements from 1 to 0 i.e. opaque to transparent. The parameters accepted are: duration: This is the duration of the animation callback: This is the callback function on completion of the animation slideUp( [ duration ], [ callback ] ): This method animates the height of the matched elements with an upward sliding motion. When the height of the element reaches 0, the css property display of the element is updated to none so that the element is hidden on the page. The parameters accepted are: duration: This is the duration of the animation callback: This is the callback function on completion of the animation slideDown( [ duration ], [ callback ] ): This method animates the height of the matched elements from 0 to the specified maximum height. Thus, the element appears to slide down on the page. The parameters accepted are: duration: This is the duration of the animation callback: This is the callback function on completion of the animation slideToggle( [ duration ], [ callback ] ): This method animates the height of the matched elements. If the element is initially hidden, it will slide down and become completely visible. If the element is initially visible, it will slide up and become hidden on the page. The parameters accepted are: duration: This is the duration of the animation callback: This is the callback function on completion of the animation jQuery.fx.off: If there is a need to disable animations because of a resource constraint or due to difficulties in viewing the animations, then this utility can be used to turn off the animation completely. This is achieved by setting all animated controls to their final state. stop ( [ clearQueue ], [ jumpToEnd ] ): This method stops the currently running animations on the page. The parameters accepted are: clearQueue: This indicates whether any queued up animations are required to be cleared. The default value is false. jumpToEnd: This indicates if the current animation is to be cleared immediately. The default value is false. In this article, we will cover some of the animation effects that can be achieved in ASP.NET using the capabilities of jQuery. Getting started Let's start by creating a new ASP.NET website in Visual Studio and name it Chapter5. Save the jQuery library in a script folder js in the project. To enable jQuery on any web form, drag-and-drop to add the following to the page: <scriptsrc="js/jquery-1.4.1.js" type="text/javascript"></script> Now let's move on to the recipes where we will see different animation techniques using jQuery. Enlarging text on hover In this recipe, we will animate the font size of text content on hover. Getting ready Add a new web form Recipe1.aspx to the current project. Create a Css class for the text content that we want to animate. The font size specified in the css Class is the original font size of the text before animation is applied to it: .enlarge { font-size:12.5px; font-family:Arial,sans-serif; } Add an ASP.NET Label control on the form and set its Css Class to the preceding style: <asp:LabelCssClass="enlarge"runat="server">Lorem ipsum dolor sit ...............</asp:Label> Thus, the ASPX markup of the form is as follows: <form id="form1" runat="server"> <div align="center"> Mouseover to enlarge text:<br /> <fieldset id="content" style="width:500px;height:300px;"> <asp:LabelCssClass="enlarge" runat="server">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</ asp:Label> </fieldset> </div> </form> Thus, initially, the page will display the Label control as follows: We will now animate the font size of the Label on hover on the containing fieldset element. How to do it… In the document.ready() function of the jQuery script block, retrieve the original font size of the Label: var origFontSize = parseFloat($(".enlarge").css('font-size')); The parseFloat() function takes in an input string and returns the first floating point value in the string. It discards any content after the floating point value. For example, if the css property returns 12.5 px, then the function will discard the px. Define the hover event of the containing fieldset element: $("#content").hover( In the mouseenter event handler of the hover method, update the cursor style to pointer: function() { $(".enlarge").css("cursor", "pointer"); Calculate the maximum font size that we want to animate to. In this example, we will set the maximum size to thrice the original: var newFontSize = origFontSize * 3; Animate the fontSize css property of the Label in 300 ms: $(".enlarge").animate({ fontSize: newFontSize }, 300); }, In the mouseleave event handler of the hover method, animate the fontSize to the original value in 300 ms as shown: function() { $(".enlarge").animate({ fontSize: origFontSize }, 300); } ); Thus, the complete jQuery solution is as follows: <script language="javascript" type="text/javascript"> $(document).ready(function() { var origFontSize = parseFloat($(".enlarge").css('fontsize')); $("#content").hover( function() { $(".enlarge").css("cursor", "pointer"); var newFontSize = origFontSize * 3; $(".enlarge").animate({ fontSize: newFontSize }, 300); }, function() { $(".enlarge").animate({ fontSize: origFontSize }, 300); } ); }); </script> How it works… Run the web form. Mouseover on the fieldset area. The text size will animate over the stated duration and change to the maximum specified font size as displayed in the following screenshot: On removing the mouse from the fieldset area, the text size will return back to the original. Creating a fade effect on hover In this recipe, we will create a fade effect on an ASP.NET Image control on hover. We will use the fadeIn and fadeOut methods to achieve the same. Getting ready Add a new web form Recipe2.aspx to the current project. Add an image control to the form: <asp:Image src="images/Image1.jpg" ID="Image1" runat="server" /> Define the properties of the image in the css: #Image1 { width:438px; height:336px; } Thus, the complete ASPX markup of the web form is as follows: <form id="form1" runat="server"> <div align="center"> Mouseover on the image to view fade effect: <fieldset id="content" style="width:480px;height:370px;"> <br /> <asp:Image src="images/Image1.jpg" ID="Image1" runat="server" /> </fieldset> </div> </form> On page load, the image is displayed as follows: We will now create a fade effect on the image on hover on the containing fieldset area. How to do it… In the document.ready() function of the jQuery script block, define the hover event on the containing fieldset area: $("#content").hover( In the mouseenter event handler of the hover method, update the cursor to pointer: function() { $("#Image1").css("cursor", "pointer"); Apply the fadeOut method on the Image control with an animation duration of 1000 ms: $("#Image1").fadeOut(1000); }, In the mouseleave event handler of the hover method, apply the fadeIn method on the Image control with an animation duration of 1000 ms: function() { $("#Image1").fadeIn(1000); } ); Thus, the complete jQuery solution is as follows: <script language="javascript" type="text/javascript"> $(document).ready(function() { $("#content").hover( function() { $("#Image1").css("cursor", "pointer"); $("#Image1").fadeOut(1000); }, function() { $("#Image1").fadeIn(1000); } ); }); </script> How it works... Run the web page. Mouseover on the Image control on the web page. The image will slowly fade away as shown in the following screenshot: On mouseout from the containing fieldset area, the image reappears. Sliding elements on a page In this recipe, we will use the slideUp and slideDown methods for achieving sliding effects on an ASP.NET panel. Getting ready Add a new web form Recipe3.aspx in the current project. Add an ASP.NET panel to the page as follows: <asp:Panel class="slide" runat="server"> Sliding Panel </asp:Panel> The css class for the panel is defined as follows: .slide { font-size:12px; font-family:Arial,sans-serif; display:none; height:100px; background-color:#9999FF; } Add a button control to trigger the sliding effect on the panel: <asp:Button ID="btnSubmit" runat="server" Text="Trigger Slide" /> Thus, the complete ASPX markup of the web form is as follows: <form id="form1" runat="server"> <div align="center"> <fieldset style="width:400px;height:150px;"> <asp:Button ID="btnSubmit" runat="server" Text="Trigger Slide" /> <br /><br/> <asp:Panel class="slide" runat="server"> Sliding Panel </asp:Panel> </fieldset> </div> </form> On page load, the page appears as shown in the following screenshot: We will now use jQuery to slide up and slide down the panel. How to do it… In the document.ready() function of the jQuery script block, define the click event of the button control: $("#btnSubmit").click(function(e) { Prevent default form submission: e.preventDefault(); Check if the ASP.NET panel control is hidden: if ($(".slide").is(":hidden")) The jQuery selector :hidden selects matched elements that are hidden on the page. If yes, then slide down the panel until its height reaches the maximum (100 px) defined in the css property. $(".slide").slideDown("slow"); If the panel is initially visible then slide up so that its height slowly reduces until it becomes 0 and the panel disappears from the page: else $(".slide").slideUp("slow"); }); Thus, the complete jQuery solution is as follows: <script language="javascript" type="text/javascript"> $(document).ready(function() { $("#btnSubmit").click(function(e) { e.preventDefault(); if ($(".slide").is(":hidden")) $(".slide").slideDown("slow"); else $(".slide").slideUp("slow"); }); }); </script>  
Read more
  • 0
  • 0
  • 13230
Modal Close icon
Modal Close icon