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-understand-and-use-microsoft-silverlight-javascript
Packt
24 Oct 2009
10 min read
Save for later

Understand and Use Microsoft Silverlight with JavaScript

Packt
24 Oct 2009
10 min read
We have come a long way from the day the WEB was created in 1992 by T.B.LEE in Switzerland. From hyper linking which was the only thing at that time, to streaming videos, instant gratification with AJAX, and a host of other do-dads that has breathed new life to JavaScript and internet usability. Silverlight among several others, is a push in this direction to satisfy the ever increasing needs of the internet users. Even so, the web application displays fall short of the rich experience one can achieve with desktop applications, and this is where the tools are being created and honed for creating RIA, short for Rich Internet Applications. In order to create such applications, a great deal of development has taken place in the Microsoft ecosystem . These are all described in the .NET and Windows Presentation Foundation which supports developers to create easily deployable Rich Internet Applications. We have to wait and see how it percolates to the Semantic Web in the future. Silverlight is a cross-platform, cross-browser plug-in that renders XAML, the declarative tag-based files while exposing the JavaScript programming interface. It makes both developers and designers to collaborate and contribute to rich and interactive designs that are well integrated with Microsoft's Expression series of programs. Initial Steps to Take In this article we will be using Silverlight 1.0 with JavaScript. Initially you need to make your browser understand the XAML, and for this you need to install Silverlight available here. There is no need for a server to work with these Silverlight application files as they will be either HTML pages, XAML pages, or JavaScript pages. Of course these files may be hosted on the server as well. The next figure shows some details you need to know before installing the plug-in. Silverlight Project Details After having enabled the browser to recognize XAML - the Extensible Application Mark up Language, you need to consider the different components that will make Silverlight happen. In the present tutorial we will look at using Silverlight 1.0. Silverlight 2.0 is still in Beta stage. If you have Silverlight already installed you may be able to verify the version in the Control Panel / Add Remove Programs and display information as shown in the next figure. To make Silverlight happen you need the following files: An HTML page that you can browse to where the Silverlight plug-in is spawned A XAML page which is all the talk is about which provides the 'Richness' Supporting script files that will create the plug-in and embeds it in the HTML page The next figure shows how these interact with one another somewhat schematically. Basically you can start with your HTML page. You need to reference two .JS files as shown in the above figure. The script file Silverlight.js exposes the properties, methods, etc. of Silverlight. This file will be available in the SDK download. You can copy this file and move it around to any location. The second script createSilvelight.js creates a plug-in which you will embed in the HTML page using yet another short script. You will see how this is created later in the tutorial. The created plug-in then brings-in the XAML page which you will create as well. The first step is to create a blank HTML page, herein called, TestSilverLight.htm as shown in the following listing: Listing 1:TestSilverLight.htm Scaffold file <html><head><script type="text/javascript" src="Silverlight.js"></script><script type="text/javascript" src="createSilverlight.js"></script><title> </title> </head> <body> Next, you go ahead and create the createSilvelight.js file. The following listing shows how this is coded. This is slightly modified although taken from a web resource. Listing 2: createSilverlight.js function createSilverlight() { Silverlight.createObject( "TestSilver.xaml", // Source property value. parentElement, // DOM reference to hosting DIV tag. "SilverlightPlugInHost1", // Unique plug-in ID value. { // Plug-in properties. width:'1024', // Width of rectangular in pixels. height:'530', // Height of rectangular in pixels. inplaceInstallPrompt:false, // install prompt if invalid version is detected. background:'white', // Background color of plug-in. isWindowless:'false', // Determines whether to display in windowless mode. framerate:'24', // MaxFrameRate property value. version:'1.0' // Silverlight version. }, { onError:null, // OnError property value onLoad:null // OnLoad property value }, null, // initParams null); // Context value } This function, createSilverlight(), when called from within a place holder location will create a Silverlight object at that location with some defined properties. You may go and look up the various customizable items in this code on the web. The object that is going to be created will be the TestSilver.xaml at the "id" of the location which will be found using the ECMA script we will see later. The "id" is also named here, found by the "parentElement". To proceed further we need to create (a) the TestSilver.xaml file and (b) create a place holder in the HTML page. At first the changes made to Listing 1 are shown in bold. This is the place holder <div> </div> tags inside the 'body' tags as shown in the next listing with the "id" used in the createSilverlight.js file. You may also use <span> </span> tags, provided you associate a "id" with it. Listing 3: Place holder created in the HTML Page <head><script type="text/javascript" src="Silverlight.js"></script><script type="text/javascript" src="createSilverlight.js"></script><title> </title> </head> <body><div id="SilverlightPlugInHost1"> </div></body> </html> Creating the XAML File If you have neither used XAML, nor created a XAML page you should access the internet where you will find tons of this stuff. A good location is MSDN's Silvelight home page. You may also want to read up this article which will give some idea about XAML. Although this article is focusing on 'Windows' and not 'Web', the idea of what XAML is the same. The next listing describes the declarative syntax that will show a 'canvas', a defined space on your web page in which an image has been brought in. The 'Canvas' is the container and the image is the contained object. A XAML file should be well formed similar to an XML file. Listing 4: A Simple XAML file <Canvas Width="200" Height="200" Background="powderblue"><Image Canvas.Left="50" Canvas.Top="50" Width="200"Source="Fish.JPG"/></Canvas> Save the above file (text) with the extension XAML. If your Silverlight 1.0 is working correctly you should see this displayed on the browser when you browse to it. You also note the [.] notation to access the properties of the Canvas. For example, Canvas.Left is 50 pixels relative to the Canvas. The namespace is very important, more about it later. Without going into too much details, the pale blue area is the canvas whose width and height are 200 pixels each. The fish image is off set by the amounts shown relative to the canvas. Canvas is the portion of the browser window which functions as a place holder. While you use "Canvas" in web, you will have "Window" for desktop applications. The namespace of the canvas should be as shown otherwise you may get errors of various types depending on the typos. Inside the canvas you may place any type of object, buttons, textboxes, shapes, and even other canvases. If and when you design using the Visual Studio designer with intellisense guiding you along you will see a bewildering array of controls, styles, etc. The details of the various XAML tags are outside the scope of this tutorial. Although Notepad is used in this tutorial, you really should use a designer as you cannot possibly remember correctly the various Properties, Methods and Events supported. In some web references you may notice one more additional namespace . Remove this namespace reference as "Canvas" does not exist in this namespace. If you use it, you will get an XamlParseException. Also if you are of the cut and paste type make sure you save the XAML file as of type "All files" with XAML extension. With the above brief background review the TestSilver.xaml file whose listing is shown in the next paragraph. Listing 5: TestSilver.xaml file referenced in Plug-in script <Canvas Width="200" Height="150" Background="powderblue"> <Canvas Width="150" Height="250" Background="PaleGoldenRod"> <Ellipse Width="100" Height="100" Stroke="Black" StrokeThickness="2" Fill="Green" /> </Canvas><Image Canvas.Left="50" Canvas.Top="50" Width="200" Source="http://localhost/IMG_0086.JPG"/></Canvas> In the above code you see a second canvas embedded inside the first with its own independent window. The order they would appear will depend on where they are in the code unless the default order is changed. You also see that the image is now referenced to a graphic file on the local server. Later on you will see the Silverlight.htm hosted on the server. If you are using more recent versions of ASP.NET used on your site, or version of IE you may get to see the complete file and some times you may get to see only part of the XMAL content and additional error message such as this one. For example, while the image in the project folder is displayed, the image on the local server may be skipped. If the setting and versions are optimum, you will get to see this displayed on your browser when you browse to the above file. Script in HTML to Embed Silverlight Plug-in This really is the last piece left to be taken care of to complete this project. The code shown in the next listing shows how this is done. The code segment shown in bold is the script that is added to the place holder we created earlier. Listing 6: Script added to bring Plug-in <html><head><script type="text/javascript" src="Silverlight.js"></script><script type="text/javascript" src="createSilverlight.js"></script><title> </title> </head> <body><div id="SilverlightPlugInHost1"> <script type="text/javascript"> var parentElement = document.getElementById("SilverlightPluginHost1"); createSilverlight();</script></div></body> </html> Hosted Files on the IIS The various files used are then saved to a folder and can be set up as the target of a virtual directory on your IIS as shown. Now you can browse the Silverlight123.htm file on your browser to see the following displayed on your IE. Summary The present tutorial shows how to create a Silverlight project describing the various files used and how they interact with each other. The importance of using the correct namespace and some tips on creating the XAML files as well as hosting them on IIS are also described. A Windows XP with SP2 was used and the Silverlight.htm file tested on IIS 5.1; IE Ver 7.0.5370IC and web site enabled for ASP.NET Version 2.0.50727 with the registered MimeType application/xaml+xml.
Read more
  • 0
  • 0
  • 5305

Packt
23 Jun 2014
10 min read
Save for later

Kendo UI DataViz – Advance Charting

