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

How-To Tutorials

7018 Articles
article-image-building-multipage-forms-intermediate
Packt
11 Jun 2013
5 min read
Save for later

Building multipage forms (Intermediate)

Packt
11 Jun 2013
5 min read
(For more resources related to this topic, see here.) Getting ready We'll separate our existing user registration form already created to multipage forms. The sections will be for personal information, address details, and contact information. How to do it... All code related to the form is written in a file named _form under protected/views/user. We are dividing the input fields into three sections, so create three separate files in the same folder with the names _page1, _page2, and _page3. Separate the code's respective files. Some sample lines are as follows: <?php $form=$this->beginWidget('CActiveForm', array( 'id'=>'user-form', 'enableAjaxValidation'=>false, 'stateful'=>true, )); ?> <div class="row"> <?php echo $form->labelEx($model,'first_name'); ?> <?php echo $form->textField($model,'first_name', array( 'size'=>50, 'maxlength'=>50 )); ?> <?php echo $form->error($model,'first_name'); ?> </div> ..... ..... <div class="row buttons"> <?php echo CHtml::submitButton('Next', array( 'name'=>'page2' )); ?> </div> <?php $this->endWidget(); ?> .... <div class="row buttons"> <?php echo CHtml::submitButton('back', array( 'name'=>'page1' )); ?> <?php echo CHtml::submitButton('Next', array( 'name'=>'page3' )); ?> </div> <div class="row buttons"> <?php echo CHtml::submitButton('Back', array( 'name'=>'page2' )); ?> <?php echo CHtml::submitButton('submit', array( 'name'=>'submit' )); ?> </div> Now, in the User controller, change the code for actionCreate as follows: public function actionCreate() { if(isset($_POST['page1'])) { $model = new User('page1'); $this->checkPageState($model, $_POST['User']); $view = '_page1'; } elseif(isset($_POST['page2'])) { $model = new User('page1'); $this->checkPageState($model, $_POST['User']); if($model->validate()) { $view = '_page2'; $model->scenario = 'page2'; } else { $view = '_page1'; } } .... $this->render($view, array('model'=>$model)); } And add a function, checkPageState(), as follows: private function checkPageState(&$model, $data) { $model->attributes = $this->getPageState('page', array()); $model->attributes = $data; $this->setPageState('page', $model->attributes); } Lastly, create scenarios in the model User to validate each page of the form separately. Add three arrays specifying all the required fields per page, as follows: return array( array('first_name, last_name, gender, dob', 'required', 'on'=>'page1' ), array('address_1, city, state, country', 'required', 'on'=>'page2' ), array('phone_number_1, email_1', 'required', 'on'=>'page3' ), How it works... We have separated all our input fields into three forms. Each page contains an entire standalone form that accepts the input from the user, validates it from the server, and stores the data till we finally submit this form. The parameter stateful passed to the CactiveForm widget specifies the form needed to maintain the state across the pages. To do this, Yii creates a hidden field in each form with the name YII_PAGE_STATE, as shown in the following screenshot: All the data submitted on the first page is stored in this hidden field and passed to the server with the second page. To read the data from this field we have used the method getPageState(), and to write we have used setPageState(). We have added a private method checkPageState() to the User controller, which reads the page state, if any, and assigns it to $model->attributes, then assigns data from the current form using $model->attributes = $_POST['User'], and finally overwrites the page state with freshly combined data. When we click on Next on _page1, we set the POST variable page2, which in turn executes the second block in the if-else ladder in actionCreate. In this article, we create an instance of the model User with scenario set to _page1 (as we need to validate the data received from _page1). With a call to checkPageState(), we check the current page state and add any new data from _page1 to the page state. Then we check if the data filled is valid using $model->validate() . If the model passes the validation we set, apply view to _page2 and set $model->scenario to _page2, to mark the required fields on _page2. If the validation fails, we set the view to _page1 with the validation errors set in the model. At the end of the action, we render the selected view with the current state of the model. If any validation errors are set, they are listed on the same page; else, the next page will be rendered. The same steps are repeated for _page2 as well. When the submit button is clicked on on _page3, we retrieve the previous data from the page state using getPageState(). Here we are not using checkPageState() as now we do not need to store any data to the page state. We simply assign the data from _page3 to the model, and if the model validates we save all the data to the database with $model->save(). After saving, we are redirected to actionView(), where data from all three forms is listed as shown in the following screenshot: Summary In this article, we saw the importance of dividing big single forms into mulitpage forms. The article provided an insight into the making of multipage forms. Resources for Article : Further resources on this subject: Play! Framework 2 – Dealing with Content [Article] Play Framework: Introduction to Writing Modules [Article] Generating Content in WordPress Top Plugins—A Sequel [Article]
Read more
  • 0
  • 0
  • 11467

article-image-qr-codes-geolocation-google-maps-api-and-html5-video
Packt
07 Jun 2013
9 min read
Save for later

QR Codes, Geolocation, Google Maps API, and HTML5 Video

Packt
07 Jun 2013
9 min read
(For more resources related to this topic, see here.) QR codes We love our smartphones. We love showing off what our smartphones can do. So, when those cryptic squares, as shown in the following figure, started showing up all over the place and befuddling the masses, smartphone users quickly stepped up and started showing people what it's all about in the same overly-enthusiastic manner that we whip them out to answer even the most trivial question heard in passing. And, since it looks like NFC isn't taking off anytime soon, we'd better be familiar with QR codes and how to leverage them. The data shows that knowledge and usage of QR codes is very high according to surveys:(http://researchaccess.com/2012/01/new-data-on-qrcode-adoption/) More than two-thirds of smartphone users have scanned a code More than 70 percent of the users say they'd do it again (especially for a discount) Wait, what does this have to do with jQuery Mobile? Traffic. Big-time successful traffic. A banner ad is considered successful if only two percent of people lick through (http://en.wikipedia.org/wiki/Clickthrough_rate). QR codes get more than 66 percent! I'd say it's a pretty good way to get people to our reations and, thus, should be of concern. But QR codes are for more than just URLs. Here we have a URL, a block of text, a phone number, and an SMS in the following QR codes: There are many ways to generate QR codes (http://www.the-qrcode-generator.com/, http://www.qrstuff.com/). Really, just search for QR Code Generator on Google and you'll have numerous options. Let us consider a local movie theater chain. Dickinson Theatres (dtmovies.com) has been around since the 1920s and is considering throwing its hat into the mobile ring. Perhaps they will invest in a mobile website, and go all-out in placing posters and ads in bus stops and other outdoor locations. Naturally, people are going to start scanning, and this is valuable to us because they're going to tell us exactly which locations are paying off. This is really a first in the advertising industry. We have a medium that seems to spur people to interact on devices that will tell us exactly where they were when they scanned it. Geolocation matters and this can help us find the right locations. Geolocation When GPS first came out on phones, it was pretty useless for anything other than police tracking in case of emergencies. Today, it is making the devices that we hold in our hands even more personal than our personal computers. For now, we can get a latitude, longitude, and timestamp very dependably. The geolocation API specification from the W3C can be found at http://dev.w3.org/geo/api/spec-source.html. For now, we'll pretend that we have a poster prompting the user to scan a QR code to find the nearest theater and show the timings. It would bring the user to a page like this: Since there's no better first date than dinner and a movie, the movie going crowd tends to skew a bit to the younger side. Unfortunately, that group does not tend to have a lot of money. They may have more feature phones than smartphones. Some might only have very basic browsers. Maybe they have JavaScript, but we can't count on it. If they do, they might have geolocation. Regardless, given the audience, progressive enhancement is going to be the key. The first thing we'll do is create a base level page with a simple form that will submit a zip code to a server. Since we're using our template from before, we'll add validation to the form for anyone who has JavaScript using the validateMe class. If they have JavaScript and geolocation, we'll replace the form with a message saying that we're trying to find their location. For now, don't worry about creating this file. The source code is incomplete at this stage. This page will evolve and the final version will be in the source package for the article in the file called qrresponse. php as shown in the following code: <?php $documentTitle = "Dickinson Theatres"; $headerLeftHref = "/"; $headerLeftLinkText = "Home"; $headerLeftIcon = "home"; $headerTitle = ""; $headerRightHref = "tel:8165555555"; $headerRightLinkText = "Call"; $headerRightIcon = "grid"; $fullSiteLinkHref = "/"; ?> <!DOCTYPE html> <html> <head> <?php include("includes/meta.php"); ?> </head> <body> <div id="qrfindclosest" data-role="page"> <div class="logoContainer ui-shadow"></div> <div data-role="content"> <div id="latLong> <form id="findTheaterForm" action="fullshowtimes.php" method="get" class="validateMe"> <p> <label for="zip">Enter Zip Code</label> <input type="tel" name="zip" id="zip" class="required number"/> </p> <p><input type="submit" value="Go"></p> </form> </div> <p> <ul id="showing" data-role="listview" class="movieListings" data-dividertheme="g"> </ul> </p> </div> <?php include("includes/footer.php"); ?> </div> <script type="text/javascript"> //We'll put our page specific code here soon </script> </body> </html> For anyone who does not have JavaScript, this is what they will see, nothing special. We could spruce it up with a little CSS but what would be the point? If they're on a browser that doesn't have JavaScript, there's pretty good chance their browser is also miserable at rendering CSS. That's fine really. After all, progressive enhancement doesn't necessarily mean making it wonderful for everyone, it just means being sure it works for everyone. Most will never see this but if they do, it will work just fine For everyone else, we'll need to start working with JavaScript to get our theater data in a format we can digest programmatically. JSON is perfectly suited for this task. If you are already familiar with the concept of JSON, skip to the next paragraph now. If you're not familiar with it, basically, it's another way of shipping data across the Interwebs. It's like XML but more useful. It's less verbose and can be directly interacted with and manipulated using JavaScript because it's actually written in JavaScript. JSON is an acronym for JavaScript Object Notation. A special thank you goes out to Douglas Crockford (the father of JSON). XML still has its place on the server. It has no business in the browser as a data format if you can get JSON. This is such a widespread view that at the last developer conference I went to, one of the speakers chuckled as he asked, "Is anyone still actually using XML?" { "theaters":[ { "id":161, "name":"Chenal 9 IMAX Theatre", "address":"17825 Chenal Parkway", "city":"Little Rock", "state":"AR", "zip":"72223", "distance":9999, "geo":{"lat":34.7684775,"long":-92.4599322}, "phone":"501-821-2616" }, { "id":158, "name":"Gateway 12 IMAX Theatre", "address":"1935 S. Signal Butte", "city":"Mesa", "state":"AZ", "zip":"85209", "distance":9999, "geo":{"lat":33.3788674,"long":-111.6016081}, "phone":"480-354-8030" }, { "id":135, "name":"Northglen 14 Theatre", "address":"4900 N.E. 80th Street", "city":"Kansas City", "state":"MO", "zip":"64119", "distance":9999, "geo":{"lat":39.240027,"long":-94.5226432}, "phone":"816-468-1100" } ] } Now that we have data to work with, we can prepare the on-page scripts. Let's put the following chunks of JavaScript in a script tag at the bottom of the HTML where we had the comment: We'll put our page specific code here soon //declare our global variables var theaterData = null; var timestamp = null; var latitude = null; var longitude = null; var closestTheater = null; //Once the page is initialized, hide the manual zip code form //and place a message saying that we're attempting to find //their location. $(document).on("pageinit", "#qrfindclosest", function(){ if(navigator.geolocation){ $("#findTheaterForm").hide(); $("#latLong").append("<p id='finding'>Finding your location...</ p>"); } }); //Once the page is showing, go grab the theater data and find out which one is closest. $(document).on("pageshow", "#qrfindclosest", function(){ theaterData = $.getJSON("js/theaters.js", function(data){ theaterData = data; selectClosestTheater(); }); }); function selectClosestTheater(){ navigator.geolocation.getCurrentPosition( function(position) { //success latitude = position.coords.latitude; longitude = position.coords.longitude; timestamp = position.timestamp; for(var x = 0; x < theaterData.theaters.length; x++) { var theater = theaterData.theaters[x]; var distance = getDistance(latitude, longitude, theater.geo.lat, theater.geo.long); theaterData.theaters[x].distance = distance; }} theaterData.theaters.sort(compareDistances); closestTheater = theaterData.theaters[0]; _gaq.push(['_trackEvent', "qr", "ad_scan", (""+latitude+","+longitude) ]); var dt = new Date(); dt.setTime(timestamp); $("#latLong").html("<div class='theaterName'>" +closestTheater.name+"</div><strong>" +closestTheater.distance.toFixed(2) +"miles</strong><br/>" +closestTheater.address+"<br/>" +closestTheater.city+", "+closestTheater.state+" " +closestTheater.zip+"<br/><a href='tel:" +closestTheater.phone+"'>" +closestTheater.phone+"</a>"); $("#showing").load("showtimes.php", function(){ $("#showing").listview('refresh'); }); }, function(error){ //error switch(error.code) { case error.TIMEOUT: $("#latLong").prepend("<div class='ui-bar-e'> Unable to get your position: Timeout</div>"); break; case error.POSITION_UNAVAILABLE: $("#latLong").prepend("<div class='ui-bar-e'> Unable to get your position: Position unavailable</div>"); break; case error.PERMISSION_DENIED: $("#latLong").prepend("<div class='ui-bar-e'> Unable to get your position: Permission denied. You may want to check your settings.</div>"); break; case error.UNKNOWN_ERROR: $("#latLong").prepend("<div class='ui-bar-e'> Unknown error while trying to access your position.</div>"); break; } $("#finding").hide(); $("#findTheaterForm").show(); }, {maximumAge:600000}); //nothing too stale } The key here is the function geolocation.getCurrentPosition, which will prompt the user to allow us access to their location data, as shown here on iPhone If somebody is a privacy advocate, they may have turned off all location services. In this case, we'll need to inform the user that their choice has impacted our ability to help them. That's what the error function is all about. In such a case, we'll display an error message and show the standard form again.
Read more
  • 0
  • 0
  • 9271

article-image-implementing-persistence-redis-intermediate
Packt
06 Jun 2013
10 min read
Save for later

Implementing persistence in Redis (Intermediate)

Packt
06 Jun 2013
10 min read
(For more resources related to this topic, see here.) Getting ready Redis provides configuration settings for persistence and for enabling durability of data depending on the project statement. If durability of data is critical If durability of data is not important You can achieve persistence of data using the snapshotting mode, which is the simplest mode in Redis. Depending on the configuration, Redis saves a dump of all the data sets in its memory into a single RDB file. The interval in which Redis dumps the memory can be configured to happen every X seconds or after Y operations. Consider an example of a moderately busy server that receives 15,000 changes every minute over its 1 GB data set in memory. Based on the snapshotting rule, the data will be stored every 60 seconds or whenever there are at least 15,000 writes. So the snapshotting runs every minute and writes the entire data of 1 GB to the disk, which soon turns ugly and very inefficient. To solve this particular problem, Redis provides another way of persistence, Append-only file (AOF), which is the main persistence option in Redis. This is similar to journal files, where all the operations performed are recorded and replayed in the same order to rebuild the exact state. Redis's AOF persistence supports three different modes: No fsync: In this mode, we take a chance and let the operating system decide when to flush the data. This is the fastest of the three modes. fsync every second: This mode is a compromised middle point between performance and durability. Data will be flushed using fsync every second. If the disk is not able to match the write speed, the fsync can take more than a second, in which case Redis delays the write up to another second. So this mode guarantees a write to be committed to OS buffers and transferred to the disk within 2 seconds in the worstcase scenario. fsync always: This is the last and safest mode. This provides complete durability of data at a heavy cost to performance. In this mode, the data needs to be written to the file and synced with the disk using fsync before the client receives an acknowledgment. This is the slowest of all three modes. How to do it... First let us see how to configure snapshotting, followed by the Append-only file method: In Redis, we can configure when a new snapshot of the data set will be performed. For example, Redis can be configured to dump the memory if the last dump was created more than 30 seconds ago and there are at least 100 keys that are modified or created. Snapshotting should be configured in the /etc/redis/6379.conf file. The configuration can be as follows: save 900 1save 60 10000 The first line translates to take a snapshot of data after 900 seconds if at least one key has changed, while the second line translates to snapshotting every 60 seconds if 10,000 keys have been modified in the meantime. The configuration parameter rdbcompression defines whether the RDB file is to be compressed or not. There is a trade-off between the CPU and RDB dump file size. We are interested in changing the dump's filename using the dbfilename parameter. Redis uses the current folder to create the dump files. For convenience, it is advised to store the RDB file in a separate folder. dbfilename redis-snapshot.rdbdir /var/lib/redis/ Let us run a small test to make sure the RDB dump is working. Start the server again. Connect to the server using redis-cli, as we did already. To test whether our snapshotting is working, issue the following commands: SET Key ValueSAVE After the SAVE command, a file should be created in the folder /var/lib/redis with the name redis-snapshot.rdb. This confirms that our installation is able to take a snapshot of our data into a file. Now let us see how to configure persistence in Redis using the AOF method: The configuration for persistence through AOF also goes into the same file located in /etc/redis/6379.conf. By default, the Append-only mode is not enabled. Enable it using the appendonly parameter. appendonly yes Also, if you would like to specify a filename for the AOF log, uncomment the line and change the filename. appendfilename redis-aof.aof The appendfsync everysec command provides a good balance between performance and durability. appendfsync everysec Redis needs to know when it has to rewrite the AOF file. This will be decided based on two configuration parameters, as follows: auto-aof-rewrite-percentage 100auto-aof-rewrite-min-size 64mb Unless the minimum size is reached and the percentage of the increase in size when compared to the last rewrite is less than 100 percent, the AOF rewrite will not be performed. How it works... First let us see how snapshotting works. When one of the criteria is met, Redis forks the process. The child process starts writing the RDB file to the disk at the folder specified in our configuration file. Meanwhile, the parent process continues to serve the requests. The problem with this approach is that the parent process stores the keys, which change during this snapshotting by the child, in the extra memory. In the worst-case scenario, if all the keys are modified, the memory usage spikes to roughly double. Caution Be aware that the bigger the RDB file, the longer it takes Redis to restore the data on startup. Corruption of the RDB file is not possible as it is created by the append-only method from the data in Redis's memory, by the child process. The new RDB file is created as a temporary file and is then renamed to the destination file using the atomic rename system call once the dump is completed. AOF's working is simple. Every time a write operation is performed, the command operation gets logged into a logfile. The format used in the logfile is the same as the format used by clients to communicate to the server. This helps in easy parsing of AOF files, which brings in the possibility of replaying the operation in another Redis instance. Only the operations that change the data set are written to the log. This log will be used on startup to reconstruct the exact data. As we are continuously writing the operations into the log, the AOF file explodes in size as compared to the amount of operations performed. So, usually, the size of the AOF file is larger than the RDB dump. Redis manages the increasing size of the data log by compacting the file in a non-blocking manner periodically. For example, say a specific key, key1, has changed 100 times using the SET command. In order to recreate the final state in the last minute, only the last SET command is required. We do not need information about the previous 99 SET commands. This might look simple in theory, but it gets complex when dealing with complex data structures and operations such as union and intersection. Due to this complexity, it becomes very difficult to compress the existing file. To reduce the complexity of compacting the AOF, Redis starts with the data in the memory and rewrites the AOF file from scratch. This is more similar to the snapshotting method. Redis forks a child process that recreates the AOF file and performs an atomic rename to swap the old file with a new one. The same problem, of the requirement of extra memory for operations performed during the rewrite, is present here. So the memory required can spike up to two times based on the operations while writing an AOF file. There's more... Both snapshotting and AOF have their own advantages and limitations, which makes it ideal to use both at the same time. Let us now discuss the major advantages and limitations in the snapshotting method. Advantages of snapshotting The advantages of configuring snapshotting in Redis are as follows: RDB is a single compact file that cannot get corrupted due to the way it is created. It is very easy to implement. This dump file is perfect to take backups and for disaster recovery of remote servers. The RDB file can just be copied and saved for future recoveries. In comparison, this approach has little or no influence over performance as the only work the parent process needs to perform is forking a child process. The parent process will never perform any disk operations; they are all performed by the child process. As an RDB file can be compressed, it provides a faster restart when compared to the append-only file method. Limitations of snapshotting Snapshotting, in spite of the advantages mentioned, has a few limitations that you should be aware of: The periodic background save can result in significant loss of data in case of server or hardware failure. The fork() process used to save the data might take a moment, during which the server will stop serving clients. The larger the data set to be saved, the longer it takes the fork() process to complete. The memory needed for the data set might double in the worst-case scenario, when all the keys in the memory are modified while snapshotting is in progress. What should we use? Now that we have discussed both the modes of persistence Redis provides us with, the big question is what should we use? The answer to this question is entirely based on our application and requirements. In cases where we expect good durability, both snapshotting and AOF can be turned on and be made to work in unison, providing us with redundant persistence. Redis always restores the data from AOF wherever applicable, as it is supposed to have better durability with little loss of data. Both RDB and AOF files can be copied and stored for future use or for recovering another instance of Redis. In a few cases, where performance is very critical, memory usage is limited, and persistence is also paramount, persistence can be turned off completely. In these cases, replication can be used to get durability. Replication is a process in which two Redis instances, one master and one slave, are in sync with the same data. Clients are served by the master, and the master server syncs the data with a slave. Replication setup for persistence Consider a setup as shown in the preceding image; that is: Master instance with no persistence Slave instance with AOF enabled In this case, the master does not need to perform any background disk operations and is fully dedicated to serve client requests, except for a trivial slave connection. The slave server configured with AOF performs the disk operations. As mentioned before, this file can be used to restore the master in case of a disaster. Persistence in Redis is a matter of configuration, balancing the trade-off between performance, disk I/O, and data durability. If you are looking for more information on persistence in Redis, you will find the article by Salvatore Sanfilippo at http://oldblog.antirez.com/post/redis-persistence-demystified.html interesting. Summary This article helps you to understand the persistence option available in Redis, which could ease your efforts of adding Redis to your application stack. Resources for Article : Further resources on this subject: Using Execnet for Parallel and Distributed Processing with NLTK [Article] Parsing Specific Data in Python Text Processing [Article] Python Text Processing with NLTK: Storing Frequency Distributions in Redis [Article]
Read more
  • 0
  • 3
  • 7259

article-image-introduction-3d-design-using-autocad
Packt
06 Jun 2013
10 min read
Save for later

Introduction to 3D Design using AutoCAD

Packt
06 Jun 2013
10 min read
(For more resources related to this topic, see here.) The Z coordinate 3D is all about the third Z coordinate. In 2D, we only care for the X and Y axes, but never used the Z axis. And most of the time, we don't even use coordinates, just the top-twenty AutoCAD commands, the Ortho tool, and so on. But in 3D, the correct use of coordinates can substantially accelerate our work. We will first briefly cover how to introduce points by coordinates and how to extrapolate to the third dimension. Absolute coordinates The location of all entities in AutoCAD is related to a coordinate system. Any coordinate system is characterized by an origin and positive directions for the X and Y axes. The Z axis is obtained directly from the X and Y axes by the right-hand rule: if we rotate the right hand from the X axis to the Y axis, the thumb indicates the positive Z direction. Picture that when prompting for a point; besides specifying it in the drawing area with a pointing device such as a mouse, we can enter coordinates using the keyboard. The format for the absolute Cartesian coordinates related to the origin is defined by the values of the three orthogonal coordinates, namely, X, Y, and Z, separated by commas: X coordinate, Y coordinate, Z coordinate The Z coordinate can be omitted. For instance, if we define a point with the absolute coordinates 30, 20, and 10, this means 30 absolute is in the X direction, 20 is in the Y direction, and 10 is in the Z direction. Relative coordinates Frequently, we want to specify a point in the coordinates, but one that is related to the previous point. The format for the relative Cartesian coordinates is defined by the symbol AT (@), followed by increment values in the three directions, separated by commas: @X increment, Y increment, Z increment Of course, one or more increments can be 0. The Z increment can be omitted. For instance, if we define a point with relative coordinates, @0,20,10, this means in relation to the previous point, 0 is in X, 20 is in Y, and 10 is in Z directions. Point filters When we want to specify a point but decompose it step-by-step, that is, separate its coordinates based on different locations, we may use filters. When prompting for a point, we access filters by digitizing the X, Y, or Z axes for individual coordinates, or XY, YZ, or ZX for pairs of coordinates. Another way is from the osnap menu, CTRL + mouse right-click, and then Point Filters. AutoCAD requests for the remaining coordinates until the completion of point definition. Imagine that we want to specify a point, for instance, the center of a circle, where its X coordinate is given by the midpoint of an edge, its y coordinate is the midpoint of another edge, and finally its Z coordinate is any point on a top face. Assuming that Midpoint osnap is predefined, the dialog should be: Command: CIRCLESpecify center point for circle or [3P/2P/Ttr (tan tan radius)]: .Xof midpoint of edge(need YZ): .Yof midpoint of edge(need Z): any point on top faceSpecify radius of circle or [Diameter]: value Workspaces AutoCAD comes with several workspaces. It's up to each of us to choose a workspace based on a classic environment or the ribbon. To change workspaces, we can pick the workspace switching button on the status bar: There are other processes for acceding this command such as the workspaces list on the Quick Access Toolbar (title bar), the Workspaces toolbar, or by digitizing WSCURRENT, but the access shown is consistent among all versions and always available. Classic environment The classic environment is based on the toolbars and the menu bar and doesn't use the ribbon. AutoCAD comes with AutoCAD Classic workspace, but it's very simple to adapt and view the suitable toolbars for 3D. The advantages of using this environment are speed and consistency. To show another toolbar, we right-click over any toolbar and choose it. Typically, we want to have the following toolbars visible besides Standard and Layers: Layers II, Modeling, Solid Editing, and Render: Ribbon environment Since the 2009 version, AutoCAD also allows for a ribbon-based environment. Normally, this environment uses neither toolbars nor the menu bar. AutoCAD comes with two ribbon workspaces, namely, 3D Basics and 3D Modeling; the first being less useful than the second. The advantages are that we have consistency with other software, commands are divided into panels and tabs, the ribbon can be collapsed to a single line, and it includes some commands not available on the toolbars. The disadvantage is that as it's a dynamic environment, we frequently have to activate other panels to access commands and some important commands and functions are not always visible: When modeling in 3D, the layers list visibility is almost mandatory. We may add this list to the Quick Access Toolbar by applying the CUI command or by right-clicking above the command icon we want to add. Another way is to pull the Layers panel to the drawing area, thus making it permanently visible. Layers, transparency, and other properties When we are modeling in AutoCAD, the ability to control object properties is essential. After some hours spent on a new 3D model, we can have hundreds of objects that overlap and obscure the model's visibility. Here are the most important properties. Layers If a correct layers application is fundamental in 2D, in 3D it assumes extreme importance. Each type of 3D object should be in a proper layer, thus allowing us to control its properties: Name: A good piece of advice is to not mix 2D with 3D objects in the same layers. So, layers for 3D objects must be easily identified, for instance, by adding a 3D prefix. Freeze/Thaw: In 3D, the density of screen information can be huge. So freezing and unfreezing layers is a permanent process. It's better to freeze the layers than to turn off because objects on frozen layers are not processed (for instance, regenerating or counting for ZOOM Extents), thus accelerating the 3D process. Lock/Unlock: It's quite annoying to notice that at an advanced phase of our project, our walls moved and caused several errors. If we need that information visible, the best way to avoid these errors is to lock layers. Color: A good and logical color palette assigned to our layers can improve our understanding while modeling. Transparency: If we want to see through walls or other objects at the creation process, we may give a value between 0 and 90 percent to the layers transparency. Last but not least, the best and the easiest process to assign rendering materials to objects is by layer, so another good point is to apply a correct and detailed layer scheme. Transparency Transparency, as a property for layers or for objects, has been available since Version 2011. Besides its utility for layers, it can also be applied directly to objects. For instance, we may have a layer called 3D-SLAB and just want to see through the upper slab. We can change the objects' transparency with PROPERTIES (Ctrl + 1). To see transparencies in the drawing area, the TPY button (on the status bar) must be on. Visibility Another recent improvement in AutoCAD is the ability to hide or to isolate objects without changing layer properties. We select the objects to hide or to isolate (all objects not selected are hidden) and right-click on them. On the cursor menu, we choose Isolate and then: Isolate Objects: All objects not selected are invisible, using the ISOLATEOBJECTS command Hide Objects: The selected objects are invisible, using the HIDEOBJECTS command End Object Isolation: All objects are turned on, using the UNISOLATEOBJECTS command. There is a small lamp icon on the status bar, the second icon from the right. If the lamp is red, it means that there are hidden objects; if it is yellow, all objects are visible: Shown on the following image is the application of transparency and hide objects to the left wall and the upper slab: Auxiliary tools AutoCAD software is very precise and the correct application of these auxiliary tools is a key factor for good projects. All users should be familiar with at least Ortho and Osnap tools. Following is the application of auxiliary tools in 3D projects complemented with the first exercise. OSNAP, ORTHO, POLAR, and OTRACK auxiliary tools Let's start with object snapping, probably the most frequently used tool for precision. Every time AutoCAD prompts for a point, we can access predefined object snaps (also known as osnaps) if the OSNAP button on the status bar is on. To change it, we only have to click on the OSNAP button or press F3. If we want an individual osnap, we can, among other ways, digitize the first three letters (for instance, MID for midpoint) or use the osnap menu (CTRL + right-click). Osnaps work everywhere in 3D (which is great) and is especially useful is the Extension osnap mode, which allows you to specify a point with a distance in the direction of any edge. But what if we want to specify the projection of 3D points onto the working XY plane? Easy! If the OSNAPZ variable is set to 1, all specified points are projected onto the plane. This variable is not saved and 0 is assigned as the initial value. More great news is that ORTHO (F8) and POLAR (F10) work in 3D. That is, we can specify points by directing the cursor along the Z axis and assign distances. Lots of @ spared, no? OTRACK (F11), used to derive points from predefined osnaps, also works along the Z-axis direction. We pause over an osnap and can assign a distance along a specific direction or just obtain a crossing: 3DOsnap tool Starting with Version 2011, AutoCAD allows you to specify 3D object snaps. Also, here we can access predefined 3D osnaps keeping 3DOSNAP (F4) on, or we can access them individually. There are osnaps for vertices, midpoints on edges, centers of faces, knots (spline points), points perpendicular to faces, and points nearest to faces. Exercise 1.1 Using the LINE command, coordinates, and auxiliary tools, let's create a cabinet skeleton. All dimensions are in meters and we start from the lower-left corner. The ORTHO or POLAR button must be on and the OTRACK and OSNAP buttons with Endpoint and Midpoint predefined. As in 2D, rotating the wheel mouse forward, we zoom in; rotating the wheel backward, we zoom out; all related to cursor position. To automatically orbit around the model, we hold down SHIFT and the wheel simultaneously. The cursor changes to two small ellipses and then we drag the mouse to orbit around the model. Visualization is the subject of the next article We run the LINE command at any point, block direction X (POLAR or ORTHO) and assign the distance: Command: LINESpecify first point: any pointSpecify next point or [Undo]: 0.6 We block the Z direction and assign the distance: Specify next point or [Undo]: 0.7 The best way to specify this point is with relative coordinates: Specify next point or [Close/Undo]: @-0.3,0,0.4 We block the Z direction and assign the distance: Specify next point or [Close/Undo]: 0.7 The best way to close the left polygon is to pause over the first point, move the cursor up to find the crossing, with Polar or Ortho coming from the last point, and apply Close option to close the polygon: Specify next point or [Close/Undo]: point with OTRACKSpecify next point or [Close/Undo]: C We copy all lines 1 meter in the Y direction: Command: COPYSelect objects: Specify opposite corner: 6 foundSelect objects: EnterCurrent settings: Copy mode = MultipleSpecify base point or [Displacement/mOde] <Displacement>: pointSpecify second point or [Array] <use first point as displacement>:1Specify second point or [Array/Exit/Undo] <Exit>: Enter We complete the cabinet skeleton by drawing lines between endpoints Command: LINE
Read more
  • 0
  • 0
  • 6174

article-image-article-playing-particles
Packt
06 Jun 2013
19 min read
Save for later

Playing with Particles

Packt
06 Jun 2013
19 min read
(For more resources related to this topic, see here.) Introducing particle effects Particle effects are the decorative flourishes used in games to represent dynamic and complex phenomena, such as fire, smoke, and rain. To create a particle effect, it requires three elements: a System, Emitters, and the Particles themselves. Understanding particle systems Particle systems are the universe in which the particles and emitters live. Much like the universe, we cannot define the size but we can define a point of origin which all emitters and particles will be placed relative to. We can also have multiple particle systems in existence at any given time, which can be set to draw the particles at different depths. While we can have as many particle systems as we want, it is best to have as few as possible in order to prevent possible memory leaks. The reason for this is that once a particle system is created, it will remain in existence forever unless it is manually destroyed. Destroying the instance that spawned it or changing rooms will not remove the system, so make sure it is removed when it is no longer needed. By destroying a particle system, it will remove all the emitters and particles in that system along with it. Utilizing particle emitters Particle emitters are defined areas within a system from which particles will spawn. There are two types of emitters to choose from: Burst emitters that spawn particles a single time, and Stream emitters that spew particles continuously over time. We can define the size and shape of the region in space for each emitter, as well as how the particles should be distributed within the region. Image When defining the region in space, there are four Shape options: DIAMOND, ELLIPSE, LINE, and RECTANGLE. An example of each can be seen in the preceding diagram, all using exactly the same dimensions, amount of particles, and distribution. While there is no functional difference between using any one of these shapes, the effect itself can benefit from a properly chosen shape. For example, only a LINE can make an effect appear to be angled 30 degrees. Image The distribution of the particles can also affect how the particles are expelled from the emitter. As can be seen in the preceding diagram, there are three different distributions. LINEAR will spawn particles with an equal random distribution throughout the emitter region. GAUSSIAN will spawn particles more towards the center of the region. INVGAUSSIAN is the inverse of GAUSSIAN, wherein the particles will spawn closer to the edges of the emitter. Applying particles Particles are the graphic resources that are spawned from the emitters. There are two types of particles that can be created: Shapes and Sprites. Shapes are the collection of 64 x 64 pixel sprites that comes built-in with GameMaker: Studio for use as particles. The shapes, as seen in the next diagram, are suitable for the majority of the most common effects, such as fireworks and flames. When wanting to create something more specialized for a game, we can use any Sprite in the Resource tree. Image There are a lot of things we can do with particles by adjusting the many attributes available. We can define ranges for how long it lives, the color it should be, and how it moves. We can even spawn more particles at the point of death for each particle. There are, however, some things that we cannot do. In order to keep the graphics processing costs low, there is no ability to manipulate individual particles within an effect. Also, particles cannot interact with objects in any way, so there is no way to know if a particle has collided with an instance in the world. If we need this kind of control, we need to build objects instead. Designing the look of a particle event is generally a trial and error process that can take a very long time. To speed things up, try using one of the many particle effect generators available on the Internet, such as Particle Designer 2.5 by Alert Games found here: http://alertgames.net/index.php?page=s/pd2. HTML5 limitations Using particle effects can really improve the visual quality of a game, but when developing a game intended to be played in a browser we need to be careful. Before implementing a particle effect, it is important to understand potential problems we may encounter. The biggest issue surrounding particles is that in order for them to be rendered smoothly without any lag, they need to be rendered with the graphics processor instead of the main CPU. Most browsers allow this to happen through a JavaScript API called WebGL. It is not, however, an HTML5 standard and Microsoft has stated that they have no plans for Internet Explorer to support it for the foreseeable future. This means a potentially significant portion of the game's potential audience could suffer poor gameplay if particles are used. Additionally, even with WebGL enabled, the functionality for particles to have additive blending and advanced color blending cannot be used, as none of the browsers currently support this feature. Now that we know this we are ready to make some effects! Adding particle effects to the game We are going to build a few different particle effects to demonstrate the various ways effects can be implemented in a game, and to look into some of the issues that might arise. To keep things straightforward, all of the effects we create will be a part of a single, global particle system. We will use both types of emitters, and utilize both shape and sprite-based particles. We will start with a Dust Cloud that will be seen anytime a Pillar is broken or destroyed. We will then add a system to create a unique shrapnel effect for each Pillar type. Finally, we will create some fire and smoke effects for the TNT explosion to demonstrate moving emitters. Creating a Dust Cloud The first effect we are going to create is a simple Dust Cloud. It will burst outwards upon the destruction of each Pillar and dissolve away over time. As this effect will be used in every level of the game, we will make all of its elements global, so they only need to be declared once. Open the Tower Toppling project we were previously working on if it is not already open. We need to make sure that WebGL is enabled when we build the game. Navigate to Resources | Change Global Game Settings and click on the HTML5 tab. On the left-hand side, click on the tab for Graphics. As seen in the following screenshot, there are three options under WebGL in Options. If WebGL is Disabled, the game will not be able to use the GPU and all browsers will suffer from any potential lag. If WebGL is Required, any browser that does not have this capability will be prevented from running the game. The final option is Auto-Detect which will use WebGL if the browser supports it, but will allow all browsers to play the game no matter what. Select Auto-Detect and then click on OK. Image Now that we have WebGL activated we can build our effects. We will start by defining our particle system as a global variable by creating a new script called scr_Global_Particles. code The first effect we are going to make is the Dust Cloud which will be attached to the Pillars. For this we only need a single emitter which we will move to the appropriate position when it is needed. Create a global variable for the emitter and add it to the particle system with the following code at the end of the script: code For this particle, we are going to use one of the built-in shapes, pt_shape_explosion, which looks like a little thick cloud of dust. Add the following code to the end of the script: code Once again we have made this a global variable, so that we have to create this Dust Cloud particle only once. We have declared only the shape attribute of this particle at this time. We will add more to this later once we can see what the effect looks like in the game. We need to initialize the particle system with the other global variables. Reopen scr_Global_GameStart and call the particles script. code With everything initialized, we can now create a new script, scr_Particles_DustCloud, which we can use to set the region of the emitter and have it activate a burst of particles. code We start by defining a small area for the emitter based on the position of instance that calls this script. The region itself will be circular with a Gaussian distribution so that the particles shoot out from the center. We then activate a single burst of 10 dust particles from the emitter. All we need to do now is execute this script from the destruction of a Pillar. Reopen scr_Pillar_Destroyand insert the following line of code on the line before the instance is destroyed: code We need to add this effect to the breaking of the Pillars as well. Reopen scr_ Pillar_BreakApart and insert the same code in the same spot. Save the game and then play it. When the glass Pillars are destroyed, we should see thick white clouds appearing as shown in the following screenshot: Image The particles are boring and static at this point, because we have not told the particles to do anything other than to look like the shape of a cloud. Let's fix this by adding some attributes to the particle. Reopen scr_Global_Particles and add the following code at the end of the script: code The first attribute we add is how long we want the particle to live for, which is a range between 15 and 30 steps, or at the speed of our rooms, a half to a whole second. Next, we want the particles to explode outwards, so we set the angle and add some velocity. Both functions that we are using have similar parameters. The first value is the particle type for which this is to be applied. The next two parameters are the minimum and maximum values from which a number will be randomly chosen. The fourth parameter sets an incremental value every step. Finally, the last parameter is a wiggle value that will randomly be applied throughout the particle's lifetime. For the Dust Cloud, we are setting the direction to be in any angle and the speed is fairly slow, ranging only a few pixels per step. We also want to change the size of the particles and their transparency, so that the dust appears to dissipate. Save the game and run it again. This time the effect appears much more natural, with the clouds exploding outwards, growing slightly larger, and fading out. It should look something like the next screenshot. The Dust Cloud is now complete. Image Adding in Shrapnel The Dust Cloud effect helps the Pillar destruction appear more believable, but it lacks the bigger chunks of material one would expect to see. We want some Shrapnel of various shapes and sizes to explode outwards for each of the different types of Pillars. We will start with the Glass particles. Create a new Sprite, spr_Particle_Glass, and with Remove Background checked, load Chapter 8/Sprites/Particle_Glass.gif.mhanaje This sprite is not meant to be animated, though it does have several frames within it. Each frame represents a different shape of particle that will be randomly chosen when the particle is spawned. We will want the particles to rotate as they move outwards, so we need to center the origin. Click on OK. Reopen scr_Global_Particles and initialize the Glass particle at the end of the script. code Once we have created the global variable and the particle, we set the particle type to be a Sprite. When assigning Sprites there are a few extra parameters beyond which resources should be used. The third and fourth parameters are for whether it should be animated, and if so, should the animation stretch for the duration of the particle's life. In our case we are not using animation, so it has been set to false. The last parameter is for whether we want it to choose a random subimage of the Sprite, which is what we do want it to do. We also need to add some attributes to this particle for life and movement. Add the following code at the end of the script: code When compared with the Dust Cloud, this particle will have a shorter lifespan but will move at a much higher velocity. This will make this effect more intense while keeping the general area small. We have also added some rotational movement through part_type_orientation. The particles can be set to any angle and will rotate 20 degrees per frame with a variance of up to four degrees. This will give us a nice variety in the spin of each particle. There is one additional parameter for orientation, which is whether the angle should be relative to its movement. We have set it to false as we just want the particles to spin freely. To test this effect out, open up scr_Particles_DustCloud and insert a burst emitter before the Dust Cloud is emitted, so that the Glass particles appear behind the other effect. code Save the game and then play it. When the Pillars break apart, there should be shards of Glass exploding out along with the Dust Cloud. The effect should look something like the following screenshot: Image Next we need to create Shrapnel for the Wood and Steel particles. Create new Sprites for spr_Particle_Wood and spr_Particle_Steel with the supplied images in Chapter 8/Sprites/ in the same manner as we did for Glass. As these particles are global, we cannot just swap the Sprite out dynamically. We need to create new particles for each type. In scr_Global_Particles, add particles for both Wood and Steel with the same attributes as Glass. Currently the effect is set to Always create Glass particles, something we do not want to do. To fix this we are going to add a variable, myParticle, to each of the different Pillars to allow us to spawn the appropriate particle. Open scr_Pillar_Glass_Create and add the following code at the end of the script: code Repeat the last step for Wood and Steel with the appropriate particle assigned. In order to have the proper particle spawn, all we need to do is reopen scr_Particles_DustCloud and change the variable particle_Glass to myParticle as in the following code: code Save the game and play the game until you can destroy all the three types of Pillars to see the effect. It should look something similar to the following screenshot, where each Pillar spawns its own Shrapnel: Image Making the TNT explosion When the TNT explodes, it shoots out some TNT Fragments which are currently bland looking Sprites. We want the Fragments to be on fire as they streak across the scene. We also want a cloud of smoke to rise up from the explosion to indicate that the explosion we see is actually on fire. This is going to cause some complications. In order to make something appear to be on fire, it will need to change color, say from white to yellow to orange. As we have already mentioned, due to the fact that WebGL is not supported by all browsers, we cannot utilize any of the functions that allow us to blend colors together. This means that we need to work around this issue. The solution is to use several particles instead of one. We will start by creating some custom colors so that we can achieve the look of fire and smoke that we want. Open scr_Global_Colors and add the following colors: code We already have a nice yellow color, so we add an orange, a slightly yellow tinted white, and a partially orange black color. In order to achieve the fake blending effect we will need to spawn one particle type, and upon its death, have it spawn the next particle type. For this to work properly, we need to construct the creation of the particles in the opposite order that they will be seen. In this case, we need to start by building the smoke particle. In scr_Global_Particles add a new particle for the smoke with the following attributes: code We start by adding the particle and using the built-in smoke shape. We want the smoke to linger for a while, so we set its life to range between a minimum of a second to almost two full seconds. We then set the direction and speed to be more or less upwards so that the smoke rises. Next, we set the size and have it grow over time. With the alpha values, we don't want the smoke to be completely opaque, so we set it to start at half transparent and fade away over time. Next, we are using part_type_color1 which allows us to tint the particle without affecting the performance very much. Finally, we apply some gravity to the particles so that any angled particles float slowly upwards. The smoke is the final step of our effect and it will be spawned from an orange flame that precedes it. code Once again we set up the particle using the built-in smoke shape, this time with a much shorter lifespan. The general direction is still mainly upwards, though there is more spread than the smoke. These particles are slightly smaller, tinted orange and will be partially transparent for its entire life. We have added a little bit of upward gravity, as this particle is in between fire and smoke. Finally, we are using a function that will spawn a single particle of smoke upon the death of each orange particle. The next particle in the chain for this effect is a yellow particle. This time we are going to use the FLARE shape, which will give a better appearance of fire. It will also be a bit smaller, live slightly longer than the orange particle, and move faster, spreading in all directions. We will not add any transparency to this particle so that it appears to burn bright. code We have only one more particle to create this effect for, which is the hottest and brightest white particle. Its construction is the same as the yellow particle, except it is smaller and faster. code We now have all the particles we need for this particle effect; we just need to add an emitter to spawn them. This time we are going to use a stream emitter, so that the fire continuously flows out of each Fragment. Since the Fragments are moving, we will need to have a unique emitter for each Fragment we create. This means it cannot be a global emitter, but rather a local one. Open scr_TNT_Fragment_Create and add the following code at the end of the script: code We create an emitter with a fairly small area for spawning with balanced distribution. At every step, the emitter will create five new Fire particles as long as the emitter exists. The emitter is now created at the same time as the Fragment, but we need the emitter to move along with it. Open scr_TNT_Fragment_Step and add the following code: code As already mentioned we need to destroy the emitter, otherwise it will never stop streaming particles. For this we will need to open obj_TNT_Fragment and add a destroy event with a new Script, scr_TNT_Fragment_Destroy, which removes the emitter attached. code This function will remove the emitter from the system without removing any of the particles that had been spawned. One last thing we need to do is to uncheck the Visible checkbox, as we don't want to see the Fragment sprite, but just the particles. Save the game and detonate the TNT. Instead of just seeing a few Fragments, there are now streaks of fire jetting out of the explosion that turn into dark clouds of smoke that float up. It should look something like the following screenshot: Image Cleaning up the particles At this point, we have built a good variety of effects using various particles and emitters. The effects have added a lot of polish to the game, but there is a flaw with the particles. If the player decides to restart the room or go to the SHOP immediately after the explosion has occurred, the emitters will not be destroyed. This means that they will continue to spawn particles forever, and we will lose all references to those emitters. The game will end up looking like the following screenshot: Image The first thing we need to do is to destroy the emitters when we leave the room. Luckily, we have already written a script that does exactly this. Open obj_TNT_Fragment and add a Room End event and attach scr_TNT_Fragment_Destroy to it. Even if we destroy the emitters before changing rooms, any particles remaining in the game will still appear in the next room, if only briefly. What we need to do is clear all the particles from the system. While this might sound like it could be a lot of work, it is actually quite simple. As Overlord is in every level, but not in any other room, we can use it to clean up the scene. Open obj_Overlord, add a Room End event and attach a new Script, scr_Overlord_RoomEnd, with the following line of code: part_particles_clear(system); This function will remove any particle that exists within the system, but will not remove the particle type from memory. It is important that we do not destroy the particle type, as we would not be able to use a particle again if its type no longer exists. Save the game, explode some TNT, and restart the room immediately. You should no longer see any particles in the scene. Summary In this article, we were provided with the details to add some spit and polish to the game to really make it shine. We delved into the world of particles and created a variety of effects that add impact to the TNT and Pillar destruction. Resources for Article : Further resources on this subject: HTML5: Generic Containers [Article] HTML5 Presentations - creating our initial presentation [Article] Deploying HTML5 Applications with GNOME [Article]
Read more
  • 0
  • 0
  • 7866

article-image-article-working-windows-phone-controls
Packt
06 Jun 2013
14 min read
Save for later

Working with Windows Phone Controls

Packt
06 Jun 2013
14 min read
(For more resources related to this topic, see here.) Supported controls in Windows Phone The following list will illustrate the different controls supported in Windows Phone. These controls are included in the System.Windows.Controls namespace in the .NET Framework class library for Silverlight: Button: As the name goes, this is a button wherein a user interacts by clicking on it. On clicking, it raises an event. HyperlinkButton: This is a button control that displays a hyperlink. When clicked, it allows users to navigate to an external web page or content within the same application. ProgressBar: This is a control that indicates the progress of an operation. MessageBox: This is a control that is used to display a message to the user and optionally prompts for a response. TextBox: This is a control that allows users to enter single or multiple lines of text. Checkbox: This is a control that a user can select or clear, that is, the control can be checked or unchecked. ListBox: This is a control that contains a list of selectable items. PasswordBox: This is a control used for entering passwords. RadioButton: This is a control that allows users to select one option from a group of options. Slider: This is a control that allows users to select from a range of values by moving a thumb control along a track. Hello world in F# The previous section gave us an insight into different controls available for Windows Phone applications. Before understanding how to work with them, let's create a Windows Phone "Hello World" application using F#. The following steps will help us create the application: Create a new project of type F# and C# Windows Phone Application (Silverlight)A solution with App and AppHost projects will be created: Image In the App project, we will have the main visual for the application called MainPage.xaml. If you open MainPage.xaml, you will notice that MainPage is actually a PhoneApplicationPage type. This is evident from the following XAML declaration: code Note the x:Class attribute; this denotes that the XAML contains a counterpart class called MainPage available in the WindowsPhoneApp namespace. The MainPage class can be found in the AppLogic.fs file in the App project. Let us take a closer look at the UI itself. The main contents of the application is contained in a grid. A grid is a layout control that is used to define a flexible area that consists of rows and columns. The body contains three TextBlock controls. A TextBlock control, as the name suggests, is used to display a small block of text. We have three TextBlock controls on the page, one for ApplicationTitle, another for PageTitle, and the last one for Results. There is also an empty grid named ContentGrid. So this is where we will be creating our "Hello World" experiment. The XAML for the content is shown as follows: code As you can see from the code, ContentGrid is empty. So let's place a TextBlock control and a Button element inside ContentGrid. The idea is to generate the text "Hello World" when we click on the button. First, let's take a look at the XAML portion of the "Hello World" experiment in MainPage.xaml: code Pay attention to the TextBlock element and the Button names. We have the TextBlock control named as txtMessage and Button named as btnSayHelloButton. Now the second part of this experiment is to wire up the button's Click event with an event handler in the MainPage class. In the AppLogic.fs file, find the MainPage type and add the following code: code First we create a reference to the text block and the button. Then we add an event handler to the button's Click event. In F#, the way we add event handlers is by writing a function using the fun keyword. The _ (underscore) tells the F# compiler to ignore the parameters of the function and then we define the statement of a function. On button click, we just change the text of the text block to say "Hello World !". Well, that's all there is to this "Hello World" experiment. Notice the use of the ? operator. This is not F#-specific code. Rather, the project template creates a module in the AppLogic.fs file called Utilities. There, ? is defined as an operator that can be used for dynamic lookup of XAML object names for binding purposes. The code snippet of the operator is shown as follows: code Now let's build and run the project. Windows Phone Emulator will be invoked by Visual Studio to deploy the app we just built. You will see a text block with the text Click the button and a button with the text Click to Say Hello !. When the button is clicked, the text block will show the text Hello World !. The screenshots of the final output are shown as follows: Image Working with the Button control A button, as the name goes, is a rectangular control that allows a user to click on it, and when clicked, raises a Click event. We can write listeners for this Click event and add an event handler for the Click event. When the Click event occurs, the event handler will be notified and we can run our business logic against the button click—whatever logical thing we need. Let's see how to work with the button control. Create a project and add three buttons in the XAML code. For the first button, we will set its properties from the XAML itself. For the second button, we will set the properties from the code. For the third button we will set its properties in its Click event. The XAML code snippet is shown as follows: code For the second and third button, except for its Content attribute, nothing is set in XAML. The properties for the second button is set on the page load event in the MainPage class. The properties for the third button is set on the click of the third button in an event handler. Now let us see the F# code snippet for this in the MainPage class: code One thing to learn from here is—whatever properties can be set from XAML, the same can also be set from the code. The preceding demo shows how at page load and with event handlers, a control's properties can be changed at runtime. The screenshot of the final output is shown as follows: Image Working with the Checkbox control As mentioned earlier, Checkbox is a control that allows a user to select or clear an option. We can use a Checkbox control to provide a list of options that a user can select, for example a list of settings to apply in an application. The Checkbox control can have three states namely Checked, Unchecked, and Indeterminate. To demonstrate this control usage, let's build a demo that contains two checkboxes. The first checkbox demonstrates the Checked and Unchecked states. The second checkbox demonstrates the Checked, Unchecked, and Indeterminate states. We will handle the Checked event when checkboxes are checked, and the Unchecked event when checkboxes are unchecked. The XAML code snippet for this demo is shown as follows: code As you can see, we have two checkboxes stacked vertically one below the other. StackPanel is a layout control, which, as its name goes, just stacks its children content either vertically or horizontally. The second checkbox has a Boolean property named IsThreeState set to true. That means this checkbox will have three states – Checked, Unchecked, and Indeterminate. Checkboxes expose Checked, Unchecked, and Indeterminate events. We will wire up event handlers for these events and write out a message to the txtMessage text block as seen in the code snippet. The following is the code snippet where we handle the events: code We first get a reference to the checkbox controls. Then we wire up the Checked and Unchecked events. For the second checkbox, since it supports the Indeterminate state, we wire up the Indeterminate event too. When you run the app and select or clear any checkbox, a message will be shown in the text block. The screenshot of the output is shown as follows: Image Working with the Hyperlink control Hyperlink is a control that presents a button control with a hyperlink. When the hyperlink is clicked, it will navigate to the URI specified, which can be an external web page or content within the app. We specify the URI to navigate through the NavigateUri property. The XAML code snippet for this control is shown as follows: code The same effect can be obtained using code. On page load, we would have to just set the NavigateUri property, and when the user clicks on the hyperlink button, he will be navigated to the set URI. Working with the ListBox control A ListBox control represents a list of selectable items. It basically displays a collection of items. More than one item in a ListBox control is visible at a time. As part of the demo app, we will create a listbox and fill it with available color names. When an item is selected in the listbox, we will set the background of the listbox to the selected item. The XAML code snippet is shown as follows: code The code to fill up the listbox with the names of the colors along with the event handler to handle the listbox's SelectionChanged event is shown as follows: code For filling up the listbox with color names, we iterate through the public properties of the System.Windows.Media.Colors class. The Colors class implements a different set of predefined colors. We fill the listbox with the names of the predefined colors by adding them to the Items collection of the listbox. To handle item selection change, we handle the SelectionChanged event. First, we get the SelectedItem property, and since we know it's a string in our case, we convert it into a string. Then we get the Color property by making use of the string that we converted from SelectedItem. Once we get the color, we set the background of the listbox to the color selected. The final output of this demo is shown as follows: Image Working with the MessageBox control In this section we will take a look at the MessageBox control. This control displays a message to the user and optionally prompts for a response. The MessageBox class provides a static Show method, which can be used to display the message in a simple dialog box. The dialog box is modal and provides an OK button. A code to work with the MessageBox control is shown next. Note that this can be worked with only from the code and not from the XAML. First, we show a message box with the ok and cancel button. When a user clicks on the ok button, we show a simple message box with just the ok button. code The final output of this demo is shown as follows: Image Working with the PasswordBox control PasswordBox, as the name suggests, is used to enter a password in applications. The user cannot view the entered text; only password characters that represent the text are displayed. The password character to be displayed can be specified by using the property PassowrdChar. Add PasswordBox, Button, and TextBlock in the XAML code. The idea is to enter some text in the PasswordBox control, and on clicking the button show the password text in the text block. The XAML for this demo is shown as follows: code The code to handle the button click and display the password entered in the text block is shown as follows: code The password box contains a property called Password, which can be used to read the entered password. The final output of the demo is shown as follows: Image Working with the ProgressBar control The ProgressBar control is used to display the progress of an operation. This is often used in UI layouts to indicate a long running operation. One of the requirements of the Windows Phone app is to include a progress bar and show a progress animation whenever a task is a long-running task in any application. The progress bar can have a range between Minimum and Maximum values. It also has an IsIndeterminate property, which means no Minimum and Maximum value is set and the progress bar displays a repeating pattern. This is predominantly used in XAML and its visibility is controlled by the code. The XAML code snippet is shown as follows: code Working with the RadioButton control RadioButton is a control, which represents a button that allows a user to select a single option from a group of options. A RadioButton control is usually used as one item in a group of RadioButton controls. RadioButtons can be grouped by setting their GroupName property. To group radio buttons, the GroupName property on each of the radio button should have the same value. RadioButtons contain two states, namely selected or cleared. RadioButtons have the IsSelected property, which will let us know if a radio button is selected or not. Create three radio buttons in XAML. Two of them will be grouped and one will be ungrouped. We will listen for the Checked event on the radio buttons and update a text block with the appropriate message. The XAML code snippet is shown as follows: code As you can see, the first two radio buttons have their GroupName property set whereas the last radio button does not have any GroupName set. We will wire up the Checked event on all three radio buttons and update the text block with information such as which radio button was clicked. The code snippet is shown as follows: code The output from this demo is shown as follows: Image Working with the Slider control The Slider control represents a control that lets users select from a range of values by moving a thumb control along a track. The Slider control exposes certain properties that can be set to customize the functioning of the slider. We can set the Orientation property to orient the slider either horizontally or vertically. We can change the direction of the increasing value with IsDirectionReversed. The range of values can be set using the Minimum and Maximum properties. The value property can be used to set the current position of the slider. Add a Slider control to the XAML. Set its Minimum to 0 and Maximum to 10. When the user changes the position of the thumb on the slider, we will listen to the ValueChanged event on the slider and show the current value in a text block. The XAML snippet for the slider is shown as follows: code As you can see, we set the Minimum and Maximum range in the XAML. From the code, we wire up the ValueChanged event. Whenever a user changes the value using the thumb on the slider, the ValueChanged event will be fired and we just read the current value of the slider and update a text block. The final output of this demo is shown as follows: Image Working with the TextBox control The TextBox control can be used to display single or multiline text. It is often used to accept user input in applications. This control is one of the most widely used controls for data input. On a Windows Phone, whenever a textbox gets focus, an on-screen keyboard known as Software Input Panel (SIP) will be shown automatically by the Windows Phone OS. If we do not want the user to edit the text, we can set the IsReadOnly property on the textbox to true. This will prevent the user from typing anything in the textbox. We can read the value entered in a textbox using the i property. The XAML snippet for a simple textbox is shown as follows: code A screenshot of a simple textbox with SIP displayed when the textbox gets focus is shown as follows: Image Summary In this article, we took a lap around the supported controls for the Silverlight runtime on the Windows Phone platform. We looked at the XAML way of defining the controls and also how to programmatically work with these controls in the code. We learnt what properties each control exposes and how to wire up events supported by each control. Resources for Article : Further resources on this subject: Deploying .NET-based Applications on to Microsoft Windows CE Enabled Smart Devices [Article] Development of iPhone Applications [Article] Getting Started with Internet Explorer Mobile [Article]
Read more
  • 0
  • 0
  • 2079
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime
article-image-article-nesting-extend-placeholders-and-mixins
Packt
05 Jun 2013
9 min read
Save for later

Nesting, Extend, Placeholders, and Mixins

Packt
05 Jun 2013
9 min read
(For more resources related to this topic, see here.) Styling a site with Sass and Compass Personally, while abstract examples are fine, I find it difficult to fully understand concepts until I put them into practice. With that in mind, at this point I'm going to amend the markup in our project's index.html file, so we have some markup to flex our growing Sass and Compass muscles on. We're going to build up a basic home page for this book. Hopefully, the basic layout and structure will be common enough to be of help. If you want to see how things turn out, you can point your browser at http://sassandcompass.com, as that's what we'll be building. The markup for the home page is fairly simple. It consists of a header with links, navigation made up of list items, images, and content and a footer area. Pasting the home page markup here will span a few pages (and be extremely dull to read. Don't get too hung up on the specifics of the markup. Let me be clear. The actual code, selectors used, and the finished webpage that we'll create are not important. The Sass and Compass techniques and tools we use to create them are. You can download the code from the book's page at http://packtpub.com and also from http://sassandcompass.com You can download the code from the book's page at http:// packtpub.com and also from http://sassandcompass.com At this point, here's how the page looks in the browser: Image Wow, what a looker! Thankfully, with Sass and Compass we're going to knock this into shape in no time at all. Notice that in the source code there are semantically named classes in the markup. Some people dislike this practice, but I have found that it makes it easier to create more modular and maintainable code. A full discussion on the reasoning behind using classes against styling elements themselves is a little beyond the scope of this book. However, a good book on this topic is SMACSS by Jonathan Snook (http:// smacss.com). It's not essential to adhere slavishly to the conventions he describes, but it's a great start in thinking about how to structure and write style sheets in general. First, let's open the _normalize.scss partial file and amend the default styles for links (changing the default text-underline to a dotted bottom border) and remove the padding and margin for the ul tags. Now I think about this, before we get knee-deep in code, a little more organization is called for. Separating the layout from visuals Before getting into nesting, @extend, placeholders, and mixins, it makes sense to create some partial files for organizing the styles. Rather than create a partial Sass file for each structural area (the header, footer, and navigation), and lump all the visual styles relevant inside, we can structure the code in a slightly more abstract manner. There is no right or wrong way to split up Sass files. However, it's worth looking at mature and respected projects such as Twitter Bootstrap (https://github.com/twitter/ bootstrap) and Foundation from Zurb (https://github.com/zurb/foundation) to see how they organize their code. We'll create a partial file called _base.scss that will contain some base styles: code Then a partial file called _layout.scss. That will only contain rules pertaining to visual layout and positioning of the main page areas (the previously mentioned header, footer, aside, section, and navigation). Here are the initial styles being added into the _layout.scss partial file: code There is nothing particular to Sass there, it's all standard CSS. Debug help in the browser Thanks to the popularity of Sass there are now experimental features in browsers to make debugging Sass even easier. When inspecting an element with developer tools, the source file and line number is provided, making it easier to find the offending selector. For Chrome, here's a step-by-step explanation: http://benfra.in/1z1 Alternatively, if using Firefox, check out the FireSass extension: https://addons.mozilla.org/en-us/firefox/addon/ firesass-for-firebug/ Let's create another partial file called _modules.scss. This will contain all the modular pieces of code. This means, should we need to move the .testimonial section (which should be a modular section) in the source code, it's not necessary to move it from one partial file to another (which would be the case if the partial files were named according to their existing layout). The _module.scss file will probably end up being the largest file in the Sass project, as it will contain all the aesthetics for the items on the page. However, the hope is that these modular pieces of code will be flexible enough to look good, regardless of the structural constraints defined in the _layout.scss partial file. If working on a very large project, it may be worth splitting the modules into sub-folders. Just create a sub-folder and import the file. For example, if there was a partial called _callouts.scss in a sub-folder called modules, it could be imported using the following code: code Here is the contents of the amended styles.scss file: code A quick look at the HTML in the browser shows the basic layout styles applied: Image With that done, let's look at how Sass's ability to nest styles can help us make modules of code. What nesting is and how it facilitates modules of code Nesting provides the ability to nest styles within one another. This provides a handy way to write mini blocks of modular code. Nesting syntax With a normal CSS style declaration, there is a selector, then an opening curly brace, and then any number of property and value pairs, followed by a closing curly brace. For example: code Where Sass differs is that before the closing curly brace, you can nest another rule within. What do I mean by that? Consider this example: code In the previous code, a color has been set for the link tag using a variable. Then the hover and focus state have been nested within the main anchor style with a different color set. Furthermore, styles for the visited and active state have been nested with an alternate color defined. To reference a variable, simply write the dollar sign ( $) and then the name of the variable, for example, $variable. When compiled, this produces the following CSS: code Notice that Sass is also smart enough to know that the hex value #7FFF00 is actually the color called chartreuse, and when it has generated the CSS it has converted it to the CSS color name. How can this be used practically? Let's look at the markup for the list of navigation links on the home page. Each currently looks like this: code I've omitted the additional list items and closing tags in the previous code for the sake of brevity. From a structure point of view, each list item contains an anchor link with a <b> tag and a <span> tag within. Here's the initial Sass nested styles that have been added into the _modules.scss partial to control that section: code Notice that the rules are being nested inside the class .chapter-summary. That's because it then limits the scope of the nested styles to only apply to elements within a list item with a class of .chapter-summary. However, remember that if the styles can be re-used elsewhere, it isn't necessarily the best practice to nest them, as they may become too specific. The nesting of the selectors in this manner partially mirrors the structure of the HTML, so it's easy to see that the styles nested within only apply to those that are similarly structured in the markup. We're starting with the outermost element that needs to be styled (the <li class=”chapter-summary”>) and then nesting the first element within that. In this instance, it's the anchor tag. Then further styles have been nested for the hover and visited states along with the <b> and <span> tags. I tend to add focus and active states at the end of a project, but that's a personal thing. If you're likely to forget them, by all means add them at the same time you add hover. Here's the generated CSS from that block: code The nested styles are generated with a degree of specificity that limits their scope; they will only apply to elements within a <li class=”chapter-summary”>. It's possible to nest all manner of styles within one another. Classes, IDs, pseudo classes; Sass doesn't much care. For example, let's suppose the <li> elements need to have a dotted border, except for the last one. Let's take advantage of the last-child CSS pseudo class in combination with nesting and add this section: code The parent selector Notice that any pseudo selector that needs to be nested in Sass is prefixed with the ampersand symbol (&), then a colon (:). The ampersand symbol has a special meaning when nesting. It always references the parent selector. It's perfect for defining pseudo classes as it effectively says 'the parent plus this pseudo element'. However, there are other ways it can work too, for example, nesting a few related selectors and expressing different relationships between them: code This actually results in the following CSS: code We have effectively reversed the selectors while nesting by using the & parent selector. Chaining selectors It's also possible to create chained selectors using the parent selector. Consider this: code That will compile to this: code That will only select an element that has both HTML classes, namely selector-one and selector-two. The parent selector is perfect for pseudo selectors and at odd times its necessary to chain selectors, but beyond that I couldn't find much practical use for it, until I saw this set of slides by Sass guru Brandon Mathis http://speakerdeck.com/u/imathis/p/sass-compass-the-future-of-stylesheets-now. In this, he illustrates how to use the parent selector for nesting a Modernizr relevant rule.
Read more
  • 0
  • 0
  • 4736

article-image-innovation-communication-and-information-technologies
Packt
05 Jun 2013
12 min read
Save for later

Innovation of Communication and Information Technologies

Packt
05 Jun 2013
12 min read
(For more resources related to this topic, see here.) Communication is not something which we consciously think about in most situations. However, let me urge you to start observing how often you communicate daily with others and particularly the ways and means you do this. I think you can then agree that communication and targeted exchange of information are basic components and a foundation of our lives. Living creatures communicate with one another via some form of tool or other means. In the prehistoric era, humankind communicated information using images, characters, sounds, and later music from the sender to the receiver. However, the uniqueness of this information was not always clearly given and messages communicated by this means did not always reach the intended recipient. Looking into the past, the origin of cooperation was to create success, whether in career opportunities or social recognition to secure survival for his fellow men and himself. In the course of time and history, many possibilities derived from technical-evolutionary ideas have been developed for communication, cooperation, and exchange of information over many centuries. Ultimately it is the human drive to be successful and efficient in communicating, processing, and transmitting information that drives this process. Let us look back at the technological developments that have taken place at the end of the nineteenth century and the beginning of the twentieth century. At that time, our "modern" information exchange and communication by telegraphy (1837, Samuel Morse F. B.) or telephony (1876, Alexander Graham Bell) were in their infant stages. Telephones were innovative pieces of equipment that had to be integrated into companies or offices in order to process information more efficiently and rapidly without having to go through an interconnecting party. These developments were tools of communication which eventually seeded the development of today's modern communication— an integrated solution for communication and collaboration, in short, unified communications/unified messaging. Defining communication A communication tool is not simply a tool for communication but it supports us in our everyday life and it is also a "tool" in our professional dealings at work, to give us information and knowledge to help us make more informed decisions better and faster. This technological advancement affects not only our individual lives but also structures in which companies and even the global economy cooperate and collaborate. Communicating relevant, mission-critical information is an indispensable task in today's work environment as well as in our private lives. Success is in part based on how much knowledge we have, which itself ultimately depends on how we communicate and how fast we process information. In the past few decades, for both our professional and private lives, we communicated using media such as paper and pen, typewriter, and the phone. In the business environment, the use of paper to communicate with companies outside caused vast quantities of paper to be transported over long routes, which resulted in long waiting times and inefficient flow of information. Introduction of the early phone system helped to greatly increase efficiency but was subject to the limited availability of the intermediate connector to the other party and allowed only audio data to be transferred. The inability to transfer other forms of data such as documents, screenshots, or other contextual information is a limitation when you are only able to communicate by audio. This, however, does not mean that individuals or companies in the past were inefficient and unsuccessful because they were unable to communicate the way we are doing today. Being "successful" is a temporary condition, which once reached, does not automatically continue for a team or an individual. Success is the result of a consistent investment in the uniqueness of the company or of the individual, the use of performance-relevant core competencies, and the ability to learn faster than others and to change in a broader sense. The right strategies, visions, mission statements, organizational structures, competent managers, and especially employees are important for success. But correct and relevant information to make sound and informed decisions helps the organization to be continually successful. Thus, the critical role is to look into ways employees, departments, offices, and business partners communicate and collaborate with one another. Fundamentally, basic communication, as you can imagine, is the basis for all these forms of modern communication and collaboration to take place. In order to better understand current and future possibilities for communication and collaboration let me first take you back once again to the past. What changed the communication industry? In the past few decades, a technical change took place due to the changing conditions and requirements of information processing with the need to communicate and collaborate in our global economy. In addition to globalization, an important benefit for business was also created by countless technical developments. For example, the invention of the Internet was considered one of the biggest changes in the information community since the invention of the printing press. The initial networking of universities and research institutes which later spread into the commercial sector, and eventually to the private sector, had an unexpected impact on various areas of everyday life. In 1990, the Internet was given virtually free by the US National Science Foundation to the world as a communication network for various technology companies, research institutes, and universities to develop. The following diagram illustrates the development of telecommunication since the mid-eighteenth century and the innovations that were invented with software-based technology. In other words, traditional telecommunication- and software-based communication and collaboration technologies are coming closer together, merging and building a strong convergence for the future. Technological development of the Internet also created changing conditions in the market economy. Initially, these new possibilities on the part of many companies were more or less declared as "utopia" or only short-term achievement. The initial technology was available but insufficient to provide a real benefit for companies. However, in 1993, through the development of new communication protocols by Tim Berners-Lee (who is considered the inventor of the World Wide Web and the HTTP protocol) and CERN, there was a rapid boost of the Internet by increasing the efficient exchange of information. E-mail as a carrier of information in business and for private users was usable with these extensions and innovations of the Internet. On closer inspection, the exchange of information via e-mail probably created the first milestone for trends such as the "paperless office", to create savings in shipping and telephone costs. Understanding modern business communication needs Today, e-mail is not a trend but an established type of communication that is deeply integrated with our communication and business processes. Although "paperless office" and telephone cost savings using this technology have been realized, communication in companies significantly increased because you spend less time and less cost to transport information from point A to point B. What is the relationship between technologies, such as the Internet, e-mail, and the phone and the information processing and collaboration for businesses? The very same question is asked; how can we make cooperation within and outside companies more efficient? How can we communicate easier and quicker? Can companies achieve their goals more easily with these tools? Are there ways to avoid/reduce costs to increase savings? Can we make it easier to deal with this knowledge change? What potential gains and advantages exist here for the companies? What kind of changes will we need in the company and how will the changes affect the person who has to implement them? How can in-house projects be realized in order to improve the communication? To answer these questions, it is important to look at the communication trends in recent years. In the past five to ten years, with combined usage of previously developed and established milestones in communication technology, the Internet and the telephone, we were able to benefit from efficient client information while constantly developing communication technology. Wi-Fi, which has only existed for several years as a standard in companies and in public places such as airports, cafes, and so on, is now used by nearly all mobile communications devices. Wi-Fi allows us to communicate with words and images wirelessly to the Internet/local area network. Computer Telephony Integration (CTI), fax, and voicemail are some of the basic terms that play a special role in cooperation and information processing. The fact that almost every workplace has an Internet connection these days shows the need to simplify all communication possibilities for all users. This includes the Internet, e-mail, landline phones, mobile phones, video conferencing equipment, tablets, PCs, netbooks, and smartphones. It is important to highlight that connectivity to the Internet and telecommunication services is still a challenge in some areas of the world and even a luxury for some developed countries and regions. Even in these developed places we will find some remote locations with limited (slow) Internet connections. More often than not, new software promising better benefits in communication and cooperation tends to overwhelm employees in the company. Year after year, companies have invested over and over again in new technologies trying to get a competitive edge over other companies, by improving their internal processes and procedures through more efficient communication methods or technologies. In the past few years, the number and complexity of technologies and processes has escalated so much that these developments and investments are showing signs of having a negative impact on the efficiency and effectiveness of the company. Also, many business owners believed that pure investment in new tools, new software programs, and new communication equipment is the sole solution for better structural communication. This circumstance is still one of the top challenges and problems for IT and change processes in organizations. Since the 1990s, according to international studies (such as the Federal Reserve Board of Governors) a large percentage of the available budget is used for communications and information technologies. The chart shows that companies are continuously upgrading and investing in their technology. Even though the study begun in the last century, it is a fact that this same development has progressed to today. Through the investments made, it is obvious that IT investments are an above-average priority for many companies. The dotted line "Actual real IT investment" shows the IT investments realized in the North American region, the solid line "Target real IT investment" shows, on the other hand, the "target" IT investment is based on financial planning and forecasting of organizations. In the other chapters of this book, we will specifically focus on the "pure" IT investments (which are the actual IT investments). Through more expensive investments in information and communication technology, we will be able to see clearly that we need more than a wealth of different complex technologies to communicate and collaborate amongst employees, customers, partner companies, and so on. Precisely for this reason, software and technology companies that were developed a few years ago started implementing solutions in this field of communications so that technology "should unify the main day-to-day communication tools". Evolution of communication tools The old wired phone of the past has evolved over the years to include more uses and functionalities, and has been transformed into today's phone, which is effectively a mobile communication link. A telephone using its own PBX (Private Branch Exchange = Telephony system) in the company is very different from a modern mobile phone with the integrated mobile phone operator services. Global companies led the integration of different technologies to improve communication. Internal studies and analyses that were conducted showed that the average employee uses many devices such as a PC, a work phone (landline), possibly several mobile phones, a tablet, a fax, a notebook, and/or a Netbook. Perhaps you can still remember the "Pager", which was expensive when released but has long since been replaced by innovations from the mobile industry (excluding a few regions and certain professional areas such as the hospitals that are still using pagers for urgent communication). Of course, such studies on consumer communication are not solely used to find out the number of devices per user, but other important data such as the frequency and intensity of usage on the various devices so that companies can invest in the appropriate technology and the staff to facilitate communication and collaboration with others. Such studies revealed high costs for the workplace equipment and loss of efficiency was caused by an overlap and a "flood" of technologies. Due to this confusion of numerous devices and their associated communication chaos, many companies have invested increasingly in the so-called unified messaging solutions. The focus of such solutions is to provide individual employees a standardized tool to carry out their job functions more efficiently. This represents a portion of unified messaging known as CTI, as mentioned earlier. CTI solutions are a specialized kind of software which is used for the integration of workplace phones into workstation software solutions such as Microsoft Office and Exchange, Lotus Notes, Novell GroupWise, or others. A use case scenario could be a PC with Microsoft Outlook installed, where an information worker can click to call from an e-mail or from the address book and also use basic CTI features such as to put the call into a conference call, put a call on hold, or forward and hang up a call. The goal of unified messaging solutions is to take the load of the various complex technologies away so that we could communicate rapidly and efficiently manage human resources within the business. CTI-solutions linked to telecommunications with the electronic data processing allows functionalities such as adoption, termination, and the automatic dial-up telephone calls from a personal computer (PC) to be possible. Fax and voicemail are also part of unified messaging. Electronic fax can be dispatched and received from any workstation. Voicemails can take and playback voice messages using unified messaging applications. By using these solutions there is not only comprehensive efficiency but also cost saving without investing in more new telephone systems, add-ons (plugins), proprietary software, fax machines, telephones, and more. However, the integration solved the problems of unified messaging applications and technologies only partially because there are more and more new communication possibilities existing within the company, on the Internet with additional phone numbers, e-mail addresses, and various web communication options.
Read more
  • 0
  • 0
  • 19356

article-image-using-hive-non-interactively-simple
Packt
05 Jun 2013
5 min read
Save for later

Using Hive non-interactively (Simple)

Packt
05 Jun 2013
5 min read
(For more resources related to this topic, see here.) Getting ready Here are the initial steps to be followed: Create the init.hql file in the current directory. This file sets up the database, specifies our Hive settings, and creates our input table. create database if not exists ch3 ; use ch3 ; set hive.exec.mode.local.auto=true ; create table if not exists athlete( name string, id string, demonstration_events_competed_in array<string>, demonstration_medals_won array<string>, country array<string>, medals_won array<string>) row format delimited fields terminated by 't' collection items terminated by ',' ; load data local inpath 'data/olympic_athlete.tsv' overwrite into table athlete ; Create the script.hql in the current directory. This file creates our output table and executes a query. create table if not exists top_athletes( name string, num_medals int) ; insert overwrite table top_athletes select name, size(medals_won) as num_medals from athlete where size(medals_won) >= ${threshold} order by num_medals desc, name asc ; How to do it... Follow these steps to complete the task: We start by running our initialization and query scripts from the command line: $ hive -v --hivevar threshold=10 -i init.hql -f script.hql We write the header of our top_athletes table to a file using the standard cut and paste Unix tools $ hive -S -e "use ch4; describe top_athletes;" | cut -f 1 | paste -s - > output.tsv We write the data from the top_athletes table to our output file by executing explicit SQL statements: $ hive -S -e "use ch4; select * from top_athletes ;" >> output.tsv We can verify the contents of our file by simply using the cat command: $ cat output.tsv name num_medals Michael Phelps 22 Larissa Latynina 14 Jenny Thompson 12 Nikolai Andrianov 12 Matt Biondi 11 Ole Einar Bjørndalen 11 Ryan Lochte 11 Boris Shakhlin 10 Takashi Ono 10 How it works... From the command line, Hive supports three mutually exclusive modes. In addition to the interactive mode, we can pass commands to Hive using two different flags. Flag Argument Effect -f filename Execute the contents of the file -e SQL statements Execute the argument as input (none) (none) Run Hive interactively For all three of these cases, Hive allows using the -i filename parameter for passing an initialization script. This script will be executed first, then the session will continue with the file contents, explicit statements, or interactive session. Hive supports using the -i flag multiple times, so we can make our initialization scripts even more reusable by splitting them according to their functionality. For example, we could have one initialization script with common settings used by all jobs running on a particular cluster and a second initialization script for all jobs that use particular table definitions. In this example, we first use our two files to create the input and output tables and run a query. By using interactive scripts, we can separate the context of our query (the database, data loading, and Hive configuration) from the logic and output. Different processes can share the same context without needing to duplicate the contents of the initialization file across all of their scripts. We also make our script.sql file reusable with different thresholds through variable substitution. Hive will automatically replace any occurrences of ${variable} with the values passed to the hive command via the --hivevar parameter. The -d and --define parameters are synonyms for --hivevar, and all of these parameters may be specified multiple times if necessary. The -v flag simply puts Hive into verbose mode, so each statement is echoed to the console as it is executed. Combining the verbose flag, variable substitution, and our scripts gives us the first shell command we executed: $ hive-v --hivevar threshold=10 -iinit.hql -f script.hql We then execute two explicit commands, first to describe the columns of the top_athletes table, and then to output its contents. These are redirected to our output file on the local filesystem. The -S flag puts Hive into silent mode, so only the output of our queries will be written to the files. This helps us capture only the table contents to our output file. $ hive -S -e "use ch3; describe top_athletes;" | cut -f 1 | paste -s - > output.tsv $ hive -S -e "use ch3; select * from top_athletes ;" >> output.tsv In Hive Versions 0.10.0 and later, we can use the -database ch3 flag instead of specifying use ch3; as part of the query. Alternatively, we could refer to the table by its full name ch3. top_athletes. Summary In this recipe, we learned how Hive supports uses cases, such as periodic ETL jobs, by rerunning the top athletes query in batch mode from the command line. Resources for Article : Further resources on this subject: Design with Spring AOP [Article] HBase Administration, Performance Tuning [Article] Apache Cassandra: Libraries and Applications [Article]
Read more
  • 0
  • 0
  • 1483

Packt
04 Jun 2013
5 min read
Save for later

Quick start – Monitoring hosts and services

Packt
04 Jun 2013
5 min read
(For more resources related to this topic, see here.) Step 1 – Modifying nagios.cfg Nagios knows which configuration files to parse by maintaining a master reference in the nagios.cfg file. For any new configuration file to be recognized by Nagios, either the file or the directory it is in has to be defined in nagios.cfg. For source installations, this file is located at /usr/local/nagios/etc/nagios.cfg. Perform the following steps to modify nagios.cfg: Start by creating two new directories to store our configuration files: cd /usr/local/nagios/etc/objectsmkdir hostsmkdir services Then open nagios.cfg with your preferred text editor to add the new directories: # You can specify individual object config files as shown below:cfg_file=/usr/local/nagios/etc/objects/commands.cfgcfg_file=/usr/local/nagios/etc/objects/contacts.cfgcfg_file=/usr/local/nagios/etc/objects/timeperiods.cfgcfg_file=/usr/local/nagios/etc/objects/templates.cfg# Definitions for monitoring the local (Linux) hostcfg_file=/usr/local/nagios/etc/objects/localhost.cfg Add the following lines to allow all files in our hosts and services directories to be automatically added to the monitoring configuration: cfg_dir=/usr/local/nagios/etc/objects/hostscfg_dir=/usr/local/nagios/etc/objects/services Save the file and close it, it's time to add our first new host! Step 2 – Adding a host A host in Nagios is any machine or device with an IP address or a host name. The following example will demonstrate the creation of a basic host configuration file that we can add to the monitoring configuration: Create a new file at /usr/local/nagios/etc/objects/hosts called test.cfg, and open it in a text editor: define host{host_name testalias testaddress 127.0.0.1use linux-server} There are many more configuration directives that can be specified for a host, but as a best practice, it's best to specify as many of these values in a template as possible. Save the file and close it. You just added your first new host! Step 3 – Adding a service Services in Nagios are processes, applications, metrics, and anything else that can be monitored under the scope of the associated host. The following example creates a basic service definition for the test used, and will be used to start monitoring with a simple HTTP check: Service configurations are created in much the same way that hosts are. Create a new file named test.cfg, at /usr/local/nagios/etc/objects/services, and open it in a text editor: define service{host_name testservice_description HTTPcheck_command check_httpuse generic-service} Services can be applied to a single host, a list of hosts, or even an entire host group, and check_command specified for each of them can be customized to take custom arguments as well. However, for the moment, let's start things simple and keep moving forward. Save the file and close it. Step 4 – Creating and assigning contacts Alerting is an essential part of monitoring infrastructure with Nagios, but it is recommended to minimize or even disable the use of alerts while setting up your monitoring environment. Users who receive too many false alerts will be trained to ignore them. Setting up effective alerting starts with creating appropriate contacts and contact groups for the hosts and services that are being monitored. Contacts also form the basis for host and service permissions in Nagios. A regular-level user in Nagios will only be able to view and submit commands for hosts and services that they are contacts for, unless he/she is granted some level of global access in the cgi.cfg file. The following are the steps to create and assign contacts: Open /usr/local/nagios/etc/objects/contacts.cfg in your preferred text editor. By default, the nagiosadmin contact is already created for you. This account should typically be reserved for the top-level Nagios administrator. For other users, new contacts should be created. Add a new contact definition with your preferred username and e-mail address. define contact{contact_name testuse generic-contactalias Test Useremail test@example.com} Let's also add this contact to the admins contact group, which already exists in the same file: define contactgroup{contactgroup_name adminsalias Nagios Administratorsmembers nagiosadmin,test} Save the file and close it. In order to allow the access of the web interface to the new contacts, they need to be added to the htpasswd.users file using the following command: htpasswd -c /usr/local/nagios/etc/htpasswd.users test Step 5 – Verifying configuration and restarting Nagios All monitoring and event handling is done based on rules defined in the object configuration files, so the monitoring process requires a valid configuration in order to run. Always verify any configuration changes before attempting to restart Nagios, using the following steps. Attempting to restart Nagios with configuration errors will halt all the monitoring on the system. Nagios configurations can be verified on any installation, by running the Nagios binary file with the -v flag, followed by the main nagios.cfg file. On a source installation, this command can be run as follows: /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg If all goes well, you'll see the following message verifying that there are no configuration errors and that Nagios is ready to be restarted: Total Warnings: 0Total Errors: 0 Things look okay. No serious problems were detected during the pre-flight check. Once configuration verification succeeds, Nagios can be restarted with the following command: /etc/init.d/nagios restart Access the web interface to see the new host and service in Nagios! Summary In this article, we saw how to monitor hosts and services using a step-by-step approach. These four steps give an easy way to achieve our goal. Resources for Article : Further resources on this subject: Monitoring CUPS- part2 [Article] Troubleshooting Nagios 3.0 [Article] Notifications and Events in Nagios 3.0- part2 [Article]
Read more
  • 0
  • 0
  • 11417
article-image-article-top-features-you-need-know-about
Packt
03 Jun 2013
3 min read
Save for later

Top features you need to know about

Packt
03 Jun 2013
3 min read
(For more resources related to this topic, see here.) 1 – Minimap The minimap is an innovative feature of Sublime Text 2 that gives you a bird's-eye view of the document you are editing. Always present at the right-hand side of the editor, it allows you to quickly look at a live, updated, zoomed out version of your current document. While the text will rarely be distinguishable, it allows for a topographical view of your document structure. Image The minimap feature is also very useful for navigating a large document as it can behave similar to a scroll bar. When clicked on, the minimap can be used to scroll the document to a different portion. However, should you find yourself not needing the minimap, or need the screen real estate it inhabits, it can easily be hidden by using the Menu bar to select View | Hide Minimap. 2 – Multiple cursors Another way Sublime Text 2 differentiates itself from the crowded text editor market is by way of including the functionality that allows the user to edit a document in multiple places at the same time. This can be very useful when making an identical change in multiple places. It is especially useful when the change that needs to occur cannot be easily accomplished with find and replace. By pressing command + left-click on OS X, or Ctrl + left-click on other platforms, an additional cursor will be placed at the location of the click. Each additional cursor will mirror the original cursor. The following screenshot shows a demo of this functionality. First, I created cursors on each of my three lines of text. Then I proceeded to type test without quotes: Image Now, as shown in the following screenshot, anything typed will be typed identically on the three lines where the cursors are placed. In this case I typed a space followed by the word test. This addition was simultaneous and I only had to make the change once, after creating the additional cursors. Image To return to a single cursor, simply press Esc or left-click anywhere on the document. Summary This article covered a few few features of Sublime Text 2 including multiple cursors, a plugin system, and a few others which will be covered in this article. Resources for Article : Further resources on this subject: Building a Flex Type-Ahead Text Input [Article] Introduction to Data Binding [Article] Working with Binding data and UI elements in Silverlight 4 [Article]
Read more
  • 0
  • 0
  • 2205

article-image-creating-our-first-game
Packt
31 May 2013
11 min read
Save for later

Creating Our First Game

Packt
31 May 2013
11 min read
(For more resources related to this topic, see here.) Let's get serious – the game The game we will implement now is inspired by Frogger. In this old school arcade game, you played the role of a frog trying to cross the screen by jumping on logs and avoiding cars. In our version, the player is a developer who has to cross the network cable by jumping packets and then cross the browser "road" by avoiding bugs. To sum up, the game specifications are as follows: If the player presses the up arrow key once, the "frog" will go forward one step. By pressing the right and left arrow key, the player can move horizontally. In the first part (the network cable) the player has to jump on packets coming from the left of the screen and moving to the right. The packets are organized in lines where packets of each line travel at different speeds. Once the player is on a packet, he/she will move along with it. If a packet drives the player outside of the screen, or if the player jumps on the cable without reaching a packet, he/she will die and start at the beginning of the same level once again. In the second part (the browser part) the player has to cross the browser screen by avoiding the bugs coming from the left. If the player gets hit by a bug he/she will start at the beginning of the same level once again. These are very simple rules, but as you will see they will already give us plenty of things to think about. Learning the basics Throughout this article, we will use DOM elements to render game elements. Another popular solution would be to use the Canvas element. There are plus and minus points for both technologies and there are a few effects that are simply not possible to produce with only DOM elements. However, for the beginner, the DOM offers the advantage of being easier to debug, to work on almost all existing browsers (yes, even on Internet Explorer 6), and in most cases to offer reasonable speed for games. The DOM also abstracts the dirty business of having to target individual pixels and tracking which part of the screen has to be redrawn. Even though Internet Explorer supports most of the features we will see in this book, I would not recommend creating a game that supports it. Indeed, its market share is negligible nowadays (http://www.ie6countdown.com/) and you will encounter some performance issues. Now from some game terminology, sprites are the moving part of a game. They may be animated or nonanimated (in the sense of changing their aspect versus simply moving around). Other parts of the game may include the background, the UI, and tiles. Framework During this article, we will write some code; part of the code belongs to an example game and is used to describe scenes or logic that are specific to it. Some code, however, is very likely to be reused in each of your games. For this reason, we will regroup some of those functions into a framework that we will cleverly call gameFramework or gf in short. A very simple way to define a namespace in JavaScript is to create an object and add all your function directly to it. The following code gives you an example of what this might look like for two functions, shake and stir, in the namespace cocktail. // define the namespacevar cocktail = {};// add the function shake to the namespacecocktail.shake = function(){...}// add the function stir to the namespacecocktail.stir = function(){...} This has the advantage of avoiding collision with other libraries that use similar names for their objects or functions. Therefore, from now on when you see any function added to the namespace, it will mean that we think those functions will be used by the other games we will create later in this article or that you might want to create yourself. The following code is another notation for namespace. Which one you use is a personal preference and you should really use the one that feels right to you! var cocktail = {// add the function shake to the namespaceshake: function(){...},// add the function stir to the namespacestir: function(){...}}; Typically, you would keep the code of the framework in a JS file (let's say gameFramework.js) and the code of the game in another JS file. Once your game is ready to be published, you may want to regroup all your JavaScript code into one file (including jQuery if you wish so) and minimize it. However, for the whole development phase it will be way more convenient to keep them separate. Sprites Sprites are the basic building blocks of your game. They are basically images that can be animated and moved around the screen. To create them you can use any image editor. If you work on OS X, there is a free one that I find has been particularly well done, Pixen (http://pixenapp.com/). You can use animated gifs. With this method you have no way to access the index of the current frame through JavaScript, and no control over when the animation starts to play or when it ends. Furthermore, having many animated GIFs tends to slow things down a lot. You can change the source of the image. This is already a better solution, but provides worse performance if proposed and requires a large number of individual images. Another disadvantage is that you cannot choose to display only one part of the image; you have to show the entire image each time. Finally, if you want to have a sprite made of a repeating image, you will have to use many img elements. For the sake of completeness, we should mention here one advantage of img; it's really easy to scale an img element—just adjust the width and height. The proposed solution uses simple divs of defined dimensions and sets an image in the background. To generate animated sprites, you could change the background image, but instead we use the background position CSS property. The image used in this situation is called a sprite sheet and typically looks something like the following screenshot: The mechanism by which the animation is generated is shown in the following screenshot: Another advantage is that you can use a single sprite sheet to hold multiple animations. This way you will avoid having to load many different images. Depending on the situation, you may still want to use more than one sprite sheet, but it's a good thing to try to minimize their number. Implementing animations It's very simple to implement this solution. We will use .css() to change the background properties and a simple setInterval to change the current frame of the animation. Therefore, let's say that we have a sprite sheet containing 4 frames of a walk cycle where each frame measures 64 by 64 pixels. First, we simply have to create a div with the sprite sheet as its background. This div should measure 64 by 64 pixels, otherwise the next frame would leak onto the current one. In the following example, we add the sprite to a div with the ID mygame. $("#mygame").append("<div id='sprite1'>"); $("#sprite1").css("backgroundImage","url('spritesheet1.png')"); As the background image is by default aligned with the upper-left corner of the div, we will only see the first frame of the walk-cycle sprite sheet. What we want is to be able to change what frame is visible. The following function changes the background position to the correct position based on the argument passed to it. Take a look at the following code for the exact meaning of the arguments: /** * This function sets the current frame. * -divId: the Id of the div from which you want to change the * frame * -frameNumber: the frame number * -frameDimension: the width of a frame **/ gameFramework.setFrame = function(divId,frameNumber, frameDimension) { $("#"+divId) .css("bakgroundPosition", "" + frameNumber * frameDimension + "px 0px"); } Now we have to call this at regular intervals to produce the animation. We will use setInterval with an interval of 60 milliseconds, that is, around 17 frames per second. This should be enough to give the impression of walking; however, this really has to be fine-tuned to match your sprite sheet. To do this we use an anonymous function that we pass to setInterval, which will in turn call our function with the correct parameter. var totalNumberOfFrame = 4;var frameNumber = 0;setInterval(function(){gameFramework.setFrame("sprite1",frameNumber, 64);frameNumber = (frameNumber + 1) % totalNumberOfFrame;}, 60); You probably noticed that we're doing something special to compute the current frame. The goal is to cover values from 0 to 3 (as they're 4 frames) and to loop back to 0 when we reach 4. The operation we use for this is called modulo (%) and it's the rest of the integer division (also known as Euclidean division). For example, at the third frame we have 3 / 4 which is equal to 0 plus a remainder of 3, so 3 % 4 = 3. When the frame number reaches 4 we have 4 / 4 = 1 plus a remainder of 0, so 4 % 4 = 0. This mechanism is used in a lot of situations. Adding animations to our framework As you can see there are more and more variables needed to generate an animation: the URL of the image, the number of frames, their dimension, the rate of the animation, and the current frame. Furthermore, all those variables are associated with one animation, so if we need a second one we have to define twice as many variables. The obvious solution is to use objects. We will create an animation object that will hold all the variables we need (for now, it won't need any method). This object, like all the things belonging to our framework, will be in the gameFramework namespace. Instead of giving all the values of each of the properties of the animation as an argument, we will use a single object literal, and all the properties that aren't defined will default to some well-thought-out values. To do this, jQuery offers a very convenient method: $.extend. This is a very powerful method and you should really take a look at the API documentation (http://api.jquery.com/) to see everything that it can do. Here we will pass to it three arguments: the first one will be extended with the values of the second one and the resulting object will be extended with the values of the third. /*** Animation Object.**/gf.animation = function(options) {var defaultValues = {url : false,width : 64,numberOfFrames : 1,currentFrame : 0,rate : 30};$.extend(this, defaultValues, options);} To use this function we will simply create a new instance of it with the desired values. Here you can see the values used in the preceding examples: var firstAnim = new gameFramework.animation({url: "spritesheet1.png",numberOfFrames: 4,rate: 60}); As you can see, we didn't need to specify width: 64 because it's the default value! This pattern is very convenient and you should keep it in mind each time you need default values and also the flexibility to override them. We can rewrite the function to use the animation object: gf.setFrame = function(divId, animation) {$("#" + divId).css("bakgroundPosition", "" + animation.currentFrame *animation.width + "px 0px");} Now we will create a function for our framework based on the technique we've already seen, but this time it will use the new animation object. This function will start animating a sprite, either once or in a loop. There is one thing we have to be careful about—if we define an animation for a sprite that is already animated we need to deactivate the current animation and replace it with the new one. To do this we will need an array to hold the list of all intervals' handles. Then we'll only need to check if one exists for this sprite and clear it, then define it again. gf.animationHandles = {}; /** * Sets the animation for the given sprite. **/ gf.setAnimation = function(divId, animation, loop){ if(gf.animationHandles[divId]){ clearInterval(gf.animationHandles[divId]); } if(animation.url){ $("#"+divId).css("backgroundImage","url('"+animation. url+"')"); } if(animation.numberOfFrame > 1){ gf.animationHandles[divId] = setInterval(function(){ animation.currentFrame++; if(!loop && currentFrame > animation.numberOfFrame){ clearInterval(gf.animationHandles[divId]); gf.animationHandles[divId] = false; } else { animation.currentFrame %= animation. numberOfFrame; gf.setFrame(divId, animation); } }, animation.rate); } } This will provide a convenient, flexible, and quite high-level way to set an animation for a sprite.
Read more
  • 0
  • 0
  • 7229

article-image-wijmo-widgets
Packt
31 May 2013
9 min read
Save for later

Wijmo Widgets

Packt
31 May 2013
9 min read
(For more resources related to this topic, see here.) Column bar chart (Simple) A column bar chart widget is slightly different from the regular bar chart widget we previously created. Remember we also had a look at some of the useful and common options used by most Wijmo developers. The last one we listed was the horizontal option of type Boolean. The default value of the horizontal option is true. This implies that the bar chart will be rendered in a horizontal layout by default. Getting ready For the creation of our first column bar chart, we shall proceed by setting the horizontal option to false, using the same code used for the previous bar chart we had created. Here's our new complete code: <html><head><!--jQuery References--><script src = "http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.1.min.js" type="text/javascript"></script><script src = "http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.17/jqueryui.min.js" type="text/javascript"></script><!--Wijmo Widgets JavaScript--><script src = "http://cdn.wijmo.com/jquery.wijmo-open.all.2.0.0.min.js"type="text/javascript"></script><script src = "http://cdn.wijmo.com/jquery.wijmo-complete.all.2.0.0.min.js" type="text/javascript"></script><!--Theme--><link href = "http://cdn.wijmo.com/themes/rocket/jquery-wijmo.css"rel="stylesheet" type="text/css" title="rocket-jqueryui" /><!--Wijmo Widgets CSS--><link href = "http://cdn.wijmo.com/jquery.wijmo-complete.all.2.0.0.min.css" rel="stylesheet" type="text/css" /></head><body><div id="wijbarchart" class="ui-widget ui-widget-content ui-cornerall"style="width: 400px;height: 300px"></div><script id="scriptInit" type="text/javascript">$(document).ready(function () {//activating the wijbarchart function on #wijbarchart$("#wijbarchart").wijbarchart({horizontal: false,//makes it verticalaxis: { //set up the x and y axesy: {text: "Total Automation Sales",},x: {text: "",labels: {style: {rotation: -45}}}},hint: { //hint text when hovering over chartcontent: function () {return this.data.label + 'n ' + this.y + '';}},header: {//chart titletext: "US Toyota Automobile Statistics (DummyData)"},//data for chart representing each columnseriesList: [{label: "US",legendEntry: true,data: { x: ['Toyota Camry', 'Toyota Corolla','Toyota Sienna'], y: [12.35, 21.50, 30.56] }}],seriesStyles: [{fill: "40-#BD0070-#718680", stroke: "#1261C0",opacity: 0.7}],seriesHoverStyles: [{ "stroke-width": "1.5", opacity:1}]});});</script></body></html> Notice from the preceding code, which we will hereon refer to as the main code, that we set the horizontal option to false. Now, when we run the main code, we should see a column bar chart widget as follows: That's how simple switching from a regular bar chart to a column bar chart is. The choice between either of the two bar charts is usually dependent on user preference. How to do it... We reference the Wijmo dependencies as follows: After the page loads, we set the horizontal property to false. The x and y properties are set, and y is rotated at -45 degrees, which rotates the labels for Toyota Camry, Toyota Corolla, and Toyota Sienna. We set the hint property, which is displayed on hovering over the chart. We set the header property, which is displayed atop the grid. For the seriesList property, we have a data subproperty that holds data for x and y. These values are mapped one-to-one in such a way that x['Toyota Camry'] gets y[0] or y[12.35]. For the seriesStyles property, we set the gradient color as "40-#BD0070- #718680" and set the opacity value as 0.7. Bubble chart (Intermediate) A bubble chart is a chart whose data points are replaced with bubbles of various shapes and scattered across the chart. It is like a scatter chart. The Wijmo widget representing a bubble chart is referred to as a wijbubblechart object. Getting ready The data points or bubbles each have three non-dependent values, x, y, and y1 as follows: The value x defines the Cartesian position along the x axis The value y defines the Cartesian position along the y axis The value y1 defines the bubble size at each point Having understood a bubble chart and the three values that define the positions of the bubble, we can now happily proceed with an implementation. Let us create a wijbubblechart object of the percentage of college graduates in six major cities around the world. This is dummy data and doesn't reflect the actual relationship between college graduates and the health of the corresponding economy. However, this dummy data is based on the assumption that a city with more graduates per thousand will have a smarter economy. Also, this depends on the overall population of that city. Enter the following code into your favorite code editor: <html><head><!--jQuery References--><script src = "http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.1.min.js" type="text/javascript"></script><script src = "http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.17/jqueryui.min.js" type="text/javascript"></script><!--Wijmo Widgets JavaScript--><script src = "http://cdn.wijmo.com/jquery.wijmo-open.all.2.0.0.min.js"type="text/javascript"></script><script src = "http://cdn.wijmo.com/jquery.wijmo-complete.all.2.0.0.min.js" type="text/javascript"></script><!--Theme--><link href = "http://cdn.wijmo.com/themes/rocket/jquery-wijmo.css"rel="stylesheet" type="text/css" title="rocket-jqueryui" /><!--Wijmo Widgets CSS--><link href = "http://cdn.wijmo.com/jquery.wijmo-complete.all.2.0.0.min.css" rel="stylesheet" type="text/css" /><script type = "text/javascript">$(document).ready(function () {$("#myWijbubblechart").wijbubblechart({showChartLabels: false,axis: {y: {text: "Smart Economy Rating"},x: {text: "College Graduates(Per Thousand)"}},hint: {content: function () {return this.data.label;}},header: {text: "College Graduates Vs. Health of the Economy- 2012"},seriesList: [{label: "Beijing",legendEntry: true,data: { y: [85], x: [150], y1: [1340] },markers: {type: "tri"}}, {label: "New Delhi",legendEntry: true,data: { y: [80], x: [167], y1: [1150] },markers: {type: "diamond"}}, {label: "Los Angeles",legendEntry: true,data: { y: [92], x: [400], y1: [309] },markers: {type: "circle"}}, {label: "Tokyo",legendEntry: true,data: { y: [94], x: [250], y1: [126] },markers: {type: "invertedTri"}}, {label: "London",legendEntry: true,data: { y: [82], x: [200], y1: [140] },markers: {type: "cross"}}, {label: "Lagos",legendEntry: true,data: { y: [48], x: [374], y1: [72] },markers: {type: "box"}}]});});</script></head><body><div id="myWijbubblechart" class="ui-widget ui-widget-content uicorner-all" style="width: 500px;height: 300px"></div></body></html> If the preceding code is copied correctly and run in a browser, we should have a Wijmo bubble chart similar to the following screenshot: How to do it... To see how the wijbubblechart object works, we can simply examine one of the objects in the seriesList property, like this one: {label: "Beijing",legendEntry: true,data: { y: [85], x: [150], y1: [1340] },markers: {type: "tri"}}, Remember that we already defined x, y, and y1 as the values of a point on the x axis, a point on the y axis, and the size of the bubble respectively. So in this case, for Beijing the value for y is set to 85, and the size of the bubble, y1, is 1340. The legendEntry property is set to true so we can see Beijing in the legend area by the right of the chart. We can see the various bubbles in different shapes and a legend that tells what city each bubble represents. The type property of the markers object is responsible for setting the shape of the bubble. markers: {type: "tri"} There's more... One more common aspect of the wijbubblechart object is the possibility of changing its appearance, for example, applying gradient colors, using some options, and so on. To achieve this we simply have to include a seriesStyles property as follows: <script type="text/javascript">$(document).ready(function () {//instantiating wijbubblechart on #myWijbubblechart$("#myWijbubblechart").wijbubblechart({showChartLabels: false,//setup the x and y axis labelsaxis: {y: {text: "Smart Economy Rating"},x: {text: "College Graduates(Per Thousand)"}},//Display hint text on chart hoverhint: {content: function () {return this.data.label;}},//title of chartheader: {text: "College Graduates Vs. Health of the Economy- 2012"},//chart color fill stylesseriesStyles: [{fill: "180-#8F8F8F-#C462AC", stroke: "#8F8F8F"}, {fill: "45-#C462AC-#2371B0", stroke: "#C462AC"}, {fill: "90-#4A067D-#0B7D19", stroke: "#4A067D"}, {fill: "270-#2371B0-#6AABA7", stroke: "#2371B0"}, {fill: "45-#0C85F0-#852E85", stroke: "#0C85F0"}, {fill: "180-#6AABA7-#AB6A9C", stroke: "#6AABA7"}],//data values for each bubbleseriesList: [{label: "Beijing",legendEntry: true,data: { y: [85], x: [150], y1: [1340] },markers: {type: "tri"}}, {label: "New Delhi",legendEntry: true,data: { y: [80], x: [167], y1: [1150] },markers: {type: "diamond"}}, {label: "Los Angeles",legendEntry: true,data: { y: [92], x: [400], y1: [309] },markers: {type: "circle"}}, {label: "Tokyo",legendEntry: true,data: { y: [94], x: [250], y1: [126] },markers: {type: "invertedTri"}}, {label: "London",legendEntry: true,data: { y: [82], x: [200], y1: [140] },markers: {type: "cross"}}, {label: "Lagos",legendEntry: true,data: { y: [48], x: [374], y1: [72] },markers: {type: "box"}}]});});</script> The script tags should be embedded within the HTML tags for a successful run. If we successfully run the preceding code, we should have a bubble chart that looks like this: See also You can visit http://wijmo.com/wiki/index. php/Bubblechart for more details about Wijmo bubble charts and more advanced options available for customizing your charts. Summary In this Article, we have discussed the Column Bar Chart and Bubble Chart wijmos. Column bar chart (Simple) explains how to convert a regular Wijmo bar chart to a column bar chart widget. Bubble chart (Intermediate) shows how to create and customize a bubble chart widget Resources for Article : Further resources on this subject: Getting Started with jQuery [Article] Exclusive Offer On jQuery Books: Winner Of 2010 Open-Source JavaScript Libraries [Article] New Effects Added by jQuery UI [Article]
Read more
  • 0
  • 0
  • 1502
article-image-dynamically-enable-control-become-expert
Packt
31 May 2013
3 min read
Save for later

Dynamically enable a control (Become an expert)

Packt
31 May 2013
3 min read
(For more resources related to this topic, see here.) Getting ready We will implement an IExternalCommandAvailability interface where we allow the command to be enabled only when a door element is selected in the current model. How to do it... Add a new class named AvailabilityDoorSelected.vb. Enter the IExternalCommandAvailability code as shown, which returns true only when a door element is selected in the model: Imports Autodesk.Revit.UIImports Autodesk.Revit.DB''' <summary>''' Enables a Command Only if a''' Door is Selected in the User Interface''' </summary>Public Class AvailabilityDoorSelectedImplements IExternalCommandAvailability''' <summary>''' Command Availability Implementation''' </summary>Public Function IsCommandAvailable(appData As _UIApplication,selectedCats As CategorySet) _As Boolean Implements _IExternalCommandAvailability.IsCommandAvailable' Iterate CategoriesFor i = 0 To selectedCats.SizeTry' Get the CategoryDim m_c As Category = _TryCast(selectedCats(i), Category)' Is it a Door?If m_c.Name = "Doors" Then Return TrueCatchEnd TryNextReturn FalseEnd FunctionEnd Class Open the ApplicationRibbon class and enter the following code right before the ' Success line in the AddPushButton function that will assign this availability implementation to our sample button: ' Availability - Door Selectionm_pb.AvailabilityClassName = _"Revit2013Samples_VB.AvailabilityDoorSelected" Run the add-in in the debugger and open one of the sample project models that ship with Revit. Select the door element in the model to enable the sample button. Deselect the door and the button will become disabled again. How it works... Our AvailabilityDoorSelected class will execute anytime that a user control that this class is assigned to is either made visible in the Revit user interface or an element in the model is selected. Element selection will only execute this class when an assigned control is visible in the Revit UI. There is no limit to the number of user controls that you can assign to any class that implements IExternalCommandAvailability nor is there a limit to the amount of IExternalCommandAvailability implementations that you can use in your projects. The following illustration shows on the left-hand side how the main button looks without a door selected and on the right-hand side how it becomes enabled when a door is selected. We could have generated a more complex scenario for our availability implementation, but in an effort to keep it simple we only included door selection as a requirement to enable our command. The possibilities for this functionality are endless and I'm sure you will find plenty of uses for it in your own projects in the future. Summary This article explained how to dynamically enable a control. Resources for Article : Further resources on this subject: Papervision3D External Models: Part 1 [Article] Importing 3D Formats into Away3D [Article] Designing an Avatar in Flash Multiplayer Virtual Worlds [Article]
Read more
  • 0
  • 0
  • 1961

article-image-welcoming-your-visitors-creating-attractive-home-pages-and-overview-pages
Packt
31 May 2013
25 min read
Save for later

Welcoming your Visitors: Creating Attractive Home Pages and Overview Pages

Packt
31 May 2013
25 min read
(For more resources related to this topic, see here.) Up to now, you've set up the home page and category overview pages using the default options. But you may have noticed that Joomla offers dozens of options for these page types. Changing these options can completely alter the way content is presented. In fact, different settings can create very different looking pages. To effectively welcome your visitors and entice them to read your valuable content, we'll create a better home page and effective category pages. In the following screenshots, you'll see the page types we're talking about. The basic layout of both home pages and overview pages is similar. On the left-hand side is the example home page in the default Joomla installation, on the right-hand side is an example category overview page found via the About Joomla menu (Using Joomla | Using Extensions | Components | Content Component | Article Category Blog): Why do you need overview pages, anyway? Typically, Joomla will lead your site visitor to a category content in three steps. Between the Main Menu and the actual content, there's a secondary page to show category contents. You can see how this works in the following set of screenshots: A visitor clicks on a menu link. They are taken to an overview page with article previews inviting them to click Read more links. They click to read the full article. As you can see, what's on the home page and the overview pages (and how it's presented) is vitally important to your site. It's the teaser texts, images, and hyperlinks on these pages that offer your visitors a first glimpse of the actual content. Of course, people don't always arrive at your site via the home page. Search engine results might take them directly to any page— including overview pages. One more reason to make those pages as enticing as you can! Overview page, landing page, secondary home page? Joomla doesn't have a name for overview pages. Among web builders they're also known as start pages, category pages, department pages, or landing pages. Whatever you like to call it, it's the same thing: a navigational page that provides an overview of site categories. In this book we'll call them category overview pages. Creating the perfect home – mastering home page layout By default, the homepage of any Joomla site is set up to display the following items: One introductory article text over the full width of the mainbody Three intro texts in three columns As we haven't changed any of the homepage layout settings up to now, the example site homepage has the same layout. This default setup is suited for many types of content-rich sites. But you're certainly not limited to displaying this one particular combination of intro texts and links in the central part of the home page (the "mainbody", as it is called in Joomla). There's a vast amount of choices on how to display content on the home page, and what to display. Changing the way the home page is arranged It's your client on the phone, telling you that—happy as they are with their new site—some CORBA staff members find the home page layout too distracting. They don't like the newspaper look that displays the content columns in different widths. Would you be so kind as to tone things down a little? If you could quickly show them an alternative layout, that would be fine. You hang up and dive into the homepage settings. Time for action – rearranging the layout of articles on the home page You decide to rearrange the items on the home page. Let's say you want a maximum of two intro texts, both in just one column. Apart from this, you would like to show a few hyperlinks to other articles that could be of interest to visitors browsing the home page. You may wonder where Joomla stores the home page settings. As we've seen in previous chapters, menu link settings often determine Joomla's page output—and this also holds for the Home link in the main menu. This menu link is of a specific Menu Item Type, Featured Articles. To change the appearance of the home page, we'll customize the Home menu link settings. Navigate to Menus | Main Menu. In the Menu Manager, click on Home to enter the screen where you can edit the menu link settings. Click the Advanced Options tab. In the Layout Options section, the current settings are shown as follows: These are the "magic numbers" that determine the page lay-out. There's 1 leading article (which means it's displayed in full width), intro articles are shown in 3 columns, and there are 0 links to articles. Change the values as follows: set # Leading Articles to 0, # Intro Articles to 2, # Columns to 1, and # Links to 4. This way just two articles will be shown in a single column and the rest of the featured articles is displayed as a set of hyperlinks. Save your changes and click on View site to see the changes on the frontend. There are now two full-width intro texts. Although you have set # Links to 4, beneath the intro texts only two article links are displayed. This is because up to now only four articles have been assigned to the home page. If you'll assign more articles to the home page, this list will grow to a maximum of four hyperlinks. What just happened? The settings of any menu item allow you to influence the look of the hyperlink's destination page. By default, the Joomla Home link of the main menu is of the Featured Articles Menu Item Type. In this case, you've tweaked the layout options of the Featured Articles menu link to change the home page mainbody. The magic numbers of the Layout Options section are really powerful as different values can completely change the way the page content is displayed. Have a go hero – tweak home page layout options Joomla offers you dozens of settings to customize the home page layout. Navigate to Menus | Main Menu | Home and click the Advanced Options tab to have a look at the different option panels, such as Layout Options. First, you will probably want to set Pagination to Hide. That way, you'll hide the pagination links (< Start Prev Next Last >) that Joomla displays when there are more articles available than can be shown on the home page as intro texts. In our example, the pagination links allow the visitor to navigate to a "second home page", displaying the intro texts of the two hyperlinks in the More articles ... list. Showing pagination links on a home page seems suited for weblog home pages, where visitors expect to be able to browse through possibly long lists of blog entries. On most other types of sites, web users aren't likely to expect multi-page home pages. The options for the Home link (or any other Featured Articles Menu Item Type) allow you to also control exactly what details are shown for every article on the home page. Through the menu link settings you determine whether or not you want to show the author name, publication date, the category name, and much more. These article display settings in the menu link overrule the general settings found through Content | Article Manager | Options. For a full overview of all options available for the Featured Articles Menu Item Type. Adding items to the home page In the More Articles … hyperlink list at the bottom of your home page, two hyperlinks are shown. That's because only four articles are set to display on the home page. To add a couple of articles, navigate to Content | Article Manager. Add any article by clicking on the white star in the Status column to the left-hand side of the article title. The grey star changes to an orange star. In the following example, we've selected a News item (CORBA Magazine Looking for Authors) to be Featured on the homepage: Want to see what this looks like up front? Just click on View Site. The new home page item is shown at the top. All other featured items are now positioned one position lower than before. You'll notice that the Hideous Still Lifes intro text has disappeared as this featured item has now slid down one position, to the list with article hyperlinks. This list now contains three articles instead of two. Another way to add articles to the home page Adding items to the home page takes just a few clicks in the Article Manager Status column. You can also add an individual article to the home page through a setting in the Edit Article screen: under Details, select Featured: Yes. Controlling the order of home page items manually Now that you've reorganized your home page layout, you'll probably want some control over the order of the home page items. To manually set the order, first edit the Home menu link. Click Advanced Options and under Layout Options, make sure Category Order is set to No order: Click Save & Close and go to Content | Featured Articles and set the order as desired. First, set the value of the Sort Order By select box (by default it shows Title) to Ordering. Now you can change the articles order by clicking the three vertical squares to the left-hand side of any article title and dragging the article to another position. The intro texts and links on the home page will now be displayed in the order they have in the Featured Articles screen: What's the use of the Featured Articles screen? In the Featured Articles screen, you can't—as you might have expected—assign items to the Featured status. As you've seen, you can assign articles to the Featured status in the Article Manager (or in the article editing screen). You'll probably use the Featured Articles screen if you want to manually control the order of home page items, or if you want a quick overview of all featured articles. Apart from this, the Featured Articles screen allows you to publish, delete, or archive featured articles—but you can just as easily use the Article Manager for that too. Setting a criteria to automatically order home page items Having full manual control over the order of home page items can be convenient when you have a fixed set of content items that you want to show up on the home page, for example, when you have a corporate site and want to always show your company profile, an introduction to your products, and a link to a page with your address and contact details. However, when your site is frequently updated with new content, you'll probably want Joomla to automatically arrange the home page items to a certain ordering criteria. Again, you can customize this behavior by editing the Home link in the main menu. Its Layout Options allow you to choose from a wide range of ordering methods. Time for action – show the most recent items first The visitors of the CORBA site will probably expect to see the most recently added items on the top of the page. Let's set the Layout Options to organize things accordingly. Navigate to Menus | Main Menu and click the Home link to edit its settings. Under the Advanced Options tab, you'll find the Layout Options offering several ordering options for featured articles. Make sure Category Order is set to No order, to avoid that specific category order settings overruling the article settings you choose. In the Article Order drop-down list, choose Most recent first. As the Date for ordering, select Create Date. When ordering your articles by date, you'll probably want to display the creation date for every article. Navigate to the Article Options panel of the menu link and make sure Show Create Date is set to Show. Click on Save and click on View Site. Now the most recent items are shown first on the home page: What just happened? You've told Joomla to put the most recently added items first on the home page. If you want, you can check this by opening a featured article, changing its created date to Today, and saving your changes; this article will immediately be displayed at the top in the home page layout. If you prefer to order home page items in another way (for example, alphabetically by title), you can do this by selecting the appropriate Article Order settings of the home page menu item (the Home link in the Main Menu). The Featured Articles Menu Item Type – an overview of all options You've seen that the Home menu is a link of the Featured Articles Menu Item Type. When adding or editing a Featured Articles menu link, you'll see there are are six expandable options panels available under the Advanced Options tab, offering a huge number of customization settings. Below you'll find a complete reference of all available options. Dozens of dazzling options – isn't that a bit too much? You've seen them before and now they turn up again, those seemingly endless lists of options. Maybe you find this abundance discouraging. Is it really necessary to check thirty or forty options to create just one menu link? Luckily, that's not how it works. You get fine results when you stick to the default settings. But if you want to tweak the way pages are displayed, it is worthwhile to experiment with the different options. See which settings fit your site best; in your day-to-day web building routine you'll probably stick to those. Layout Options Under Layout Options of the Featured Articles Menu Item Type, you find the main settings affecting the layout and arrangement of home page items. Select Categories   By default, the home page displays Featured Articles from all article categories. You can, however, control exactly from which categories featured articles should be shown. For example, you might want to display only featured articles from the News category on the home page, and featured articles from another category on another Featured Articles page, introducing another category. You'll see an example of this in the section Creating more than one page containing featured articles later in this article. # Leading Articles   Enter the number of leading articles you want to display, that is, intro texts displayed across the entire width of the mainbody. # Intro Articles The number of article intro texts that you want to show in two or more columns. # Columns   Specify the number of columns; over how many columns should the # Intro Articles be distributed? # Links   The number of hyperlinks to other articles (shown below Leading or Intro Articles) Multi Column Order   Should intro texts in multiple columns be sorted from left to right (across) or from top to bottom (down)? Category Order   Do you want to organize the items on the page by category title? You might want to do this when you have many items on your home page and you want your visitor to understand the category structure behind this. If you want to order by category, set Show Category (see Article Options explained in the next table) to show; that way, the visitor can see that the articles are grouped by category. The following Category Order options are available: No Order: If you select this option, the items are displayed in the order you set in the Article Order field (the next option under Layout Options). Title Alphabetical: Organizes categories alphabetically by title. Title Reverse Alphabetical: Organizes categories reverse-alphabetically by title. Category Manager Order: Organizes categories according to the order in the Category Manager and orders the category contents according to the Article Order (which you can specify below). Article Order   You can order the items within the featured articles page by date, alphabetically by Author name or Title, Most hits, and so on. If you choose Featured Articles Order, then the items appear in the order they have on the Content | Featured Articles screen. This last option gives you full manual control over the order of items on the page. Note: the Article Order is applied only after the Category Order. Article Order only has effect if you choose No Order in the Category Order box. Date for Ordering   If you've set the Article Order to Most Recent First or Oldest First, select the date for ordering: Created, Modified, or Published. Pagination   Auto: When there are more items available than it can fit the first page, Joomla automatically adds pagination links (<<Start <Previous 1 2 3 Next> End>>). On the home page, in many cases, you'll probably want to set Pagination to Hide. Pagination Results   If pagination links are shown, Joomla can also display the Pagination Results, the total number of pages (as in Page 1 of 3). Article Options The Article Options influence how articles are displayed on the Featured Articles page. For many extras you can select Show, Hide, Use Global (which means: use the settings chosen under Article Manager | Options), or Use Article Settings (use the settings chosen in the option panels of the individual articles). The Article Options are similar to the options you can set in the general preferences for articles (Article Manager | Options. Here, you can depart from the general settings for the articles and make different choices for this particular menu item. Show Title Display article titles or not? It's hard to find a reason to select Hide. Linked Titles Should the title of the article be a hyperlink to the full article? By default this option is set to Yes. This is better for usability reasons, because your visitor can just click on the article title to read a full article (instead of just on a Read more link). It is also better because search engines love links that clearly define the destination (which article titles should do). Show Intro Text After the visitor has clicked on a Read more link, do you want them to see a page with just the rest of the article text (select No) or the full article including the intro text (select Yes)? Position of Article Info The Article Info consists of the article details, such as the publication date, author name, and so on. If these details are set to be displayed, do you want to display them above the article, below the article, or split (partly above the article and partly below it)? Show Category Select Show if you want to show the category name below the article title. Joomla will display the category (as shown in the following screenshot: Category: Club Meetings). Link Category If the Category title is shown, should it be a hyperlink to the category? In most cases it's a good idea to select Yes here: this provides visitors with a link to category contents with every article. Show Parent Select Show if you want to show the name of the main category (the parent category of the current article category) below the article title. This will look as follows: Link Parent Just like the Category title, the title of the parent category can be made a link to an overview page of the main category contents. Show Author, Link Author, Show Create Date, Show Modify Date, Show Publish Date Do you want to show the author name (and make it a link to a page with other articles by the same author), the creation date, the date the article was last updated, and/or the date on which the article was first published? By default, many of these options are set to Show. You may want to choose Hide if you've got a small site or a site that isn't regularly updated. In that case you probably don't want to broadcast when your articles were written or who wrote them. Show Navigation Select Show if want to display navigation links between articles. Show Voting Should readers be able to rate articles (assign one to five stars to an article)? Show "Read more" Do you want a Read more link to appear below an article intro text? You'll probably want to leave this set to Yes, but if the title of the article is a hyperlink, a Read more link can be omitted. Although Joomla displays the Read more link by default, many web builders just make the article title clickable and omit a separate Read more link. Show Title with Read More It's a good idea to display the article title as part of the Read more text, as this will make the link text more meaningful for both search engines and ordinary visitors. Show Icons Joomla can show a set of special function icons with any article. These allow the visitor to print the article, or to e-mail it. Do you want to display these options as icons or text links? Show Print Icon, Show Email Icon Show or hide the special function icons? It's often better to altogether hide these extras. Your visitors may want to use the print function, but any modern browser offers a print function with better page formatting options. Show Hits Should the number of hits per article (the number of times it's been displayed) be shown? Show Unauthorized Links Do you want to show hyperlinks to articles that are only accessible to registered users, or hide these articles completely? The Article Options listed previously allow you to show or hide all kinds of details, such as Author, Create Date, and Modify Date. In the following image, you can see the result when most options are set to Show. Obviously, this results in too much "detail clutter". On a website that's maintained by just one or a few authors, or a website that isn't updated regularly, you might want to hide author and date details. On a home page you'll probably also want to hide all of the special function icons (set Icons, Print Icon, and Email Icon to Hide). It's unlikely that visitors want to print or e-mail parts of your home page content. In the following image, all extras are hidden, which leaves much more room for actual content in the same space. Integration Options The Integration Options are only relevant when you use news feeds (RSS feeds) on your website. Show Feed Link The Show Feed Link option allows you to show or hide an RSS Feed Link. This will display a feed icon in the address bar of the web browser. For each feed item show This option allows you to control what to show in the news feed; the intro text of each article, or the full article. Link Type Options The Link Type Options allow you to set the display of the menu link to this page (in this case the Home link). Link Title Attribute Here you can add a description that is displayed when the mouse cursor hovers over the menu link to this page. Link CSS Style Only relevant if you are familiar with CSS and want to apply a custom CSS style to this specific menu link. If you've added a specific style in the CSS stylesheet, in this box you should fill in the name of that special style. Joomla will adjust the HTML and add the CSS style to the current menu Home link, as follows: <a class="specialstyle" ref="/index.php">Home </a> Link Image Should an image be shown in the Main Menu link next to the Home link? Menu images (icons) can make a menu more attractive and easier to scan. Following is one of countless examples from the web: Add Menu Title When you use a Link Image, should the menu link text be displayed next to it? Select No only if you want a completely graphical menu, using just icons. Page Display Options Under Page Display Options, you'll find some options to customize page headings and an option to control the general design of the page. Browser Page Title An HTML page contains a title tag. This doesn't appear on the page itself, but it's is displayed in the title bar of the browser. By default, Joomla will use the menu item title as the title tag. Here, you can overrule this default title. Show Page Heading Here you can determine if a page heading appears at the top of the page (that is, in the mainbody). By default, this option is set to No. Select Yes to show the Menu Item Title as the Page Heading. Page Heading If you want to customize the Page Heading (instead of using the default Menu Item Title as the heading text), enter a text here. Page Class This is only relevant if you want to get more control over the page design: font size, colors, and so on. Using the Page Class field, you add a suffix to the name of all CSS styles used on this page. To use this feature, you have to know your way around in CSS. Metadata Options The Metadata Options allow you to add description and keywords to describe the web page's content. Meta Description, Meta Keywords, Robots, Secure Metadata information is used by search engines. You can add an article description, meta keywords, and enter instructions for Robots (web search engine spiders) and select whether this link should use a specified security protocol. Module Assignment for this Menu Item tab Click the Module Assignment for this Menu Item tab to see links to all modules that are assigned to the current menu item. Modules in Joomla are always assigned to one or more menu items. When the visitor clicks a menu link, a page is displayed consisting of (among other things) specific module blocks. This overview of (links to) assigned modules makes it easier for administrators to jump directly from the menu item to all related modules and change their settings. Creating more than one page containing featured articles By default, the Featured Articles Menu Item Type is used only once on your site. All articles that have the Featured status, are shown on the homepage. This is because the Home link in the Main Menu is created using the Featured Articles Menu Item Type. However, you can create as many Featured Articles pages as you like, each one showing featured articles from different categories. Let's say you want to create a page called "News Highlights", containing featured articles only from the News category. To do this, create a new menu link of the Featured Articles Menu Item Type and instead of All Categories select only the News category: The output would be a separate featured articles page containing news highlights. To avoid the same featured news showing up on both the homepage and the News Highlights page, you would probably want to change the home page settings (currently set to show all categories) and get it to display featured articles from all categories except for the News category. Another type of home page: using a single article So far you've used Joomla's Featured Articles layout for your site's home page. But what if you want a completely different home page layout? That's easily achieved, since Joomla allows you to set any menu item as the default page. Time for action – creating a different home page Let's not use the Featured Articles and create a simple home page that only shows one single, full article: Navigate to Menus | Main Menu. As you can see, there's a star in the Home column of the Home link. This indicates that this is the default page; the visitor will see this page in the mainbody when accessing your site. In this example we'll select the Mission Statement menu item as the new home page. Locate this article in the list and click on the grey star in the Home column. Clicking the grey star will turn its color into orange, indicating this is now the default page. Click on View Site. The results are shown in the following screenshot. An ordinary article is now the home page: If you want to update the Main Menu to reflect these changes, you can hide the existing Home link in the Article Manager, which is still pointing to the "old" homepage. To do this, in the Menu Manager you would click on the Unpublish item icon next to the Home link and rename the existing Mission Statement menu link to Home. What just happened? You've changed the default view of the home page to a fresh look, showing one article. Of course, you can dress up such a basic home page any way you like. For some sites (a simple "brochure site" presenting a small company or a project), this may be a good solution. The consequence of this approach is, of course, that the Featured status (that you can set in the Article Manager and in the article edit screen) no longer determines what's published on the home page.
Read more
  • 0
  • 0
  • 3866
Modal Close icon
Modal Close icon