Packt
23 Jun 2014
10 min read
(For more resources related to this topic, see here.) Creating a chart to show stock history The Kendo UI library provides a specialized chart widget that can be used to display the stock price data for a particular stock over a period of time. In this recipe, we will take a look at creating a Stock chart and customizing it. Getting started Include the CSS files, kendo.dataviz.min.css and kendo.dataviz.default.min.css, in the head section. These files are used in styling some of the parts of a stock history chart. How to do it… A Stock chart is made up of two charts: a pane that shows you the stock history and another pane that is used to navigate through the chart by changing the date range. The stock price for a particular stock on a day can be denoted by the following five attributes: Open: This shows you the value of the stock when the trading starts for the day Close: This shows you the value of the stock when the trading closes for the day High: This shows you the highest value the stock was able to attain on the day Low: This shows you the lowest value the stock reached on the day Volume: This shows you the total number of shares of that stock traded on the day Let's assume that a service returns this data in the following format: [ { "Date" : "2013/01/01", "Open" : 40.11, "Close" : 42.34, "High" : 42.5, "Low" : 39.5, "Volume": 10000 } . . . ] We will use the preceding data to create a Stock chart. The kendoStockChart function is used to create a Stock chart, and it is configured with a set of options similar to the area chart or Column chart. In addition to the series data, you can specify the navigator option to show a navigation pane below the chart that contains the entire stock history: $("#chart").kendoStockChart({ title: { text: 'Stock history' }, dataSource: { transport: { read: '/services/stock?q=ADBE' } }, dateField: "Date", series: [{ type: "candlestick", openField: "Open", closeField: "Close", highField: "High", lowField: "Low" }], navigator: { series: { type: 'area', field: 'Volume' } } }); In the preceding code snippet, the DataSource object refers to the remote service that would return the stock data for a set of days. The series option specifies the series type as candlestick; a candlestick chart is used here to indicate the stock price for a particular day. The mappings for openField, closeField, highField, and lowField are specified; they will be used in plotting the chart and also to show a tooltip when the user hovers over it. The navigator option is specified to create an area chart, which uses volume data to plot the chart. The dateField option is used to specify the mapping between the date fields in the chart and the one in the response. How it works… When you load the page, you will see two panes being shown; the navigator is below the main chart. By default, the chart displays data for all the dates in the DataSource object, as shown in the following screenshot: In the preceding screenshot, a candlestick chart is created and it shows you the stock price over a period of time. Also, notice that in the navigator pane, all date ranges are selected by default, and hence, they are reflected in the chart (candlestick) as well. When you hover over the series, you will notice that the stock quote for the selected date is shown. This includes the date and other fields such as Open, High, Low, and Close. The area of the chart is adjusted to show you the stock price for various dates such that the dates are evenly distributed. In the previous case, the dates range from January 1, 2013 to January 31, 2013. However, when you hover over the series, you will notice that some of the dates are omitted. To overcome this, you can either increase the width of the chart area or use the navigator to reduce the date range. The former option is not advisable if the date range spans across several months and years. To reduce the date range in the navigator, move the two date range selectors towards each other to narrow down the dates, as shown in the following screenshot: When you try to narrow down the dates, you will see a tooltip in the chart, indicating the date range that you are trying to select. The candlestick chart is adjusted to show you the stock price for the selected date range. Also, notice that the opacity of the selected date range in the navigator remains the same while the rest of the area's opacity is reduced. Once the date range is selected, the selected pane can be moved in the navigator. There's more… There are several options available to you to customize the behavior and the look and feel of the Stock Chart widget. Specifying the date range in the navigator when initializing the chart By default, all date ranges in the chart are selected and the user will have to narrow them down in the navigator pane. When you work with a large dataset, you will want to show the stock data for a specific range of date when the chart is rendered. To do this, specify the select option in navigator: navigator: { series: { type: 'area', field: 'Volume' }, select: { from: '2013/01/07', to: '2013/01/14' } } In the previous code snippet, the from and to date ranges are specified. Now, when you render the page, you will see that the same dates are selected in the navigator pane. Customizing the look and feel of the Stock Chart widget There are various options available to customize the navigator pane in the Stock Chart widget. Let's increase the height of the pane and also include a title text for it: navigator: { . . pane: { height: '50px', title: { text: 'Stock Volume' } } } Now when you render the page, you will see that the title and height of the navigator pane have been increased. Using the Radial Gauge widget The Radial Gauge widget allows you to build a dashboard-like application wherein you want to indicate a value that lies in a specific range. For example, a car's dashboard can contain a couple of Radial Gauge widgets that can be used to indicate the current speed and RPM. How to do it… To create a Radial Gauge widget, invoke the kendoRadialGauge function on the selected DOM element. A Radial Gauge widget contains some components, and it can be configured by providing options, as shown in the following code snippet: $("#chart").kendoRadialGauge({ scale: { startAngle: 0, endAngle: 180, min: 0, max: 180 }, pointer: { value: 20 } }); Here the scale option is used to configure the range for the Radial Gauge widget. The startAngle and endAngle options are used to indicate the angle at which the Radial Gauge widget's range should start and end. By default, its values are 30 and 210, respectively. The other two options, that is, min and max, are used to indicate the range values over which the value can be plotted. The pointer option is used to indicate the current value in the Radial Gauge widget. There are several options available to configure the Radial Gauge widget; these include positioning of the labels and configuring the look and feel of the widget. How it works… When you render the page, you will see a Radial Gauge widget that shows you the scale from 0 to 180 and the pointer pointing to the value 20. Here, the values from 0 to 180 are evenly distributed, that is, the major ticks are in terms of 20. There are 10 minor ticks, that is, ticks between two major ticks. The widget shows values in the clockwise direction. Also, the pointer value 20 is selected in the scale. There's more… The Radial Gauge widget can be customized to a great extent by including various options when initializing the widget. Changing the major and minor unit values Specify the majorUnit and minorUnit options in the scale: scale: { startAngle: 0, endAngle: 180, min: 0, max: 180, majorUnit: 30, minorUnit: 10, } The scale option specifies the majorUnit value as 30 (instead of the default 20) and minorUnit as 10. This will now add labels at every 30 units and show you two minor ticks between the two major ticks, each at a distance of 10 units, as shown in the following screenshot: The ticks shown in the preceding screenshot can also be customized: scale: { . . minorTicks: { size: 30, width: 1, color: 'green' }, majorTicks: { size: 100, width: 2, color: 'red' } } Here, the size option is used to specify the length of the tick marker, width is used to specify the thickness of the tick, and the color option is used to change the color of the tick. Now when you render the page, you will see the changes for the major and minor ticks. Changing the color of the radial using the ranges option The scale attribute can include the ranges option to specify a radial color for the various ranges on the Radial Gauge widget: scale: { . . ranges: [ { from: 0, to: 60, color: '#00F' }, { from: 60, to: 130, color: '#0F0' }, { from: 130, to: 200, color: '#F00' } ] } In the preceding code snippet, the ranges array contains three objects that specify the color to be applied on the circumference of the widget. The from and to values are used to specify the range of tick values for which the color should be applied. Now when you render the page, you will see the Radial Gauge widget showing the colors for various ranges along the circumference of the widget, as shown in the following screenshot: In the preceding screenshot, the startAngle and endAngle fields are changed to 10 and 250, respectively. The widget can be further customized by moving the labels outside. This can be done by specifying the labels attribute with position as outside. In the preceding screenshot, the labels are positioned outside, hence, the radial appears inside. Updating the pointer value using a Slider widget The pointer value is set when the Radial Gauge widget is initialized. It is possible to change the pointer value of the widget at runtime using a Slider widget. The changes in the Slider widget can be observed, and the pointer value of the Radial Gauge can be updated accordingly. Let's use the Radial Gauge widget. A Slider widget is created using an input element: <input id="slider" value="0" /> The next step is to initialize the previously mentioned input element to a Slider widget: $('#slider').kendoSlider({ min: 0, max: 200, showButtons: false, smallStep: 10, tickPlacement: 'none', change: updateRadialGuage }); The min and max values specify the range of values that can be set for the slider. The smallStep attribute specifies the minimum increment value of the slider. The change attribute specifies the function that should be invoked when the slider value changes. The updateRadialGuage function should then update the value of the pointer in the Radial Gauge widget: function updateRadialGuage() { $('#chart').data('kendoRadialGauge') .value($('#slider').val()); } The function gets the instance of the widget and then sets its value to the value obtained from the Slider widget. Here, the slider value is changed to 100, and you will notice that it is reflected in the Radial Gauge widget.
Read more
  • 0
  • 0
  • 5304

article-image-installing-and-configuring-joomla-local-and-remote-servers
Packt
27 May 2010
8 min read
Save for later

Installing and Configuring Joomla! on Local and Remote Servers

Packt
27 May 2010
8 min read
Like every other endeavor in life, there are two ways of installing Joomla!—the easy way and the difficult way. In order to do it the difficult way, you will need to set up your server by yourself before you proceed with the installation. You have the choice of environment to use for your new installation: you may install directly to a live server or you can set up a test environment on your local computer. Minimum system requirements A fully-operational web server (preferably Apache) is required to successfully install and use Joomla!. You also need a database (preferably MySQL) and the server-side scripting language PHP, together with specific modules for MySQL, XML, and Zlib functionality, which are activated within PHP amongst others. Following are the minimum versions of these server components that are required: Software Minimum requirement Recommended Latest options Website PHP 4.3.10 4.4.7 5.x.series http://php.net MySQL 3.23.x or above   5.x series http://dev.mysql.com/downloads/mysql/5.0.html Apache 1.3 or above   2.2 series http://httpd.apache.org Installation on a local computer There are a number of ways to set up a test environment on your own local computer. Most time-pressed developers will install and configure directly onto a live server, but there are good reasons for running your application first on a local development server: Developing your application locally allows you to work on it even if you are not connected to the Internet. The experience that you gain from getting your local server running on a simple installation like WampServer for a machine running Windows, or MAMP for a Mac, will make it easier for you to understand server processes and databases. This knowledge will certainly pay off as you get deeper into Joomla!. The Web is constantly scanned and archived by various search engines, and so will everything that you put on the Web. This information will be around for quite a bit of time and you certainly don't want Google to display your inevitable learning mistakes for the world to see. Installation on WampServer WampServer2 enables you to run Apache, MySQL, and PHP on Windows, and is available for free. You can download it from http://www.wampserver.com. The WampServer2 package comes with the following components already configured to work together: Apache 2.2.11 MySQL 5.1.30 PHP 5.2.8 There are similar packages that already include Joomla! (such as DeveloperSide and WDE). However, note that these may not always have the latest secure version of Joomla!. Therefore, it is better to use WampServer2 and load it with the Joomla! version of your choice. WampServer2 is self-installing. Just double-click on the icon after you've unpacked your zipped download and follow the installation instructions. This gets your development environment ready in just a few minutes. Now let the fun begin! Installing Joomla! 1.5 on localhost Installing Joomla! on localhost can be remarkably straightforward: Download the latest stable release of Joomla!, and unzip the discernible Joomla! 1.5 folder. You will need to use a tool such as WinZip for Windows (http://www.winzip.com) to perform this task. Another free alternative to WinZip is IZArc (http://www.izarc.org/). Locate the directory in which WampServer2 is installed on your computer. This will usually be the root of your computer's main directory (usually C:) and in a folder named wamp. Open it, locate the www folder, and copy your Joomla! 1.5 folder into it. Name the Joomla! folder as per your preference. In the unlikely scenario that you will be installing only one Joomla! test site on your local machine, you may—just for the sake of living to a ripe old age—name it Joomla. Navigate to your computer desktop taskbar tray, click on the WampServer icon, and select the Start All Services option (if this has not yet been selected). Then open your browser and navigate to http://localhost. This will display the main WampServer2 interface and you will see your project, Joomla, listed under Your Projects. However, because Joomla! needs a database to run, you must create the database for our project. Click on the phpMyAdmin link. This will display another interface, this time for phpMyAdmin. Enter the name of your new database in the Create new database field. For the simple reason that we shouldn't live a complicated life, we have given this database the same name (Joomla) as our project and our installation folder. We are now ready to install Joomla!. Joomla! has an automated installation script that automatically populates database tables. The installation script will set the base URL, connect Joomla! to the database, and create tables in the database. Navigate to http://localhost/Joomla and start your installation. You will be presented with a step-by-step guide to the installation in the later pages. Page 1: Choose Language This page asks what language you want to use for the installation. We select English as the language of choice. Click on the Next button to continue with your installation. Page 2: Pre-installation Check Checks are made by the installation script on server configuration. If any of these items are not supported (marked as No), then your system does not meet the minimum requirements for the installation of Joomla!, and you should take the appropriate actions in order to correct the errors. Failing to do so could lead to your Joomla! installation not functioning properly. You are not likely to face this problem on your local installation, and if you do, it can be quickly fixed. Page 3: License The License page is just a page of legalese that the developers of Joomla! really think you must read. It tells you the conditions for use of the free software and also spells out liabilities. Primarily, if the Joomla! installation makes your computer to explode or you start acting funny after you are done with the installation, the suppliers of Joomla! will accept no liability. After correcting any host-specific errors and reading the license, you will be directed to the Database Configuration page. Page 4: Database Configuration On the Database Configuration page, you specify the database where Joomla! will store and retrieve data. Select the type of database from the drop-down list. This will generally be mysql. Also, enter the hostname of the database server that Joomla! will be installed on. This may not necessarily be the same as your web server, so check with your hosting provider if you are not sure. In the present case, it will be localhost. Now enter the MySQL username, password, and database name that you wish to use with Joomla!. These must already exist for the database that you are going to use. We have already determined this when we created the data base. Here are the values for our present project: Host Name: localhost Username: root (unless you have changed it) Password: Leave blank (unless you added a password when you set up your database) Database Name: Joomla (or whatever you have called yours) Table Prefix: If you are installing more than one instance of Joomla! in a single database, then give one of them a prefix (such as jos2_), or else the second instance will not install. Otherwise, you may safely ignore this. Click on the Next button to continue. Page 5: FTP Configuration You can safely omit this step and go on to the next page. But if you do decide to carry out this step, do take notice of the following requirements: As explained on this Joomla! installation page, due to file system permission restrictions on Linux and other Unix systems (and PHP Safe Mode restrictions), an FTP layer is used to handle fi le system manipulation and to enable Joomla! installers. You may enter an FTP username and password with access to the Joomla! root directory. This will be the FTP account that handles all of the file system operations when Joomla! requires FTP access to complete a task. However, for security reasons, if the option is available, you are advised to create a separate FTP user account with access to the Joomla! installation only and not to the entire web server. Page 6: Main Configuration This is where you define your site's public identity. The descriptions of the fields are as follows: Site Name: Enter the name of your Joomla! site. Your E-mail: This will be the e-mail address of the website Super Administrator. Admin Password: Enter a new password and then confirm it, in the appropriate fields. Along with the username admin, this will be the password that you will use to login to the Administrator Control Panel at the end of the installation. Install Sample Data: It is strongly recommended that new Joomla! users install the default sample data. To do this, select this option and click on the button, before proceeding to the next stage. Page 7: Finish That's all! Your installation success screen will be displayed. Congratulations, you are now on your way to becoming a Joomla! Guru. Once the installation script has successfully been completed and you have removed the installation folder, you will be directed to the Joomla! Administration login page—if you want to immediately perform administrative functions on your new site. Otherwise, clicking on the Site icon will direct you to the front page of your site showing all of the sample data—if you have loaded it. That is the most of what you need to know about installing Joomla!.
Read more
  • 0
  • 0
  • 5294

Packt
14 Feb 2014
6 min read
Save for later

CreateJS – Performing Animation and Transforming Function

Packt
14 Feb 2014
6 min read
(For more resources related to this topic, see here.) Creating animations with CreateJS As you may already know, creating animations in web browsers during web development is a difficult job because you have to write code that has to work in all browsers; this is called browser compatibility. The good news is that CreateJS provides modules to write and develop animations in web browsers without thinking about browser compatibility. CreateJS modules can do this job very well and all you need to do is work with CreateJS API. Understanding TweenJS TweenJS is one of the modules of CreateJS that helps you develop animations in web browsers. We will now introduce TweenJS. The TweenJS JavaScript library provides a simple but powerful tweening interface. It supports tweening of both numeric object properties and CSS style properties, and allows you to chain tweens and actions together to create complex sequences.—TweenJS API Documentation What is tweening? Let us understand precisely what tweening means: Inbetweening or tweening is the process of generating intermediate frames between two images to give the appearance that the first image evolves smoothly into the second image.—Wikipedia The same as other CreateJS subsets, TweenJS contains many functions and methods; however, we are going to work with and create examples for specific basic methods, based on which you can read the rest of the documentation of TweenJS to create more complex animations. Understanding API and methods of TweenJS In order to create animations in TweenJS, you don't have to work with a lot of methods. There are a few functions that help you to create animations. Following are all the methods with a brief description: get: It returns a new tween instance. to: It queues a tween from the current values to the target properties. set: It queues an action to set the specified properties on the specified target. wait: It queues a wait (essentially an empty tween). call: It queues an action to call the specified function. play: It queues an action to play (un-pause) the specified tween. pause: It queues an action to pause the specified tween. The following is an example of using the Tweening API: var tween = createjs.Tween.get(myTarget).to({x:300},400). set({label:"hello!"}).wait(500).to({alpha:0,visible:false},1000). call(onComplete); The previous example will create a tween, which: Tweens the target to an x value of 300 with duration 400ms and sets its label to hello!. Waits 500ms. Tweens the target's alpha property to 0with duration 1s and sets the visible property to false. Finally, calls the onComplete function. Creating a simple animation Now, it's time to create our simplest animation with TweenJS. It is a simple but powerful API, which gives you the ability to develop animations with method chaining. Scenario The animation has a red ball that comes from the top of the Canvas element and then drops down. In the preceding screenshot, you can see all the steps of our simple animation; consequently, you can predict what we need to do to prepare this animation. In our animation,we are going to use two methods: get and to. The following is the complete source code for our animation: var canvas = document.getElementById("canvas"); var stage = new createjs.Stage(canvas); var ball = new createjs.Shape(); ball.graphics.beginFill("#FF0000").drawCircle(0, 0, 50); ball.x = 200; ball.y = -50; var tween = createjs.Tween.get(ball) to({ y: 300 }, 1500, createjs.Ease.bounceOut); stage.addChild(ball); createjs.Ticker.addEventListener("tick", stage); In the second and third line of the JavaScript code snippet, two variables are declared, namely; the canvas and stage objects. In the next line, the ball variable is declared, which contains our shape object. In the following line, we drew a red circle with the drawCircle method. Then, in order to set the coordinates of our shape object outside the viewport, we set the x axis to -50 px. After this, we created a tween variable, which holds the Tween object; then, using the TweenJS method chaining, the to method is called with duration of 1500 ms and the y property set to 300 px. The third parameter of the to method represents the ease function of tween, which we set to bounceOut in this example. In the following lines, the ball variable is added to Stage and the tick event is added to the Ticker class to keep Stage updated while the animation is playing. You can also find the Canvas element in line 30, using which all animations and shapes are rendered in this element. Transforming shapes CreateJS provides some functions to transform shapes easily on Stage. Each DisplayObject has a setTransform method that allows the transforming of a DisplayObject (like a circle). The following shortcut method is used to quickly set the transform properties on the display object. All its parameters are optional. Omitted parameters will have the default value set. setTransform([x=0] [y=0] [scaleX=1] [scaleY=1] [rotation=0] [skewX=0] [skewY=0] [regX=0] [regY=0]) Furthermore, you can change all the properties via DisplayObject directly (like scaleY and scaleX) as shown in the following example: displayObject.setTransform(100, 100, 2, 2); An example of Transforming function As an instance of using the shape transforming feature with CreateJS, we are going to extend our previous example: var angle = 0; window.ball; var canvas = document.getElementById("canvas"); var stage = new createjs.Stage(canvas); ball = new createjs.Shape(); ball.graphics.beginFill("#FF0000").drawCircle(0, 0, 50); ball.x = 200; ball.y = 300; stage.addChild(ball); function tick(event) { angle += 0.025; var scale = Math.cos(angle); ball.setTransform(ball.x, ball.y, scale, scale); stage.update(event); } createjs.Ticker.addEventListener("tick", tick); In this example, we have a red circle, similar to the previous example of tweening. We set the coordinates of the circle to 200 and 300 and added the circle to the stage object. In the next line, we have a tick function that transforms the shape of the circle. Inside this function, we have an angle variable that increases with each call. We then set the ballX and ballY coordinate to the cosine of the angle variable. The transforming done is similar to the following screenshot: This is a basic example of transforming shapes in CreateJS, but obviously, you can develop and create better transforming by playing with a shape's properties and values. Summary In this article, we covered how to use animation and transform objects on the page using CreateJS. Resources for Article: Further resources on this subject: Introducing a feature of IntroJs [Article] So, what is Node.js? [Article] So, what is Ext JS? [Article]
Read more
  • 0
  • 0
  • 5275

article-image-migrating-wordpress-blog-middleman-and-deploying-to-amazon-part3
Mike Ball
09 Feb 2015
9 min read
Save for later

Part 3: Migrating a WordPress Blog to Middleman and Deploying to Amazon S3

Mike Ball
09 Feb 2015
9 min read
Part 3: Migrating WordPress blog content and deploying to production In parts 1 and 2 of this series, we created middleman-demo, a basic Middleman-based blog, imported content from WordPress, and deployed middleman-demo to Amazon S3. Now that middleman-demo has been deployed to production, let’s design a continuous integration workflow that automates builds and deployments. In part 3, we’ll cover the following: Testing middleman-demo with RSpec and Capybara Integrating with GitHub and Travis CI Configuring automated builds and deployments from Travis CI If you didn’t follow parts 1 and 2, or you no longer have your original middleman-demo code, you can clone mine and check out the part3 branch:  $ git clone http://github.com/mdb/middleman-demo && cd middleman-demo && git checkout part3 Create some automated tests In software development, the practice of continuous delivery serves to frequently deploy iterative software bug fixes and enhancements, such that users enjoy an ever-improving product. Automated processes, such as tests, assist in rapidly validating quality with each change. middleman-demo is a relatively simple codebase, though much of its build and release workflow can still be automated via continuous delivery. Let’s write some automated tests for middleman-demo using RSpec and Capybara. These tests can assert that the site continues to work as expected with each change. Add the gems to the middleman-demo Gemfile:  gem 'rspec'gem 'capybara' Install the gems: $ bundle install Create a spec directory to house tests: $ mkdir spec As is the convention in RSpec, create a spec/spec_helper.rb file to house the RSpec configuration: $ touch spec/spec_helper.rb Add the following configuration to spec/spec_helper.rb to run middleman-demo during test execution: require "middleman" require "middleman-blog" require 'rspec' require 'capybara/rspec' Capybara.app = Middleman::Application.server.inst do set :root, File.expand_path(File.join(File.dirname(__FILE__), '..')) set :environment, :development end Create a spec/features directory to house the middleman-demo RSpec test files: $ mkdir spec/features Create an RSpec spec file for the homepage: $ touch spec/features/index_spec.rb Let’s create a basic test confirming that the Middleman Demo heading is present on the homepage. Add the following to spec/features/index_spec.rb: require "spec_helper" describe 'index', type: :feature do before do visit '/' end it 'displays the correct heading' do expect(page).to have_selector('h1', text: 'Middleman Demo') end end Run the test and confirm that it passes: $ rspec You should see output like the following: Finished in 0.03857 seconds (files took 6 seconds to load) 1 example, 0 failures Next, add a test asserting that the first blog post is listed on the homepage; confirm it passes by running the rspec command: it 'displays the "New Blog" blog post' do expect(page).to have_selector('ul li a[href="/blog/2014/08/20/new-blog/"]', text: 'New Blog') end As an example, let’s add one more basic test, this time asserting that the New Blog text properly links to the corresponding blog post. Add the following to spec/features/index_spec.rb and confirm that the test passes: it 'properly links to the "New Blog" blog post' do click_link 'New Blog' expect(page).to have_selector('h2', text: 'New Blog') end middleman-demo can be further tested in this fashion. The extent to which the specs test every element of the site’s functionality is up to you. At what point can it be confidently asserted that the site looks good, works as expected, and can be publicly deployed to users? Push to GitHub Next, push your middleman-demo code to GitHub. If you forked my original github.com/mdb/middleman-demo repository, skip this section. 1. Create a GitHub repositoryIf you don’t already have a GitHub account, create one. Create a repository through GitHub’s web UI called middleman-demo. 2. What should you do if your version of middleman-demo is not a git repository?If your middleman-demo is already a git repository, skip to step 3. If you started from scratch and your code isn’t already in a git repository, let’s initialize one now. I’m assuming you have git installed and have some basic familiarity with it. Make a middleman-demo git repository: $ git init && git add . && git commit -m 'initial commit' Declare your git origin, where <your_git_url_from_step_1> is your GitHub middleman-demo repository URL: $ git remote add origin <your_git_url_from_step_1> Push to your GitHub repository: $ git push origin master You’re done; skip step 3 and move on to Integrate with Travis CI. 3. If you cloned my mdb/middleman-demo repository…If you cloned my middleman-demo git repository, you’ll need to add your newly created middleman-demo GitHub repository as an additional remote: $ git remote add my_origin <your_git_url_from_step_1> If you are working in a branch, merge all your changes to master. Then push to your GitHub repository: $ git push -u my_origin master Integrate with Travis CI Travis CI is a distributed continuous integration service that integrates with GitHub. It’s free for open source projects. Let’s configure Travis CI to run the middleman-demo tests when we push to the GitHub repository. Log in to Travis CI First, sign in to Travis CI using your GitHub credentials. Visit your profile. Find your middleman-demo repository in the “Repositories” list. Activate Travis CI for middleman-demo; click the toggle button “ON.” Create a .travis.ymlfile Travis CI looks for a .travis.yml YAML file in the root of a repository. YAML is a simple, human-readable markup language; it’s a popular option in authoring configuration files. The .travis.yml file informs Travis how to execute the project’s build. Create a .travis.yml file in the root of middleman-demo: $ touch .travis.yml Configure Travis CI to use Ruby 2.1 when building middleman-demo. Add the following YAML to the .travis.yml file: language: rubyrvm: 2.1 Next, declare how Travis CI can install the necessary gem dependencies to build middleman-demo; add the following: install: bundle install Let’s also add before_script, which runs the middleman-demo tests to ensure all tests pass in advance of a build: before_script: bundle exec rspec Finally, add a script that instructs Travis CI how to build middleman-demo: script: bundle exec middleman build At this point, the .travis.yml file should look like the following: language: ruby rvm: 2.1 install: bundle install before_script: bundle exec rspec script: bundle exec middleman build Commit the .travis.yml file: $ git add .travis.yml && git commit -m "added basic .travis.yml file" Now, after pushing to GitHub, Travis CI will attempt to install middleman-demo dependencies using Ruby 2.1, run its tests, and build the site. Travis CI’s command build output can be seen here: https://travis-ci.org/<your_github_username>/middleman-demo Add a build status badge Assuming the build passes, you should see a green build passing badge near the top right corner of the Travis CI UI on your Travis CI middleman-demo page. Let’s add this badge to the README.md file in middleman-demo, such that a build status badge reflecting the status of the most recent Travis CI build displays on the GitHub repository’s README. If one does not already exist, create a README.md file: $ touch README.md Add the following markdown, which renders the Travis CI build status badge: [![Build Status](https://travis-ci.org/<your_github_username>/middleman-demo.svg?branch=master)](https://travis-ci.org/<your_github_username>/middleman-demo) Configure continuous deployments Through continuous deployments, code is shipped to users as soon as a quality-validated change is committed. Travis CI can be configured to deploy a middleman-demo build with each successful build. Let’s configure Travis CI to continuously deploy middleman-demo to the S3 bucket created in part 2 of this tutorial series. First, install the travis command-line tools: $ gem install travis Use the travis command-line tools to set S3 deployments. Enter the following; you’ll be prompted for your S3 details (see the example below if you’re unsure how to answer): $ travis setup s3 An example response is: Access key ID: <your_aws_access_key_id> Secret access key: <your_aws_secret_access_key_id> Bucket: <your_aws_bucket> Local project directory to upload (Optional): build S3 upload directory (Optional): S3 ACL Settings (private, public_read, public_read_write, authenticated_read, bucket_owner_read, bucket_owner_full_control): |private| public_read Encrypt secret access key? |yes| yes Push only from <your_github_username>/middleman-demo? |yes| yes This automatically edits the .travis.yml file to include the following deploy information: deploy: provider: s3 access_key_id: <your_aws_access_key_id> secret_access_key: secure: <your_encrypted_aws_secret_access_key_id> bucket: <your_s3_bucket> local-dir: build acl: !ruby/string:HighLine::String public_read on: repo: <your_github_username>/middleman-demo Add one additional option, informing Travis to preserve the build directory for use during the deploy process: skip_cleanup: true The final .travis.yml file should look like the following: language: ruby rvm: 2.1 install: bundle install before_script: bundle exec rspec script: bundle exec middleman build deploy: provider: s3 access_key_id: <your_aws_access_key> secret_access_key: secure: <your_encrypted_aws_secret_access_key> bucket: <your_aws_bucket> local-dir: build skip_cleanup: true acl: !ruby/string:HighLine::String public_read on: repo: <your_github_username>/middleman-demo Confirm that your continuous integration works Commit your changes: $ git add .travis.yml && git commit -m "added travis deploy configuration" Push to GitHub and watch the build output on Travis CI: https://travis-ci.org/<your_github_username>/middleman-demo If all works as expected, Travis CI will run the middleman-demo tests, build the site, and deploy to the proper S3 bucket. Recap Throughout this series, we’ve examined the benefits of static site generators and covered some basics regarding Middleman blogging. We’ve learned how to use the wp2middleman gem to migrate content from a WordPress blog, and we’ve learned how to deploy Middleman to Amazon’s cloud-based Simple Storage Service (S3). We’ve configured Travis CI to run automated tests, produce a build, and automate deployments. Beyond what’s been covered within this series, there’s an extensive Middleman ecosystem worth exploring, as well as numerous additional features. Middleman’s custom extensions seek to extend basic Middleman functionality through third-party gems. Read more about Middleman at Middlemanapp.com. About this author Mike Ball is a Philadelphia-based software developer specializing in Ruby on Rails and JavaScript. He works for Comcast Interactive Media where he helps build web-based TV and video consumption applications. 
Read more
  • 0
  • 0
  • 5275

article-image-different-strategies-make-responsive-websites
Packt
04 Oct 2013
9 min read
Save for later

Different strategies to make responsive websites

Packt
04 Oct 2013
9 min read
(For more resources related to this topic, see here.) The Goldilocks approach In 2011, and in response to the dilemma of building several iterations of the same website by targeting every single device, the web-design agency, Design by Front, came out with an official set of guidelines many designers were already adhering to. In essence, the Goldilocks approach states that rather than rearranging our layouts for every single device, we shouldn't be afraid of margins on the left and right of our designs. There's a blurb about sizing around the width of our body text (which they state should be around 66 characters per line, or 33 em's wide), but the important part is that they completely destroyed the train of thought that every single device needed to be explicitly targeted—effectively saving designers countless hours of time. This approach became so prevalent that most CSS frameworks, including Twitter Bootstrap 2, adopted it without realizing that it had a name. So how does this work exactly? You can see a demo at http://goldilocksapproach.com/demo; but for all you bathroom readers out there, you basically wrap your entire site in an element (or just target the body selector if it doesn't break anything else) and set the width of that element to something smaller than the width of the screen while applying a margin: auto. The highlighted element is the body tag. You can see the standard and huge margins on each side of it on larger desktop monitors. As you contract the viewport to a generic tablet-portrait size, you can see the width of the body is decreased dramatically, creating margins on each side again. They also do a little bit of rearranging by dropping the sidebar below the headline. As you contract the viewport more to a phone size, you'll notice that the body of the page occupies the full width of the page now, with just some small margins on each side to keep text from butting up against the viewport edges. Okay, so what are the advantages and disadvantages? Well, one advantage is it's incredibly easy to do. You literally create a wrapping element and every time the width of the viewport touches the edges of that element, you make that element smaller and tweak a few things. But, the huge advantage is that you aren't targeting every single device, so you only have to write a small amount of code to make your site responsive. The downside is that you're wasting a lot of screen real-estate with all those margins. For the sake of practice, create a new folder called Goldilocks. Inside that folder create a goldilocks.html and goldilocks.css file. Put the following code in your goldilocks.html file: <!DOCTYPE html> <html> <head> <title>The Goldilocks Approach</title> <link rel="stylesheet" href="goldilocks.css"> </head> <body> <div id="wrap"> <header> <h1>The Goldilocks Approach</h1> </header> <section> <aside>Sidebar</aside> <article> <header> <h2>Hello World</h2> <p> Lorem ipsum... </p> </header> </article> </section> </div> </body> </html> We're creating an incredibly simple page with a header, sidebar, and content area to demonstrate how the Goldilocks approach works. In your goldilocks.css file, put the following code: * { margin: 0; padding: 0; background: rgba(0,0,0,.05); font: 13px/21px Arial, sans-serif; } h1, h2 { line-height: 1.2; } h1 { font-size: 30px; } h2 { font-size: 20px; } #wrap { width: 900px; margin: auto; } section { overflow: hidden; } aside { float: left; margin-right: 20px; width: 280px; } article { float: left; width: 600px; } @media (max-width: 900px) { #wrap { width: 500px; } aside { width: 180px; } article { width: 300px; } } @media (max-width: 500px) { #wrap { width: 96%; margin: 0 2%; } aside, article { width: 100%; margin-top: 10px; } } Did you notice how the width of the #wrap element becomes the max-width of the media query? After you save and refresh your page, you'll be able to expand/contract to your heart's content and enjoy your responsive website built with the Goldilocks approach. Look at you! You just made a site that will serve any device with only a few media queries. The fewer media queries you can get away with, the better! Here's what it should look like: The preceding screenshot shows your Goldilocks page at desktop width. At tablet size, it looks like the following: On a mobile site, you should see something like the following screenshot: The Goldilocks approach is great for websites that are graphic heavy as you can convert just three mockups to layouts and have completely custom, graphic-rich websites that work on almost any device. It's nice if you are of the type who enjoys spending a lot of time in Photoshop and don't mind putting in the extra work of recreating a lot of code for a more textured website with a lot of attention to detail. The Fluid approach Loss of real estate and a substantial amount of extra work for slightly prettier (and heavier) websites is a problem that most of us don't want to deal with. We still want beautiful sites, and luckily with pure CSS, we can replicate a huge amount of elements in flexible code. A common, real-world example of replacing images with CSS is to use CSS to create buttons. Where Goldilocks looks at your viewport as a container for smaller, usually pixel-based containers, the Fluid approach looks at your viewport as a 100 percent large container. If every element inside the viewport adds up to around 100 percent, you've effectively used the real estate you were given. Duplicate your goldilocks.html file, then rename it to fluid.html. Replace the mentions of "Goldilocks" with "Fluid": <!DOCTYPE html> <html> <head> <title>The Fluid Approach</title> <link rel="stylesheet" href="fluid.css"> </head> <body> <div id="wrap"> <header> <h1>The Fluid Approach</h1> </header> <section> <aside>Sidebar</aside> <article> <header> <h2>Hello World</h2> </header> <p> Lorem ipsum... </p> </article> </section> </div> </body> </html> We're just duplicating our very simple header, sidebar, and article layout. Create a fluid.css file and put the following code in it: * { margin: 0; padding: 0; background: rgba(0,0,0,.05); font: 13px/21px Arial, sans-serif; } aside { float: left; width: 24%; margin-right: 1%; } article { float: left; width: 74%; margin-left: 1%; } Wow! That's a lot less code already. Save and refresh your browser, then expand/contract your viewport. Did you notice how we're using all available space? Did you notice how we didn't even have to use media queries and it's already responsive? Percentages are pretty cool. Your first fluid, responsive, web design We have a few problems though: On large monitors, when that layout is full of text, every paragraph will fit on one line. That's horrible for readability. Text and other elements butt up against the edges of the design. The sidebar and article, although responsive, don't look great on smaller devices. They're too small. Luckily, these are all pretty easy fixes. First, let's make sure the layout of our content doesn't stretch to 100 percent of the width of the viewport when we're looking at it in larger resolutions. To do this, we use a CSS property called max-width. Append the following code to your fluid.css file: #wrap { max-width: 980px; margin: auto; } What do you think max-width does? Save and refresh, expand and contract. You'll notice that wrapping div is now centered in the screen at 980 px width, but what happens when you go below 980 px? It simply converts to 100 percent width. This isn't the only way you'll use max-width, but we'll learn a bit more in the Gotchas and best practices section. Our second problem was that the elements were butting up against the edges of the screen. This is an easy enough fix. You can either wrap everything in another element with specified margins on the left and right, or simply add some padding to our #wrap element shown as follows: #wrap { max-width: 980px; margin: auto; padding: 0 20px; } Now our text and other elements are touching the edges of the viewport. Finally, we need to rearrange the layout for smaller devices, so our sidebar and article aren't so tiny. To do this, we'll have to use a media query and simply unassign the properties we defined in our original CSS: @media (max-width: 600px) { aside, article { float: none; width: 100%; margin: 10px 0; } } We're removing the float because it's unnecessary, giving these elements a width of 100 percent, and removing the left and right margins while adding some margins on the top and bottom so that we can differentiate the elements. This act of moving elements on top of each other like this is known as stacking. Simple enough, right? We were able to make a really nice, real-world, responsive, fluid layout in just 28 lines of CSS. On smaller devices, we stack content areas to help with readability/usability: It's up to you how you want to design your websites. If you're a huge fan of lush graphics and don't mind doing extra work or wasting real estate, then use Goldilocks. I used Goldilocks for years until I noticed a beautiful site with only one breakpoint (width-based media query), then I switched to Fluid and haven't looked back. It's entirely up to you. I'd suggest you make a few websites using Goldilocks, get a bit annoyed at the extra effort, then try out Fluid and see if it fits. In the next section we'll talk about a somewhat new debate about whether we should be designing for larger or smaller devices first. Summary In this article, we have taken a look at how to build a responsive website using the Goldilocks approach and the Fluid approach. Resources for Article : Further resources on this subject: Creating a Web Page for Displaying Data from SQL Server 2008 [Article] The architecture of JavaScriptMVC [Article] Setting up a single-width column system (Simple) [Article]
Read more
  • 0
  • 0
  • 5234
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-how-to-integrate-social-media-into-wordpress-website
Packt
29 Apr 2015
6 min read
Save for later

How to integrate social media with your WordPress website

Packt
29 Apr 2015
6 min read
In this article by Karol Krol, the author of the WordPress 4.x Complete, we will look at how we can integrate our website with social media. We will list some more ways in which you can make your site social media friendly, and also see why you'd want to do that in the first place. Let's start with the why. In this day and age, social media is one of the main drivers of traffic for many sites. Even if you just want to share your content with friends and family, or you have some serious business plans regarding your site, you need to have at least some level of social media integration. Even if you install just simple social media share buttons, you will effectively encourage your visitors to pass on your content to their followers, thus expanding your reach and making your content more popular. (For more resources related to this topic, see here.) Making your blog social media friendly There are a handful of ways to make your site social media friendly. The most common approaches are as follows: Social media share buttons, which allow your visitors to share your content with their friends and followers Social media APIs integration, which make your content look better on social media (design wise) Automatic content distribution to social media Social media metrics tracking Let's discuss these one by one. Setting up social media share buttons There are hundreds of social media plugins available out there that allow you to display a basic set of social media buttons on your site. The one I advise you to use is called Social Share Starter (http://bit.ly/sss-plugin). Its main advantage is that it's optimized to work on new and low-traffic sites, and doesn't show any negative social proof when displaying the buttons and their share numbers. Setting up social media APIs' integration The next step worth taking to make your content appear more attractive on social media is to integrate it with some social media APIs; particularly that of Twitter. What exactly their API is and how it works isn't very relevant for the WordPress discussion we're having here. So instead, let's just focus on what the outcome of integrating your site with this API is. Here's what a standard tweet mentioning a website usually looks like (please notice the overall design, not the text contents): Here's a different tweet, mentioning an article from a site that has Twitter's (Twitter Cards) API enabled: This looks much better. Luckily, having this level of Twitter integration is quite easy. All you need is a plugin called JM Twitter Cards (available at https://wordpress.org/plugins/jm-twitter-cards/). After installing and activating it, you will be guided through the process of setting everything up and approving your site with Twitter (mandatory step). Setting up automatic content distribution to social media The idea behind automatic social media distribution of your content is that you don't have to remember to do so manually whenever you publish a new post. Instead of copying and pasting the URL address of your new post by hand to each individual social media platform, you can have this done automatically. This can be done in many ways, but let's discuss the two most usable ones, the Jetpack and Revive Old Post plugins. The Jetpack plugin The Jetpack plugin is available at https://wordpress.org/plugins/jetpack/. One of Jetpack's modules is called Publicize. You can activate it by navigating to the Jetpack | Settings section of the wp-admin. After doing so, you will be able to go to Settings | Sharing and integrate your site with one of the six available social media platforms: After going through the process of authorizing the plugin with each service, your site will be fully capable of posting each of your new posts to social media automatically. The Revive Old Post plugin The Revive Old Post plugin is available at https://revive.social/plugins/revive-old-post. While the Jetpack plugin takes the newest posts on your site and distributes them to your various social media accounts, the Revive Old Post plugin does the same with your archived posts, ultimately giving them a new life. Hence the name Revive Old Post. After downloading and activating this plugin, go to its section in the wp-admin Revive Old Post. Then, switch to the Accounts tab. There, you can enable the plugin to work with your social media accounts by clicking on the authorization buttons: Then, go to the General settings tab and handle the time intervals and other details of how you want the plugin to work with your social media accounts. When you're done, just click on the SAVE button. At this point, the plugin will start operating automatically and distribute your random archived posts to your social media accounts. Note that it's probably a good idea not to share things too often if you don't want to anger your followers and make them unfollow you. For that reason, I wouldn't advise posting more than once a day. Setting up social media metrics tracking The final element in our social media integration puzzle is setting up some kind of tracking mechanism that would tell us how popular our content is on social media (in terms of shares). Granted, you can do this manually by going to each of your posts and checking their share numbers individually (provided you have the Social Share Starter plugin installed). However, there's a quicker method, and it involves another plugin. This one is called Social Metrics Tracker and you can get it at https://wordpress.org/plugins/social-metrics-tracker/. In short, this plugin collects social share data from a number of platforms and then displays them to you in a single readable dashboard view. After you install and activate the plugin, you'll need to give it a couple of minutes for it to crawl through your social media accounts and get the data. Soon after that, you will be able to visit the plugin's dashboard by going to the Social Metrics section in the wp-admin: For some webhosts and setups, this plugin might end up consuming too much of the server's resources. If this happens, consider activating it only occasionally to check your results and then deactivate it again. Doing this even once a week will still give you a great overview of how well your content is performing on social media. This closes our short guide on how to integrate your WordPress site with social media. I'll admit that we're just scratching the surface here and that there's a lot more that can be done. There are new social media plugins being released literally every week. That being said, the methods described here are more than enough to make your WordPress site social media friendly and enable you to share your content effectively with your friends, family, and audience. Summary Here, we talked about social media integration, tools, and plugins that can make your life a lot easier as an online content publisher. Resources for Article: Further resources on this subject: FAQs on WordPress 3 [article] Creating Blog Content in WordPress [article] Customizing WordPress Settings for SEO [article]
Read more
  • 0
  • 0
  • 5233

article-image-creating-photo-gallery-expressionengine-2
Packt
11 Oct 2010
12 min read
Save for later

Creating a Photo Gallery with ExpressionEngine 2

Packt
11 Oct 2010
12 min read
  Building Websites with ExpressionEngine 2 A step-by-step guide to ExpressionEngine: the web-publishing system used by top designers and web professionals everywhere Learn all the key concepts and terminology of ExpressionEngine: channels, templates, snippets, and more Use RSS to make your content available in news readers including Google Reader, Outlook, and Thunderbird Manage your ExpressionEngine website, including backups, restores, and version updates Written in an easy-to-follow step-by-step style, with plenty of examples and exercises         Read more about this book      (For more resources on ExpressionEngine, see here.) Designing your photo gallery There are many different ways you can approach creating a photo gallery in ExpressionEngine. At the most basic level, you have a choice between each channel entry containing only one photo (and a description) or each channel entry containing a set of photos. If you allow only one photo per entry, you can use categories to organize the photos into galleries (and you can even include the same photo in more than one gallery). If you allow multiple photos per channel entry, each entry represents a photo gallery by itself.   One way to accommodate multiple photos per entry is to create as many custom fields as the photos you think you will have in a gallery. For example, if you know each gallery will have a maximum of 20 photos, then you could create 20 custom fields for the photos and 20 custom fields for the descriptions. This solution works, but is not the most flexible (that is, to add 21 photos to a gallery, you would have to modify your custom fields and your templates). An alternative approach to accommodate multiple photos per entry without creating an abundance of custom fields is to use a third party add-on such as Matrix by Pixel & Tonic (http://pixelandtonic.com/matrix). This add-on allows for tabular data in channel entries—you define the column headings (such as the photo and the description) and then add a row in the table for each photo. In each channel entry, you can create as many rows as you need. For example, you can create one entry with 12 photos and another entry with 25 photos. Rather than creating lots of custom fields, or using a third party add-on, this article will show you a simple and elegant way to create a photo gallery using the one photo per entry design and then will use categories to organize the photos into galleries. Before you create your photo gallery channel, you first need to define where your photos will be stored. File manager The file manager is where you can upload new photos or crop, resize, rotate, or delete the images you have already uploaded, all from within the ExpressionEngine control panel. For this photo gallery, you will create a new upload destination—this is the directory on your server where ExpressionEngine will store your photos. The first step in creating a new upload destination is to create the new directory on your server. Create a new directory called photos in /images. If you are following along on an actual web server, ensure that the new directory has 777 permissions (usually right-clicking on the directory in your FTP client will allow you to set permissions).If, instead of creating a new sub-directory inside the "/images" directory, you prefer to create a new top-level directory and you are using the ".htaccess" exclude method to remove the "index.php" from ExpressionEngine URLs, then be sure to add the new directory to your ".htaccess" file. Next, you need to tell ExpressionEngine where this directory is. Inside the control panel, select Content and then File Manager. On the left-hand side of the screen, you will see the directory or directories where you can currently upload files to (if any), along with the files currently in each directory. In the toolbar on the right-hand side, underneath File Tools, select Create New Upload Destination. Enter a descriptive name of Photo Gallery. The Server Path and URL may be pre-filled, however, you should make sure it points to the actual directory you just created (/images/photos). If you are following along in a localhost environment, the URL would be http://localhost/images/photos. Leave Allowed File Types as Images only. All the fields that begin with maximum can be left blank. These fields allow you to restrict the size, height, and width of photos. If you do enter values in here, and then later try to upload a file that exceeds these limits, you will see an error message such as The file you are attempting to upload is larger than the permitted size. Set the Image Properties, Image Pre Formatting, and Image Post Formatting to be blank. These fields allow you to enter code that appears inside, before, and after the img tag. However, you will format your img tag as needed inside your template. The File Properties, File Pre, and Post Formatting can be ignored for now as they only apply to non-image files that you upload (and you have specified that you are only allowing images in your photo gallery). If desired, you can allow certain member groups to upload files. The member groups you see listed (if any) will depend on the member groups you have. Set all the member groups to Yes except Members, which should be set as No. Click Submit and your new upload destination will be ready to go. Go back to the file manager and you can see the new photo gallery upload destination with no files. Creating your photo gallery channel Now that you have created a place to store your photos, you can create your photo gallery channel. You will follow the same basic steps—creating custom fields and categories, creating your channel, publishing some entries, and then building your templates. Creating your custom fields Since you are going to have one photo per channel entry, you have a lot of flexibility to create as many custom fields for each photo as you see fit—for example, you could have fields to capture the location of the photograph, the subject of the photo, the type of camera that was used, the name of the photographer, and so forth. However, to keep things simple, you will only create two custom fields right now—one for the photo itself and one for the description. From the main menu of the control panel, select Admin, Channel Administration, and then Custom Fields. Select Create a New Channel Field Group and call the new group photos. Click Submit. Next to the new group, select Add/Edit Custom Fields and then select Create a New Custom Field. The field type will be File. The field label will be Photo and the field name will be photos_photo (the first part representing the field group name). In the field instructions, indicate that photos in the photo gallery should be no more than 600x800 pixels (so that they fit on a typical computer screen without scrolling).You could also prevent photos that are bigger than 600x800 pixels from being uploaded by specifying the maximum width and height in the File Upload Preferences for the photo gallery upload destination. You have not done this here because it would prevent you from being able to upload a larger photo and then re-sizing it using file manager. The field should be required, but not searchable, and should be shown by default. The field display order should be 1 and the file type should be Image. Click Submit. Click Create a New Custom Field again. This time, the field type should be Textarea, the field label Caption, and the field name photos_caption. The field instructions can be left blank. Answer Yes to it being a required field, being searchable and being shown by default. The Field Display Order should be 2. The number of rows can be left as 6 and the default text formatting should be set to Auto <br /> (this will prevent unwanted whitespace in your captions due to extra paragraph tags being added, but will also allow multi-line captions). Say No to allowing an override on the Publish page. The text direction can also be left as left-to-right. Finally, say Yes to Formatting Buttons, Spellcheck, and Write mode. Say No to Smileys, Glossary, and the File Chooser. Click Submit to create the new field. Now that you have your custom fields, you can define your categories. Creating your categories As discussed at the beginning of this article, you are going to use categories to distinguish between photo galleries. To start with, you are going to create two photo galleries—one for vacation photos and one for local photos. You can always come back and add more galleries later. Still in the control panel, select Admin, Channel Administration, and then Categories. Select Create a New Category Group and name it Photo Categories. Select Allow All HTML in the category field formatting and check the boxes to allow other member groups to edit (or delete) categories as appropriate. (If you see a message saying that there are no member groups allowed to edit/delete categories, this is fine too). Click Submit. Back on the Category Management screen, select Add/Edit Categories for the Photo Categories category group. Click Create a New Category. The first category will be called Local Photos. The Category URL will default to local_photos. Type in a category description (you will later display this on your website), leave the Category Image URL blank, leave the Category Parent as None, and click Submit. Select Create a New Category again. This time call the new category Vacation Photos, with a URL of vacation_photos. Type in a category description such as A selection of vacation photos taken by Ed & Eg. Leave the category image URL blank and the category parent as None. Click Submit. Now that you have your category group and custom field group defined, you can go ahead and create your channel. Creating your channel The actual creating of your channel is very straightforward. Select Admin | Channel Administration | Channels. Select Create a New Channel. Call the new channel Photos with a short name of photos. Do not duplicate an existing channel's preferences. Select Yes to Edit Group Preferences and select Photo Categories for the category group, Statuses for the status group, and photos for the field group. Select No to creating new templates and then click Submit. Your channel is created! Now you can start creating some content and displaying the photos on your website. Uploading your first photos There are three ways to upload photos to your website. Your first option is to go to File Manager (under the Content menu) and select File Upload on the right-hand toolbar. Alternatively, you can go to publish an entry in the Photos channel, click on Add File, and upload a file. Both of these options are convenient since they use the built-in ExpressionEngine file manager to upload your file—you never have to leave the control panel. However, you can only upload one photo at a time and you may run into issues if you try and upload very large photos (greater than 2 MB). The third option for uploading photos is to do so directly, using FTP, just as you would upload any files to your website. Since this requires another tool, it is less convenient than uploading a single photo from within ExpressionEngine, but if you are uploading lots of photos, then using FTP is a lot faster to do. This is the method we will use here. The built-in file manager also allows you to crop, resize, and rotate images (although you can take advantage of these tools even if you do not use file manager to upload the files).   Download the example photos (local1.jpg through local8.jpg and vacation1.jpg through vacation8.jpg) from either the Packtpub support page at http://www.packtpub.com/support or from http://www.leonardmurphy.com/book2/chapter8. (Or you can substitute your own photos). Copy or FTP the photos into the /images/photos directory that you created earlier in the article. Back in the ExpressionEngine control panel, select Content | Publish and then select the Photos channel. Type in a title of Fireworks and a caption Fireworks exploding with a bang. Then select Add File. The first screen to appear in the Upload File screen. Since you have already uploaded the files, you can simply select the photo gallery option in the left-hand menu.If no photos appear under the photo gallery, or the files appear but no thumbnails appear, try logging out of the control panel and logging back in. (This helps to refresh ExpressionEngine so it recognizes the new files—the first time you access the files after uploading via FTP, ExpressionEngine has to create the thumbnails). Select local1.jpg. On the Categories tab, select Local Photos. Then click Submit. Now, repeat the same steps to create entries for the rest of the photos, using appropriate captions that describe the photos. Be sure to select a category for each photo. There are 16 example photos (eight local and eight vacation photos). Having several example photos in each category will demonstrate how the photo gallery works better.
Read more
  • 0
  • 0
  • 5222

Packt
12 Aug 2010
4 min read
Save for later

Easy guide to understand WCF in Visual Studio 2008 SP1 and Visual Studio 2010 Express

Packt
12 Aug 2010
4 min read
(For more resources on Microsoft, see here.) Creating your first WCF application in Visual Studio 2008 You start creating a WCF project by creating a new project from File | New | Project.... This opens the New Project window. You can see that there are four different templates available. We will be using the WCF Service Library template. Change the default name and provide a name for the project (herein JayWcf01) and click OK. The project JayWcf01 gets created with the folder structure shown in the next image: If you were to expand References node in the above you would notice that System.ServiceModel is already referenced. If it is not, for some reason, you can bring it in by using the Add Reference... window which is displayed when you right click the project in the Solution Explorer. IService1.vb is a service interface file as shown in the next listing. This defines the service contract and the operations expected of the service. If you change the interface name "IService1" here, you must also update the reference to "IService1" in App.config. <ServiceContract()> _Public Interface IService1 <OperationContract()> _ Function GetData(ByVal value As Integer) As String <OperationContract()> _ Function GetDataUsingDataContract(ByVal composite As CompositeType) As CompositeType ' TODO: Add your service operations hereEnd Interface' Use a data contract as illustrated in the sample below to add composite types to service operations<DataContract()> _Public Class CompositeType Private boolValueField As Boolean Private stringValueField As String <DataMember()> _ Public Property BoolValue() As Boolean Get Return Me.boolValueField End Get Set(ByVal value As Boolean) Me.boolValueField = value End Set End Property <DataMember()> _ Public Property StringValue() As String Get Return Me.stringValueField End Get Set(ByVal value As String) Me.stringValueField = value End Set End PropertyEnd Class The Service Contract is a contract that will be agreed to between the Client and the Server. Both the Client and the Server should be working with the same service contract. The one shown above is in the server. Inside the service, data is handled as simple (e.g. GetData) or complex types (e.g. GetDataUsingDataContract). However outside the Service these are handled as XML Schema Definitions. WCF Data contracts provides a mapping between the data defined in the code and the XML Schema defined by W3C organization, the standards organization. The service performed when the terms of the contract are properly adhered to is in the listing of Service1.vb file shown here. ' NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in App.config.Public Class Service1 Implements IService1 Public Function GetData(ByVal value As Integer) As _ String Implements IService1.GetData Return String.Format("You entered: {0}", value) End Function Public Function GetDataUsingDataContract(ByVal composite As CompositeType) _ As CompositeType Implements IService1.GetDataUsingDataContract If composite.BoolValue Then composite.StringValue = (composite.StringValue & "Suffix") End If Return composite End FunctionEnd Class Service1 is defining two methods of the service by way of Functions. The GetData accepts a number and returns a string. For example, if the Client enters a value 50, the Server response will be "You entered: 50". The function GetDataUsingDataContract returns a Boolean and a String with 'Suffix' appended for an input which consists of a Boolean and a string. The JayWcf01 is a completed program with a default example contract IService1 and a defined service, Service1. This program is complete in itself. It is a good practice to provide your own names for the objects. Notwithstanding the default names are accepted in this demo. In what follows we test this program as is and then slightly modify the contract and test it again. The testing in the next section will invoke an in-built client and then later on we will publish it to the localhost which is an IIS 7 web server. How to test this program The program has a valid pair of contract and service and we should be able to test this service. The Windows Communication Foundation allows Visual Studio 2008 (also Visual Studio 2010 Express) to launch a host to test the service with a client. Build the program and after it succeeds hit F5. The WcfSvcHost is spawned which stays in the taskbar as shown. You can click WcfSvcHost to display the WCF Service Host window popping-up as shown. The host gets started as shown here. The service is hosted on the developmental server. This is immediately followed by the WCF Test Client user interface popping-up as shown. In this harness you can test the service.
Read more
  • 0
  • 0
  • 5215

article-image-creating-dynamic-ui-android-fragments
Packt
26 Sep 2013
2 min read
Save for later

Creating Dynamic UI with Android Fragments

Packt
26 Sep 2013
2 min read
(For more resources related to this topic, see here.) Many applications involve several screens of data that a user might want to browse or flip through to view each screen. As an example, think of an application where we list a catalogue of books with each book in the catalogue appearing on a single screen. A book's screen contains an image, title, and description like the following screenshot: To view each book's information, the user needs to move to each screen. We could put a next button and a previous button on the screen, but a more natural action is for the user to use their thumb or finger to swipe the screen from one edge of the display to the other and have the screen with the next book's information slide into place as represented in the following screenshot: This creates a very natural navigation experience, and honestly, is a more fun way to navigate through an application than using buttons. Summary Fragments are the foundation of modern Android app development, allowing us to display multiple application screens within a single activity. Thanks to the flexibility provided by fragments, we can now incorporate rich navigation into our apps with relative ease. Using these rich navigation capabilities, we're able to create a more dynamic user interface experience that make our apps more compelling and that users find more fun to work with. Resources for Article : Further resources on this subject: So, what is Spring for Android? [Article] Android Native Application API [Article] Animating Properties and Tweening Pages in Android 3-0 [Article]
Read more
  • 0
  • 0
  • 5202
article-image-wordpress-customizing-content-display
Packt
14 Dec 2011
8 min read
Save for later

WordPress: Customizing Content Display

Packt
14 Dec 2011
8 min read
(For more resources on WordPress, see here.) At its most basic, a simple implementation of the loop could work like this: <?php if (have_posts()) : while (have_posts()) : the_post(); ?><?php the_title(); ?><?php the_content(); ?><?php endwhile; else: ?><p>Sorry, no posts matched your criteria.'</p><?php endif; ?> In the real world, however, the WordPress loop is rarely that simple. This is one of those concepts best explained by referring to a real world example, so open up the index.php file of your system's TwentyEleven theme. Look for the following lines of code: <?php if ( have_posts() ) : ?><?php twentyeleven_content_nav( 'nav-above' ); ?><?php /* Start the Loop */ ?><?php while ( have_posts() ) : the_post(); ?><?php get_template_part( 'content', get_post_format()); ?><?php endwhile; ?><?php twentyeleven_content_nav( 'nav-below' ); ?><?php else : ?><article id="post-0" class="post no-results not-found"><header class="entry-header"><h1 class="entry-title"><?php _e( 'Nothing Found','twentyeleven' ); ?></h1></header><!-- .entry-header --><div class="entry-content">3<p><?php _e( 'Apologies, but no results were foundfor the requested archive. Perhaps searching will helpfind a related post.', 'twentyeleven' ); ?></p><?php get_search_form(); ?></div><!-- .entry-content --></article><!-- #post-0 --><?php endif; ?> Most of the extra stuff seen in the loop from TwentyEleven is there to add in additional page elements, including content navigation; there's also some code to control what happens if there are no posts to display. The nature of the WordPress loops means that theme authors can add in what they want to display and thereby customize and control the output of their site. As you would expect, the WordPress Codex includes an extensive discussion of the WordPress loop. Visit http://codex.wordpress.org/The_Loop. Accessing posts within the WordPress loop In this recipe, we look at how to create a custom template that includes your own implementation of the WordPress loop. Getting ready All you need to execute this recipe is your favorite code editor and access to the WordPress files on your server. You will also need a theme template file, which we will use to hold our modified WordPress loop. How to do it Let's assume you have created a custom template. Inside of that template you will want to include the WordPress loop. Follow these steps to add the loop, along with a little customization: Access the active theme files on your WordPress installation. Find a template file and open it for editing. If you're not sure which one to use, try the index.php file. Add to the file the following line of code, which will start the loop: <?php if ( have_posts() ) : while ( have_posts() ) : the_post();?> Next, let's display the post title, wrapped in an h2 tag: <h2><?php the_title() ?></h2> Let's also add a link to all posts by this author. Add this code immediately below the previous line: <?php the_author_posts_link() ?> For the post content, let's wrap it in a div for easy styling: <div class="thecontent"><?php the_content(); ?></div> Next, let's terminate the loop and add some code to display a message if there were no posts to display: <?php endwhile; else: ?><p>Oops! There are no posts to display.</p> Finally, let's put a complete stop to the loop by ending the if statement that began the code in step number 3, above: <?php endif; ?> Save the file. That's all there is to it. Your code should look like this: ?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?><h2><?php the_title() ?></h2><?php the_author_posts_link() ?><div class="thecontent"><?php the_content(); ?></div><?php endwhile; else: ?><p>Oops! There are no posts to display.</p><?php endif; ?> How it works... This basic piece of code first checks if there are posts in your site. If the answer is yes, the loop will repeat until every post title and their contents are displayed on the page. The post title is displayed using the_title(). The author's name and link are added with the_ author_posts_link() function. The content is displayed with the_content() function and styled by the div named thecontent. Finally, if there are no posts to display, the code will display the message Oops! There are no posts to display. There's more... In the preceding code you saw the use of two template tags: the_author_posts_link and the_content. These are just two examples of the many template tags available in WordPress. The tags make your life easier by reducing an entire function to just a short phrase. You can find a full list of the template tags at: http://codex.wordpress.org/ Template_Tags. The template tags can be broken down into a number of categories: General tags: The tags in this category cover general page elements common to most templates Author tags: Tags related to author information Bookmark tags: The tag to list bookmarks Category tags: Category, tag, and item description-related Comment tags: Tags covering the comment elements Link tags: Tags for links and permalinks Post tags: Tags for posts, excerpts, titles, and attachments Post Thumbnail tags: Tags that relate to the post thumbnails Navigation Menu tags: Tags for the nav menu and menu tree Retrieving posts from a specific category There are times when you might wish to display only those posts that belong to a specific category, for example, perhaps you want to show only the featured posts. With a small modification to the WordPress loop, it's easy to grab only those posts you want to display. In this recipe we introduce query_posts(),which can be used to control which posts are displayed by the loop. Getting ready To execute this recipe, you will need a code editor and access to the WordPress files on your server. You will also need a theme template file, which we will use to hold our modified WordPress loop. To keep this recipe short and to the point, we use the loop we created in the preceding recipe. How to do it... Let's create a situation where the loop shows only those posts assigned to the Featured category. To do this, you will need to work through two different processes. First, you need to find the category ID number of the Featured category. To do this, follow these steps: Log in to the Dashboard of your WordPress site. Click on the Posts menu. Click on the Categories option. Click on the category named Featured. Look at the address bar of your browser and you will notice that part of the string looks something like this:&tag_ID=9. On the site where we are working, the Featured category has the ID of 9. Category IDs vary from site to site. The ID used in this recipe may not be the same as the ID for your site! Next, we need to add a query to our loop that will extract only those posts that belong to the Featured category, that is, to those posts that belong to the category with the ID of 9. Follow these steps: Open the file that contains the loop. We'll use the same file we created in the preceding recipe. Find the loop: <?php if ( have_posts() ) : while ( have_posts() ) :the_post(); ?><h2><?php the_title() ?></h2><?php the_author_posts_link() ?><div class="thecontent"><?php the_content(); ?></div><?php endwhile; else: ?><p>Oops! There are no posts to display.</p><?php endif; ?> Add the following line of code immediately above the loop: <?php query_posts($query_string.'&cat=9'); ?> Save the file. That's all there is to it. If you visit your site, you will now see that the page displays only the posts that belong to the category with the ID of 9. How it works... The query_posts() function modifies the default loop. When used with the cat parameter, it allows you to specify one or more categories that you want to use as filters for the posts. For example: query_posts(&query_string.'&cat=5');: Get posts from the category with ID 5 only query_posts(&query_string.'&cat=5,6,9');: Get posts from the category with IDs 5, 6, and 9 query_posts(&query_string.'&cat=-3');: Get posts from all categories, except those from the category with ID 3 For more information, visit the WordPRess Codex page on query posts: http://codex.wordpress.org/Function_Reference/query_posts
Read more
  • 0
  • 0
  • 5152

article-image-roles-and-permissions-moodle-administration-part2
Packt
23 Oct 2009
5 min read
Save for later

Roles and Permissions in Moodle Administration-part2

Packt
23 Oct 2009
5 min read
Capabilities and Permissions So far, we have given users existing roles in different Moodle contexts. In the following few pages, we want to have a look at the inside of a role that is called capabilities and permissions. Once we have understood them, we will be able to modify existing roles and create entirely new custom ones. Role Definitions Existing roles are accessed via Users | Permissions | Define Roles in the Site Administration block. The screen that will be shown is similar to the familiar roles assignment screen, but has a very different purpose: When you click on a role name, its composition is shown. Each role contains a unique Name, a unique Short name (used when uploading users), and an optional Description. The Legacy role type has been introduced for backward compatibility, to allow old legacy code that has not been fully ported to work with the new system comprising new roles and capabilities. It is expected that this facility will disappear in the future (this might be for some time since a lot of core code depends on it), and should be ignored in due course unless you are working with legacy code or third-party add-ons. In addition to these four fields, each role consists of a large number of capabilities. Currently, Moodle's roles system contains approximately 200 capabilities. A capability is a description of a particular Moodle feature (for example) to grade assignments or to edit a Wiki page. Each capability represents a permissible Moodle action: Permission is a capability and its value, taken together. So each row of the table in the screen shot represents permission. The left column is the capability name and the radio buttons specify the value. So now permission has a description, a unique name, a value, and up to four associated risks. The description, for example, Approve course creation provides a short explanation of the capability. On clicking, the description or the online Moodle documentation is opened in a separate browser. The name, for instance moodle /site: approvecourse, follows a strict naming convention that identifies the capability in the overall role system: level/type: function. The level states to which part of Moodle the capability belongs (such as moodle, mod, block, gradereport, or enroll). The type is the class of the capability and the function identifies the actual functionality. The permission of each capability has to have one of the four values: Permission Description Not Set By default, all permissions for a new role are set to this value. The value in the context where it will be assigned will be inherited from the parent-context. To determine what this value is, Moodle searches upward through each context, until it 'finds' an explicit value (Allow, Prevent or Prohibit) for this capability, i.e. the search terminates when an explicit permission is found. For example, if a role is assigned to a user in a Course context, and a capability has a value of 'Not set,' then the actual permission will be whatever the user has at the category level, or, failing to find an explicit permission at the category level, at the site level. If no explicit permission is found, then the value in the current context becomes Prevent. Allow To grant permission for a capability choose Allow. It applies in the context in which the role will be assigned and all contexts which are below it (children, grand-children, etc). For example, when assigned in the course context, students will be able to start new discussions in all forums in that course, unless some forum contains an override or a new assignment with a Prevent or Prohibit value for this capability. Prevent To remove permission for a capability choose Prevent. If it has been granted in a higher context (no matter at what level), it will be overridden. The value can be overridden again in a lower context. Prohibit This is the same as Prevent, but the value cannot be overridden again in a lower context. The value is rarely needed, but useful when an admin wants to prohibit a user from certain functionality throughout the entire site, in which case the capability is set to Prohibit and then assigned in the site context.   Principally, permissions at lower contexts override permissions at higher contexts. The exception is "Prohibit", which by definition cannot be overridden at lower levels. Resolving Permission Conflicts There is a possibility of conflict if two users are assigned the same role in the same context, where one role allows a capability and the other prevents it. In this case, Moodle will look upwards in higher contexts for a decider. This does not apply to Guest accounts, where "Prevent" will be used by default. For example, a user has two roles in the Course context, one that allows functionality and one that prevents it. In this case, Moodle checks the Category and the System contexts respectively, looking for another defined permission. If none is found, then the permission is set to "Prevent". Permission Risks Additionally, Moodle displays the risks associated with each capability, that is, the risks that each capability can potentially raise. They can be any combination of the following four risk types: Risk Icon Description Configuration Users can change site configuration and behavior. XSS Users can add files and texts that allow cross-site scripting (potentially malicious scripts which are embedded in web pages and executed on the user's computer). Privacy Users can gain access to private information of other users. Spam Users can send spam to site users or others. Risks are only displayed. It is not possible to change these settings, since they only act as warnings. When you click on a risk icon, the "Risks" documentation page is opened in a separate browser window. Moodle's default roles have been designed with the following capability risks in mind:
Read more
  • 0
  • 0
  • 5139

article-image-getting-started-couchdb-and-futon
Packt
27 Nov 2012
11 min read
Save for later

Getting Started with CouchDB and Futon

Packt
27 Nov 2012
11 min read
(For more resources related to this topic, see here.) What is CouchDB? The first sentence of CouchDB's definition (as defined by http://couchdb.apache.org/) is as follows: CouchDB is a document database server, accessible through the RESTful JSON API. Let's dissect this sentence to fully understand what it means. Let's start with the term database server. Database server CouchDB employs a document-oriented database management system that serves a flat collection of documents with no schema, grouping, or hierarchy. This is a concept that NoSQL has introduced, and is a big departure from relational databases (such as MySQL), where you would expect to see tables, relationships, and foreign keys. Every developer has experienced a project where they have had to force a relational database schema into a project that really didn't require the rigidity of tables and complex relationships. This is where CouchDB does things differently; it stores all of the data in a self-contained object with no set schema. The following diagram will help to illustrate this: In order to handle the ability for many users to belong to one-to-many groups in a relational database (such as MySQL), we would create a users table, a groups table, and a link table, called users_groups. This practice is common to most web applications. Now look at the CouchDB documents. There are no tables or link tables, just documents. These documents contain all of the data pertaining to a single object. This diagram is very simplified. If we wanted to create more logic around the groups in CouchDB, we would have had to create group documents, with a simple relationship between the user documents and group documents. Let's dig into what documents are and how CouchDB uses them. Documents To illustrate how you might use documents, first imagine that you are physically filling out the paper form of a job application. This form has information about you, your address, and past addresses. It also has information about many of your past jobs, education, certifications, and much more. A document would save all of this data exactly in the way you would see it in the physical form - all in one place, without any unnecessary complexity. In CouchDB, documents are stored as JSON objects that contain key and value pairs. Each document has reserved fields for metadata such as id, revision, and deleted. Besides the reserved fields, documents are 100 percent schema-less, meaning that each document can be formatted and treated independently with as many different variations as you might need. Example of a CouchDB document Let's take a look at an example of what a CouchDB document might look like for a blog post: { "_id": "431f956fa44b3629ba924eab05000553", "_rev": "1-c46916a8efe63fb8fec6d097007bd1c6", "title": "Why I like Chicken", "author": "Tim Juravich", "tags": [ "Chicken", "Grilled", "Tasty" ], "body": "I like chicken, especially when it's grilled." } Downloading the example code You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. JSON format The first thing you might notice is the strange markup of the document, which is JavaScript Object Notation (JSON). JSON is a lightweight data-interchange format based on JavaScript syntax and is extremely portable. CouchDB uses JSON for all communication with it. Key-value storage The next thing that you might notice is that there is a lot of information in this document. There are key-value pairs that are simple to understand, such as "title", "author", and "body", but you'll also notice that "tags" is an array of strings. CouchDB lets you embed as much information as you want directly into a document. This is a concept that might be new to relational database users who are used to normalized and structured databases. Reserved fields Let's look at the two reserved fields: _id and _rev. _id is the unique identifier of the document. This means that _id is mandatory, and no two documents can have the same value. If you don't define an _id on creation of a document, CouchDB will choose a unique one for you. _rev is the revision version of the document and is the field that helps drive CouchDB's version control system. Each time you save a document, the revision number is required so that CouchDB knows which version of the document is the newest. This is required because CouchDB does not use a locking mechanism, meaning that if two people are updating a document at the same time, then the first one to save his/her changes first, wins. One of the unique things about CouchDB's revision system is that each time a document is saved, the original document is not overwritten, and a new document is created with the new data, while CouchDB stores a backup of the previous documents in its original form in an archive. Old revisions remain available until the database is compacted, or some cleanup action occurs. The last piece of the definition sentence is the RESTful JSON API. So, let's cover that next. RESTful JSON API In order to understand REST, let's first define HyperText Transfer Protocol (HTTP ). HTTP is the underlying protocol of the Internet that defines how messages are formatted and transmitted and how services should respond when using a variety of methods. These methods consist of four main verbs, such as GET, PUT, POST, and DELETE. In order to fully understand how HTTP methods function, let's first define REST. Representation State Transfer (REST ) is a stateless protocol that accesses addressable resources through HTTP methods. Stateless means that each request contains all of the information necessary to completely understand and use the data in the request, and addressable resources means that you can access the object via a URL. That might not mean a lot in itself, but, by putting all of these ideas together, it becomes a powerful concept. Let's illustrate the power of REST by looking at two examples: Resource GET PUT POST DELETE http://localhost/collection Read a list of all of the items inside of collection Update the Collection with another collection Create a new collection Delete the collection http://localhost/collection/abc123 Read the details of the abc123 item inside of collection Update the details of abc123 inside of collection Create a new object abc123 inside of a collection Delete abc123 from collection By looking at the table, you can see that each resource is in the form of a URL. The first resource is collection, and the second resource is abc123, which lives inside of collection. Each of these resources responds differently when you pass different methods to them. This is the beauty of REST and HTTP working together. Notice the bold words I used in the table: Read, Update, Create, and Delete. These words are actually, in themselves, another concept, and it, of course, has its own term; CRUD. The unflattering term CRUD stands for Create, Read, Update, and Delete and is a concept that REST uses to define what happens to a defined resource when an HTTP method is combined with a resource in the form of a URL. So, if you were to boil all of this down, you would come to the following diagram: This diagram means: In order to CREATE a resource, you can use either the POST or PUT method In order READ a resource, you need to use the GET method In order to UPDATE a resource, you need to use the PUT method In order to DELETE a resource, you need to use the DELETE method As you can see, this concept of CRUD makes it really clear to find out what method you need to use when you want to perform a specific action. Now that we've looked at what REST means, let's move onto the term API , which means Application Programming Interface. While there are a lot of different use cases and concepts of APIs, an API is what we'll use to programmatically interact with CouchDB. Now that we have defined all of the terms, the RESTful JSON API could be defined as follows: we have the ability to interact with CouchDB by issuing an HTTP request to the CouchDB API with a defined resource, HTTP method, and any additional data. Combining all of these things means that we are using REST. After CouchDB processes our REST request, it will return with a JSON-formatted response with the result of the request. All of this background knowledge will start to make sense as we play with CouchDB's RESTful JSON API, by going through each of the HTTP methods, one at a time. We will use curl to explore each of the HTTP methods by issuing raw HTTP requests. Time for action – getting a list of all databases in CouchDB Let's issue a GET request to access CouchDB and get a list of all of the databases on the server. Run the following command in Terminal curl -X GET http://localhost:5984/_all_dbs Terminal will respond with the following: ["_users"] What just happened? We used Terminal to trigger a GET request to CouchDB's RESTful JSON API. We used one of the options: -X, of curl, to define the HTTP method. In this instance, we used GET. GET is the default method, so technically you could omit -X if you wanted to. Once CouchDB processes the request, it sends back a list of the databases that are in the CouchDB server. Currently, there is only the _users database, which is a default database that CouchDB uses to authenticate users. Time for action – creating new databases in CouchDB In this exercise, we'll issue a PUT request , which will create a new database in CouchDB. Create a new database by running the following command in Terminal: curl -X PUT http://localhost:5984/test-db Terminal will respond with the following: {"ok":true} Try creating another database with the same name by running the following command in Terminal: curl -X PUT http://localhost:5984/test-db Terminal will respond with the following: {"error":"file_exists","reason":"The database could not becreated, the file already exists."} Okay, that didn't work. So let's to try to create a database with a different name by running the following command in Terminal: curl -X PUT http://localhost:5984/another-db Terminal will respond with the following: {"ok":true} Let's check the details of the test-db database quickly and see more detailed information about it. To do that, run the following command in Terminal: curl -X GET http://localhost:5984/test-db Terminal will respond with something similar to this (I re-formatted mine for readability): {"committed_update_seq": 1,"compact_running": false,"db_name": "test-db","disk_format_version": 5,"disk_size": 4182,"doc_count": 0,"doc_del_count": 0,"instance_start_time": "1308863484343052","purge_seq": 0,"update_seq": 1} What just happened? We just used Terminal to trigger a PUT method to the created databases through CouchDB's RESTful JSON API, by passing test-db as the name of the database that we wanted to create at the end of the CouchDB root URL. When the database was successfully created, we received a message that everything went okay. Next, we created a PUT request to create another database with the same name test-db. Because there can't be more than one database with the same name, we received an error message We then used a PUT request to create a new database again, named another-db. When the database was successfully created, we received a message that everything went okay. Finally, we issued a GET request to our test-db database to find out more information on the database. It's not important to know exactly what each of these statistics mean, but it's a useful way to get an overview of a database. It's worth noting that the URL that was called in the final GET request was the same URL we called when we first created the database. The only difference is that we changed the HTTP method from PUT to GET. This is REST in action!
Read more
  • 0
  • 0
  • 5136
article-image-article-getting-started-with-html5-modernizer-url
Packt
31 Jan 2013
4 min read
Save for later

Getting Started with Modernizr

Packt
31 Jan 2013
4 min read
(For more resources on this subject, see here.) Detect and design with features, not User agents (browsers) What if you could build your website based on features instead of for the individual browser idiosyncrasies by manufacturer and version, making your website not just backward compatible but also forward compatible? You could quite potentially build a fully backward and forward compatible experience using a single code base across the entire UA spectrum. What I mean by this is instead of baking in an MSIE 7.0 version, an MSIE 8.0 version , a Firefox version, and so on of your website, and then using JavaScript to listen for, or sniff out, the browser version in play, it would be much simpler to instead build a single version of your website that supports all of the older generation, latest generation, and in many cases even future generation technologies, such as a video API,box-shadow,and first-of-type. Think of your website as a full-fledged cable television network broadcasting over 130 channels, and your users as customers that sign up for only the most basic package available, of only 15 channels. Any time that they upgrade their cable (browser) package to one offering additional channels (features), they can begin enjoying them immediately because you have already been broadcasting to each one of those channels the entire time. What happens now is that a proverbial line is drawn in the sand, and the site is built on the assumption that a particular set of features will exist and are thus supported. If not, fallbacks are in place to allow a smooth degradation of the experience as usual, but more importantly the site is built to adopt features that the browser will eventually have. Modernizr can detect CSS features, such as @font-face , box-shadow , and CSS gradients. It can also detect HTML5 elements, such as canvas , localstorage, and application cache. In all it can detect over 40 features for you, the developer. Another term commonly used to describe this technique is "progressive enhancement ". When the time fi nally comes that the user decides to upgrade their browser, the new features that the more recent browser version brings with it, for example text-shadow , will automatically be detected and picked up by your website, to be leveraged by your site with no extra work or code from you when they do. Without any additional work on your part, any text that is assigned text-shadow attributes will turn on at the fl ick of a switch so that user's experience will smoothly, and progressively be enhanced. What is Modernizr? More importantly, why should you use it? At its foundation, Modernizr is a feature-detection library powered by none other than JavaScript. Here is an example of conditionally adding CSS classes based on the browser, also known as the User Agent . When the browser parses this HTML document and fi nds a match, that class will be conditionally added to the page. Now that the browser version has been found, the developer can use CSS to alter the page based on the version of the browser that is used to parse the page. In the following example, IE 7, IE 8, and IE 9 all use a different method for a drop shadow attribute on an anchor element: /* IE7 Conditional class using UA sniffing */ .lt-ie7 a{ display: block; float: left; background: url( drop-shadow. gif ); } .lt-ie8 a{ display: inline-block; background: url( drop-shadow.png ); } .lt-ie9 a{ display: inline-block; box-shadow: 10px 5px 5px rgba(0,0,0,0.5); } The problem with the conditional method of applying styles is that not only does it require more code, but it also leaves a burden on the developer to know what browser version is capable of a given feature, in this case box-shadow . Here is the same example using Modernizr . Note how Modernizr has done the heavy lifting for you, irrespective of whether or not the box-shadow feature is supported by the browser: /* Box shadow using Modernizr CSS feature detected classes */ .box-shadow a{ box-shadow: 10px 5px 5px rgba(0,0,0,0.5); } .no-box-shadow a{ background: url( drop-shadow.gif ); }   The Modernizr namespace The Modernizr JavaScript library in your web page's header is a lightweight feature library that will test your browser for the features that it may or may not support, and store those results in a JavaScript namespace aptly named Modernizr. You can then use those test results as you build your website. From this point on everything you need to know about what features your user's browser can and cannot support can be checked for in two separate places. Going back to the cable television analogy, you now know what channels (features) your user does and does not have, and can act accordingly.
Read more
  • 0
  • 0
  • 5100

article-image-how-add-static-material-course-moodle
Packt
06 Sep 2011
7 min read
Save for later

How to Add Static Material to a Course in Moodle

Packt
06 Sep 2011
7 min read
  (For more resources on Moodle, see here.)   Kinds of static course material that can be added Static course material is added from the Add a resource drop-down menu. Using this menu, you can create: Web pages Links to anything on the Web Files A label that displays any text or image Multimedia   Adding links On your Moodle site, you can show content from anywhere on the Web by using a link. You can also link to files that you've uploaded into your course. By default, this content appears in a frame within your course. You can also choose to display it in a new window. When using content from outside sites, you need to consider the legality and reliability of using the link. Is it legal to display the material on your Moodle site? Will the material still be there when your course is running? In this example, I've linked to an online resource from the BBC, which is a fairly reliable source: Remember that the bottom of the window displays Window Settings, so you can choose to display this resource in its own window. You can also set the size of the window. You may want to make it appear in a smaller window, so that it does not completely obscure the window of your Moodle site. This will make it clearer to the student that he or she has opened a new window. To add a link to a resource on the Web: Log in to your course as a Teacher or Site Administrator. In the upper-right corner of the page, if you see a button that reads, Turn editing on, click on this button. If it reads Turn editing off, then you do not need to click on this button. (You will also find this button in the Settings menu on the leftmost side of the page.) From the Add a resource... drop-down menu, select URL. Moodle displays the Adding a new URL page. Enter a Name for the link. This is the name that people will see on the home page of your course. Enter a Description for the link. When the student sees the course's home page, they will see the Name and not the Description. However, whenever this resource is selected from the Navigation bar, the Description will be displayed. Here is a link as it appears on the home page of a course: Here is the same link, as it appears when selected from the Navigation bar: In the External URL field, enter the Web address for this link. From the Display drop-down menu, select the method that you want Moodle to use when displaying the linked page. Embed will insert the linked page into a Moodle page. Your students will see the Navigation bar, any blocks that you have added to the course and navigation links across the top of the page, just like when they view any other page in Moodle. The center of the page will be occupied by the linked page. Open will take the student away from your site, and open the linked page in the window that was occupied by Moodle. In pop-up will launch a new window, containing the linked page on top of the Moodle page. Automatic will make Moodle choose the best method for displaying the linked page. The checkboxes for Display URL name and Display URL description will affect the display of the page, only if Embed is chosen as the display method. If selected, the Name of the link will be displayed above the embedded page, and the Description will be displayed below the embedded page. Under Options, the ShowAdvanced button will display fields that allow you to set the size of the popup window. If you don't select In pop-up as the display method, these fields have no effect. Under Parameters, you can add parameters to the link. In a Web link, a parameter would add information about the course or student to the link. If you have Web programming experience, you might take advantage of this feature. For more about passing parameters in URLs, see http://en.wikipedia.org/wiki/Query_string. Under Common Module Settings, the Visible setting determines if this resource is visible to students. Teachers and site Administrators can always see the resource. Setting this to Hide will completely hide the resource. Teachers can hide some resources and activities at the beginning of a course, and reveal them as the course progresses. Show/Hide versus Restrict availability If you want a resource to be visible, but not available, then use the Restrict Availability settings further down on the page. Those settings enable you to have a resource's name and its description appear, but still make the resource unavailable. You might want to do this for resources that will be used later in a course, when you don't want the student to work ahead of the syllabus. The ID number field allows you to enter an identifier for this resource, which will appear in the Gradebook. If you export grades from the Gradebook and then import them into an external database, you might want the course ID number here to match the ID number that you use in that database. The Restrict Availability settings allow you to set two kinds of conditions that will control whether this resource is available to the student. The Accessible from and Accessible until settings enable you to set dates for when this resource will be available. The Grade condition setting allows you to specify the grade that a student must achieve in another Activity in this course, before being able to access this Resource. The setting for Before activity is available determines if the Resource will be visible while it is unavailable. If it is visible but unavailable, Moodle will display the conditions needed to make it available (achieve a grade, wait for a date, and so on.). Click on one of the Save buttons at the bottom of the page to save your work.   Adding pages Under the Add a resource drop-down menu, select Page to add a Web page to a course. A link to the page that you create will appear on the course's home page. Moodle's HTML editor When you add a Page to your course, Moodle displays a Web page editor. This editor is based on an open source web page editor called TinyMCE. You can use this editor to compose a web page for your course. This page can contain almost anything that a web page outside of Moodle can contain. Pasting text into a Moodle page Many times, we prefer to write text in our favorite word processor instead of writing it in Moodle. Or we may find text that we can legally copy and paste into a Moodle page, somewhere else. Moodle's text editor does allow you to do this. To paste text into a page, you can just use the appropriate keyboard shortcut. Try Ctrl + V for Windows PCs and Apple + V for Macintoshes. If you use this method, the format of the text will be preserved. To paste plain text, without the format of the original text, click on the Paste as Plain Text icon, as shown below: When you paste text from a Microsoft Word document into a web page, it usually includes a lot of non-standard HTML code. This code doesn't work well in all browsers, and makes it more difficult to edit the HTML code in your page. Many advanced web page editors, such as AdobeDreamWeaver, have the ability to clean up Word HTML code. Moodle's web page editor can also clean up Word HTML code. When pasting text that was copied from Word, use the Paste from Word icon, as shown in the image below. This will strip out most of Word's non-standard HTML code.  
Read more
  • 0
  • 0
  • 5097
Modal Close icon
Modal Close icon