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-getting-started-apache-nutch
Packt
18 Dec 2013
13 min read
Save for later

Getting Started with Apache Nutch

Packt
18 Dec 2013
13 min read
(For more resources related to this topic, see here.) Introduction of Apache Nutch Apache Nutch is a very robust and scalable tool for webcrawling and it can be integrated with scripting language i.e Python for web crawling. You can use it whenever your application contains huge data and you want to apply crawling on your data. Apache Nutch is an Open Source WebCrawler Software which is used for crawling websites. You can create your own search engine like google if you understand Apache Nutch clearly. It will provide you your own search engine using which you can increase your application page rank in searching and also customize your application searching according to your needs. It is extensible and scalable. It facilitates for parsing, indexing, creating your own search engine, customize search according to needs, scalability, robustness and ScoringFilter for custom implementations. ScoringFilter is a Java class which is used while creating Apache Nutch plugin. It is used for manipulating scoring variables. We can run Apache Nutch on a single machine as well as distributed environment like Apache Hadoop. It is written in Java. We can find broken links using Apache Nutch, create a copy of all the visited pages for searching over for example: Build indexes. We can find Web page hyperlinks in an automated manner. Apache Nutch can be integrated with Apache Solr easily and we can index all the webpages which are crawled by Apache Nutch to Apache Solr. We can then use Apache Solr for searching the webpages which are indexed by Apache Nutch. Apache Solr is a search platform which is built on top of Apache Lucene. It can be used for searching any type of data for example webpages. Crawling your first website Crawling is driven by Apache Nutch crawling tool and certain related tools for building and maintaining several data structures. It includes web database, the index and a set of segments. Once Apache Nutch has indexed the webpages to Apache Solr, you can search for the required webpage(s) in Apache Solr. Apache Solr Installation Apache Solr is a search platform which is built on top of Apache Lucene. It can be used for searching any type of data for example webpages. It’s a very powerful searching mechanism and provides full-text search, dynamic clustering, database integration, rich document handling and many more. Apache SOLR will be used for indexing urls which are crawled by Apache Nutch and then one can search the details in Apache SOLR crawled by Apache Nutch. Crawling your website using the crawl script Apache Nutch 2.2.1 comes with the facility of crawl script which does crawling by just executing one single script. In earlier version, we have to manually do each step like generating data, fetching data, parsing data and so on for perfrom crawling. Crawling the web, the CrawlDb, and URL filters When user invokes crawling command in Apache Nutch 1.x, crawlDB is generated by Apache Nutch which is nothing but a directory which contains details about crawling. In Apache 2.x, crawlDB is not present. Instead Apache Nutch keeps all the crawling data directly into the database. InjectorJob The injector will add the necessary urls to the crawldb. Crawldb is the directory which is created by Apache Nutch for storing data related to crawling. You need to provide urls to InjectorJob either by downloading urls from internet or writing your own file which contains urls. Let’s say you have created one directory called urls which contains all the urls that needs to be injected in cralwdb. Following command will be used for perform the InjectorJob: #bin/nutch inject crawl/crawldb urls Urls will be directory which contains all the urls which needs to be injected in crawldb. Crawl/crawldb is the directory in which injected urls will be placed. After performing this job, you have number of unfetched urls inside your database i.e crawldb. GeneratorJob Once we have done with the InjectorJob, now it’s time to fetch the injected urls from crawldb. So for fetching the urls, you need to perform GeneratorJob before. Follwing command will be used for GeneratorJob: #bin/nutch generate crawl/crawldb crawl/segments Crawldb is the directory from where urls are generated. Segments is the directory which is used by GeneratorJob to fetch the necessary information required for crawling. FetcherJob The job of the fetch is to fetch the urls which are generated by GeneratorJob. It will use the input provided by GeneratorJob. Follwing command will be used for FetcherJob: #bin/nutch fetch –all Here I have provided input parameters –all which means this job will fetch all the urls which are generated by GeneratorJob. You can use different input parameters according to your needs. ParserJob After FetcherJob, ParserJob is to parse the urls which are fetched by FetcherJob. Follwing command will be used for ParserJob: # bin/nutch parse –all I have used input parameters –all which will parse all the urls which are fetched by FetcherJob. You can use different input parameter according to your needs. DbUpdaterJob Once the ParserJob has been completed, we need to update the database by providing results of the FetcherJob. This will update the respected databases with the last fetched urls. Following command will be used for DbUpdaterJob: # bin/nutch updatedb crawl/crawldb –all After performing this job, database will contain both updated entries of all the initial pages and also contains the new entities which are correspond to the newly discovered pages which are linked from the initial set. Invertlinks Before applying indexing, we need to first invert all the links. After this we will be able to index incoming anchor text with the pages. Following command will be used for Invertlinks: # bin/nutch invertlinks crawl/linkdb -dir crawl/segments Apache Hadoop Apache Hadoop is designed for running your application on servers where there will be lot of computers in which one will be master computer and rest will be the slave computers. So it’s huge data warehouse. Master computers are the computers which will direct slave computers for data processing. So processing is done by slave computers. This is the reason why Apache Hadoop is used for processing huge amount of data as process is divided into the number of slave computers and that’s why Apache Hadoop gives highest throughput for any processing. So as data will increase, you need to increase number of slave computers. That’s how Apache Hadoop functionality runs. Integration of Apache Nutch with Apache Hadoop Apache Nutch can be easily integrated with Apache Hadoop and we can make our process much faster than running Apache Nutch on single machine. After integrating Apache Nutch with Apache Hadoop, we can perform crawling on Apache Hadoop cluster environment. So the process will be much faster and we will get highest amount of throughput. Apache Hadoop Setup with Cluster This setup is not required a huge hardware to purchase and running Apache Nutch and Apache Hadoop. It is designed in such a way to make the use of hardware maximum. Formatting the HDFS filesystem using the NameNode HDFS stands for Hadoop Distributed File system is a directory which is used by Apache Hadoop for storage purpose. So it’s the directory which stroes all the data related to Apache Hadoop. It has two components as NameNode and DataNode in which NameNode manages the filesystem metadata and DataNodes actually stores the data. It’s highly configurable and suited well for many installations. When there are very large clusters, at that time configuration needs to be tuned. The first step for getting start your Apache Hadoop is the formatting Hadoop filesystem which is implemented on top of the local filesystem of your cluster(which will include only your local machine if you have followed). Setting up the deployment architecture of Apache Nutch We have to setup Apache Nutch on each of the machine which we are using. In this case, we are using six machines cluster. So we have to setup Apache Nutch on each machine. For the less number of machines in our cluster configuration, we can setup manually on each machine. But when the machines are more, let’s say we have 100 machines in our cluster environment. So we can’t setup on each machine manually. For that we require some deployment tool such as Chef or ateleast distributed ssh. You can refer to http://www.opscode.com/chef/ for getting familiar with Chef. You can refer http://www.ibm.com/developerworks/aix/library/au-satdistadmin/for getting familiar with distributed ssh.I will just demonstrate about running Apache Hadoop on Ubuntu for Single-Node Cluster. If you want to go for running Apache Hadoop on Ubuntu for Multi-Node cluster then I have already provided reference link above. You can follow that and configure the same. Once we have done with the deployment of Apache Nutch to single machine, we will run this script start-all.sh that will start the services on the master node and data nodes. It means the script will begin the hadoop daemons on the master node and so we are able to login into all the slave nodes using ssh command as explained above and will begin daemons on the slave nodes. The start-all.sh script expects that Apache Nutch should be put on the same location on each machine. It is also expecting that Apache Hadoop is storing the data at the same filepath on each machine. The start-all.sh script which starts the daemons on the master and slave nodes are going to use password-less login using ssh. Introduction of Apache Nutch configuration with Eclipse Apache Nutch can be easily configured with Eclipse. After that we can perform crawling easily using Eclipse. So need to perform crawling from command line. We can use eclipse for all the operations of crawling which we are doing from command line.Instructions are provided for fixing a development environment for Apache Nutch with Eclipse IDE. It's supposed to give a comprehensive starting resource for configuring, building, crawling and debugging of Apache Nutch within the above of context. Following are the prerequisites for Apache Nutch integration with Eclipse: Get the latest version of Eclipse from http://www.eclipse.org/downloads/packages/release/juno/r All the required subsequent are available from the Eclipse Marketplace. But if they are not, you can download eclipse market place as follows http://marketplace.eclipse.org/marketplace-client-intro Once you've configuired Eclipse, Download as per here http://subclipse.tigris.org/. If you have faced a problem with the 1.8.x release, try 1.6.x. This may resolve compatability issues. Download IvyDE plugin for Eclipse as here http://ant.apache.org/ivy/ivyde/download.cgi Download m2e plugin for Eclipse here http://marketplace.eclipse.org/content/maven-integration-eclipse Introduction of Apache Accumulo Accumulo is basically used as the datastore for storing data. So same way as we are using different databases like MySQL, Oracle, etc. So same way Apache Accumulo can be used. The key point of Apache Accumulo is, it is running on Apache Hadoop Cluster environment. So that's a very good feature with Accumulo.Accumulo sorted, distributed key/value store could be a strong, scalable, high performance information storage and retrieval system. Apache Accumulo depends on Google's BigTable design and is built ontop of Apache Hadoop, ,Thrift and Zookeeper. Apache Accumulo features a some novel improvement on the BigTable design within a form of cell-based access management and the server-side programming mechanism which will do modificationication in key/value pairs at varied points within the data management process Introduction of Apache Gora Apache Gora open source framework providesin-memory data model and persistence for large data. Apache Gora supports persisting to column stores, key and value stores, document stores and RDBMSs and analyzing the data with extensive Apache Hadoop MapReduce support. Supported Datastores Apache Gora presently supports the subsequent datastores: AccumuloProphetess PApache Hbase Amazon DynamoDB Use of Apache Gora Although there are many excellent ORM frameworks for relational databases and data modeling in NoSQL data stores different profoundly from their relative cousins. DataD-model agnostic frameworks like JDO aren't comfortable to be used cases, wherever one has to use the complete power of data models in column stores. Gora fills the thegap giving user an easy-to-use in-memory data model plus persistence for large data frameworkproviding data store specific mappings and also in built Apache Hadoop support. Integration of Apache Nutch with Apache Accumulo In this section, we are going to cover the integration process for integrating Apache Nutch with Apache Accumulo. Apache Accumulo is basically used for a huge data storeage. It is built on the top of Apache Hadoop, Zookeeper and Thrift. So a potential use of integrating Apache Nutch with Apache Accumulo is when our application has huge data to process and we want to run our application in cluste environment. At that time we can use Apache Accumulo as data storage purpose. As Apache Accumulo only running with Apache Hadoop, maximum use of Apache Accumulo would be in cluster based environment. So first we will start with the configuration of Apache GORA with Apache Nutch. Then we will setup Apache Hadoop and Zookeeper. Then we will do installation and configuration of Apache Accumulo. Then we will test Apache Accumulo and at the end we will see Crawling with Apache Nutch on Apache Accumulo. Setup Apache Hadoop and Apache Zookeeper for Apache Nutch Apache Zookeeper is a centralized service which is used for maintaining configuration information, provideses distributed synchronization, naming and also provideses group services. All these services are used by distributed applications in one or another manner. So all these services are provided by zookeeper so you don’t have to write these services from scratch. You can use these services for implementing consensus, management, group, leader election and presence protocols and you can also build it for your own requirements. Apache Accumulo is built on the top of Apache Hadoop, Zookeeper. So we must configure Apache Accumulo within Apache Hadoop and Apache Zookeeper. You can referrer to http://www.covert.io/post/18414889381/accumulo-nutch-and-gora for any queries related to setup. Integration of Apache Nutch with MySQL In this section, we are going to integrate Apache Nutch with MySQL. So after that you can crawled webpages in Apache Nutch that will be stored in MYSQL. So you can go to MySQL and check your crawled webpages and also perform necessary operations. We will start with the introduction of MySQL then we will cover what is the need of integrating MySQL with Apache Nutch. After that we will see configuration of MySQL with Apache Nutch and at the end we will do crawling with Apache Nutch on MySQL. So let’s just start with the introduction of MYSQL. Summary We covered the following: Downloading Apache Hadoop and Apache Nutch Perform Crawling on Apache Hadoop Cluster in Apache Nutch Apache Nutch configuration with eclipse Installation steps of building Apache Nutch with Eclipse Crawling in Eclipse Configuration of Apache GORA with Apache Nutch Installation and Configuration of Apache Accumulo Crawling with Apache Nutch on Apache Accumulo Need of integrating MySQL with Apache Nutch   Resources for Article: Further resources on this subject: Getting Started with the Alfresco Records Management Module [Article] Making Big Data Work for Hadoop and Solr [Article] Apache Solr PHP Integration [Article]
Read more
  • 0
  • 0
  • 3017

article-image-hello-opencl
Packt
18 Dec 2013
16 min read
Save for later

Hello OpenCL

Packt
18 Dec 2013
16 min read
(For more resources related to this topic, see here.) The Wikipedia definition says that, Parallel Computing is a form of computation in which many calculations are carried out simultaneously, operating on the principle that large problems can often be divided into smaller ones, which are then solved concurrently (in parallel). There are many Parallel Computing programming standards or API specifications, such as OpenMP, OpenMPI, Pthreads, and so on. This book is all about OpenCL Parallel Programming. In this article, we will start with a discussion on different types of parallel programming. We will first introduce you to OpenCL with different OpenCL components. We will also take a look at the various hardware and software vendors of OpenCL and their OpenCL installation steps. Finally, at the end of the article we will see an OpenCL program example SAXPY in detail and its implementation. Advances in computer architecture All over the 20th century computer architectures have advanced by multiple folds. The trend is continuing in the 21st century and will remain for a long time to come. Some of these trends in architecture follow Moore's Law. "Moore's law is the observation that, over the history of computing hardware, the number of transistors on integrated circuits doubles approximately every two years". Many devices in the computer industry are linked to Moore's law, whether they are DSPs, memory devices, or digital cameras. All the hardware advances would be of no use if there weren't any software advances. Algorithms and software applications grow in complexity, as more and more user interaction comes into play. An algorithm can be highly sequential or it may be parallelized, by using any parallel computing framework. Amdahl's Law is used to predict the speedup for an algorithm, which can be obtained given n threads. This speedup is dependent on the value of the amount of strictly serial or non-parallelizable code (B). The time T(n) an algorithm takes to finish when being executed on n thread(s) of execution corresponds to: T(n) = T(1) (B + (1-B)/n) Therefore the theoretical speedup which can be obtained for a given algorithm is given by : Speedup(n) = 1/(B + (1-B)/n) Amdahl's Law has a limitation, that it does not fully exploit the computing power that becomes available as the number of processing core increase. Gustafson's Law takes into account the scaling of the platform by adding more processing elements in the platform. This law assumes that the total amount of work that can be done in parallel, varies linearly with the increase in number of processing elements. Let an algorithm be decomposed into (a+b). The variable a is the serial execution time and variable b is the parallel execution time. Then the corresponding speedup for P parallel elements is given by: (a + P*b) Speedup = (a + P*b) / (a + b) Now defining α as a/(a+b), the sequential execution component, as follows, gives the speedup for P processing elements: Speedup(P) = P – α *(P - 1) Given a problem which can be solved using OpenCL, the same problem can also be solved on a different hardware with different capabilities. Gustafson's law suggests that with more number of computing units, the data set should also increase that is, "fixed work per processor". Whereas Amdahl's law suggests the speedup which can be obtained for the existing data set if more computing units are added, that is, "Fixed work for all processors". Let's take the following example: Let the serial component and parallel component of execution be of one unit each. In Amdahl's Law the strictly serial component of code is B (equals 0.5). For two processors, the speedup T(2) is given by: T(2) = 1 / (0.5 + (1 – 0.5) / 2) = 1.33 Similarly for four and eight processors, the speedup is given by: T(4) = 1.6 and T(8) = 1.77 Adding more processors, for example when n tends to infinity, the speedup obtained at max is only 2. On the other hand in Gustafson's law, Alpha = 1(1+1) = 0.5 (which is also the serial component of code). The speedup for two processors is given by: Speedup(2) = 2 – 0.5(2 - 1) = 1.5 Similarly for four and eight processors, the speedup is given by: Speedup(4) = 2.5 and Speedup(8) = 4.5 The following figure shows the work load scaling factor of Gustafson's law, when compared to Amdahl's law with a constant workload: Comparison of Amdahl's and Gustafson's Law OpenCL is all about parallel programming, and Gustafson's law very well fits into this book as we will be dealing with OpenCL for data parallel applications. Workloads which are data parallel in nature can easily increase the data set and take advantage of the scalable platforms by adding more compute units. For example, more pixels can be computed as more compute units are added. Different parallel programming techniques There are several different forms of parallel computing such as bit-level, instruction level, data, and task parallelism. This book will largely focus on data and task parallelism using heterogeneous devices. We just now coined a term, heterogeneous devices. How do we tackle complex tasks "in parallel" using different types of computer architecture? Why do we need OpenCL when there are many (already defined) open standards for Parallel Computing? To answer this question, let us discuss the pros and cons of different Parallel computing Framework. OpenMP OpenMP is an API that supports multi-platform shared memory multiprocessing programming in C, C++, and Fortran. It is prevalent only on a multi-core computer platform with a shared memory subsystem. A basic OpenMP example implementation of the OpenMP Parallel directive is as follows: #pragma omp parallel { body; } When you build the preceding code using the OpenMP shared library, libgomp would expand to something similar to the following code: void subfunction (void *data) { use data; body; } setup data; GOMP_parallel_start (subfunction, &data, num_threads); subfunction (&data); GOMP_parallel_end (); void GOMP_parallel_start (void (*fn)(void *), void *data, unsigned num_threads) The OpenMP directives make things easy for the developer to modify the existing code to exploit the multicore architecture. OpenMP, though being a great parallel programming tool, does not support parallel execution on heterogeneous devices, and the use of a multicore architecture with shared memory subsystem does not make it cost effective. MPI Message Passing Interface (MPI) has an advantage over OpenMP, that it can run on either the shared or distributed memory architecture. Distributed memory computers are less expensive than large shared memory computers. But it has its own drawback with inherent programming and debugging challenges. One major disadvantage of MPI parallel framework is that the performance is limited by the communication network between the nodes. Supercomputers have a massive number of processors which are interconnected using a high speed network connection or are in computer clusters, where computer processors are in close proximity to each other. In clusters, there is an expensive and dedicated data bus for data transfers across the computers. MPI is extensively used in most of these compute monsters called supercomputers. OpenACC The OpenACC Application Program Interface (API) describes a collection of compiler directives to specify loops and regions of code in standard C, C++, and Fortran to be offloaded from a host CPU to an attached accelerator, providing portability across operating systems, host CPUs, and accelerators. OpenACC is similar to OpenMP in terms of program annotation, but unlike OpenMP which can only be accelerated on CPUs, OpenACC programs can be accelerated on a GPU or on other accelerators also. OpenACC aims to overcome the drawbacks of OpenMP by making parallel programming possible across heterogeneous devices. OpenACC standard describes directives and APIs to accelerate the applications. The ease of programming and the ability to scale the existing codes to use the heterogeneous processor, warrantees a great future for OpenACC programming. CUDA Compute Unified Device Architecture (CUDA) is a parallel computing architecture developed by NVIDIA for graphics processing and GPU (General Purpose GPU) programming. There is a fairly good developer community following for the CUDA software framework. Unlike OpenCL, which is supported on GPUs by many vendors and even on many other devices such as IBM's Cell B.E. processor or TI's DSP processor and so on, CUDA is supported only for NVIDIA GPUs. Due to this lack of generalization, and focus on a very specific hardware platform from a single vendor, OpenCL is gaining traction. CUDA or OpenCL? CUDA is more proprietary and vendor specific but has its own advantages. It is easier to learn and start writing code in CUDA than in OpenCL, due to its simplicity. Optimization of CUDA is more deterministic across a platform, since less number of platforms are supported from a single vendor only. It has simplified few programming constructs and mechanisms. So for a quick start and if you are sure that you can stick to one device (GPU) from a single vendor that is NVIDIA, CUDA can be a good choice. OpenCL on the other hand is supported for many hardware from several vendors and those hardware vary extensively even in their basic architecture, which created the requirement of understanding a little complicated concepts before starting OpenCL programming. Also, due to the support of a huge range of hardware, although an OpenCL program is portable, it may lose optimization when ported from one platform to another. The kernel development where most of the effort goes, is practically identical between the two languages. So, one should not worry about which one to choose. Choose the language which is convenient. But remember your OpenCL application will be vendor agnostic. This book aims at attracting more developers to OpenCL. There are many libraries which use OpenCL programming for acceleration. Some of them are MAGMA, clAMDBLAS, clAMDFFT, BOLT C++ Template library, and JACKET which accelerate MATLAB on GPUs. Besides this, there are C++ and Java bindings available for OpenCL also. Once you've figured out how to write your important "kernels" it's trivial to port to either OpenCL or CUDA. A kernel is a computation code which is executed by an array of threads. CUDA also has a vast set of CUDA accelerated libraries, that is, CUBLAS, CUFFT, CUSPARSE, Thrust and so on. But it may not take a long time to port these libraries to OpenCL. Renderscripts Renderscripts is also an API specification which is targeted for 3D rendering and general purpose compute operations in an Android platform. Android apps can accelerate the performance by using these APIs. It is also a cross-platform solution. When an app is run, the scripts are compiled into a machine code of the device. This device can be a CPU, a GPU, or a DSP. The choice of which device to run it on is made at runtime. If a platform does not have a GPU, the code may fall back to the CPU. Only Android supports this API specification as of now. The execution model in Renderscripts is similar to that of OpenCL. Hybrid parallel computing model Parallel programming models have their own advantages and disadvantages. With the advent of many different types of computer architectures, there is a need to use multiple programming models to achieve high performance. For example, one may want to use MPI as the message passing framework, and then at each node level one might want to use, OpenCL, CUDA, OpenMP, or OpenACC. Besides all the above programming models many compilers such as Intel ICC, GCC, and Open64 provide auto parallelization options, which makes the programmers job easy and exploit the underlying hardware architecture without the need of knowing any parallel computing framework. Compilers are known to be good at providing instruction-level parallelism. But tackling data level or task level auto parallelism has its own limitations and complexities. Introduction to OpenCL OpenCL standard was first introduced by Apple, and later on became part of the open standards organization "Khronos Group". It is a non-profit industry consortium, creating open standards for the authoring, and acceleration of parallel computing, graphics, dynamic media, computer vision and sensor processing on a wide variety of platforms and devices. The goal of OpenCL is to make certain types of parallel programming easier, and to provide vendor agnostic hardware-accelerated parallel execution of code. OpenCL (Open Computing Language) is the first open, royalty-free standard for general-purpose parallel programming of heterogeneous systems. It provides a uniform programming environment for software developers to write efficient, portable code for high-performance compute servers, desktop computer systems, and handheld devices using a diverse mix of multi-core CPUs, GPUs, and DSPs. OpenCL gives developers a common set of easy-to-use tools to take advantage of any device with an OpenCL driver (processors, graphics cards, and so on) for the processing of parallel code. By creating an efficient, close-to-the-metal programming interface, OpenCL will form the foundation layer of a parallel computing ecosystem of platform-independent tools, middleware, and applications. We mentioned vendor agnostic, yes that is what OpenCL is about. The different vendors here can be AMD, Intel, NVIDIA, ARM, TI, and so on. The following diagram shows the different vendors and hardware architectures which use the OpenCL specification to leverage the hardware capabilities: The heterogeneous system The OpenCL framework defines a language to write "kernels". These kernels are functions which are capable of running on different compute devices. OpenCL defines an extended C language for writing compute kernels, and a set of APIs for creating and managing these kernels. The compute kernels are compiled with a runtime compiler, which compiles them on-the-fly during host application execution for the targeted device. This enables the host application to take advantage of all the compute devices in the system with a single set of portable compute kernels. Based on your interest and hardware availability, you might want to do OpenCL programming with a "host and device" combination of "CPU and CPU" or "CPU and GPU". Both have their own programming strategy. In CPUs you can run very large kernels as the CPU architecture supports out-of-order instruction level parallelism and have large caches. For the GPU you will be better off writing small kernels for better performance. Hardware and software vendors There are various hardware vendors who support OpenCL. Every OpenCL vendor provides OpenCL runtime libraries. These runtimes are capable of running only on their specific hardware architectures. Not only across different vendors, but within a vendor there may be different types of architectures which might need a different approach towards OpenCL programming. Now let's discuss the various hardware vendors who provide an implementation of OpenCL, to exploit their underlying hardware. Advanced Micro Devices, Inc. (AMD) With the launch of AMD A Series APU, one of industry's first Accelerated Processing Unit (APU), AMD is leading the efforts of integrating both the x86_64 CPU and GPU dies in one chip. It has four cores of CPU processing power, and also a four or five graphics SIMD engine, depending on the silicon part which you wish to buy. The following figure shows the block diagram of AMD APU architecture: AMD architecture diagram—© 2011, Advanced Micro Devices, Inc. An AMD GPU consist of a number of Compute Engines (CU) and each CU has 16 ALUs. Further, each ALU is a VLIW4 SIMD processor and it could execute a bundle of four or five independent instructions. Each CU could be issued a group of 64 work items which form the work group (wavefront). AMD Radeon ™ HD 6XXX graphics processors uses this design. The following figure shows the HD 6XXX series Compute unit, which has 16 SIMD engines, each of which has four processing elements: AMD Radeon HD 6xxx Series SIMD Engine—© 2011, Advanced Micro Devices, Inc. Starting with the AMD Radeon HD 7XXX series of graphics processors from AMD, there were significant architectural changes. AMD introduced the new Graphics Core Next (GCN) architecture. The following figure shows an GCN compute unit which has 4 SIMD engines and each engine is 16 lanes wide: GCN Compute Unit—© 2011, Advanced Micro Devices, Inc. A group of these Compute Units forms an AMD HD 7xxx Graphics Processor. In GCN, each CU includes four separate SIMD units for vector processing. Each of these SIMD units simultaneously execute a single operation across 16 work items, but each can be working on a separate wavefront. Apart from the APUs, AMD also provides discrete graphics cards. The latest family of graphics card, HD 7XXX, and beyond uses the GCN architecture. NVIDIA® One of NVIDIA GPU architectures is codenamed "Kepler". GeForce® GTX 680 is one Kepler architectural silicon part. Each Kepler GPU consists of different configurations of Graphics Processing Clusters (GPC) and streaming multiprocessors. The GTX 680 consists of four GPCs and eight SMXs as shown in the following figure: NVIDIA Kepler architecture—GTX 680, © NVIDIA® Kepler architecture is part of the GTX 6XX and GTX 7XX family of NVIDIA discrete cards. Prior to Kepler, NVIDIA had Fermi architecture which was part of the GTX 5XX family of discrete and mobile graphic processing units. Intel® Intel's OpenCL implementation is supported in the Sandy Bridge and Ivy Bridge processor families. Sandy Bridge family architecture is also synonymous with the AMD's APU. These processor architectures also integrated a GPU into the same silicon as the CPU by Intel. Intel changed the design of the L3 cache, and allowed the graphic cores to get access to the L3, which is also called as the last level cache. It is because of this L3 sharing that the graphics performance is good in Intel. Each of the CPUs including the graphics execution unit is connected via Ring Bus. Also each execution unit is a true parallel scalar processor. Sandy Bridge provides the graphics engine HD 2000, with six Execution Units (EU), and HD 3000 (12 EU), and Ivy Bridge provides HD 2500(six EU) and HD 4000 (16 EU). The following figure shows the Sandy bridge architecture with a ring bus, which acts as an interconnect between the cores and the HD graphics: Intel Sandy Bridge architecture—© Intel® ARM Mali™ GPUs ARM also provides GPUs by the name of Mali Graphics processors. The Mali T6XX series of processors come with two, four, or eight graphics cores. These graphic engines deliver graphics compute capability to entry level smartphones, tablets, and Smart TVs. The below diagram shows the Mali T628 graphics processor. ARM Mali—T628 graphics processor, © ARM Mali T628 has eight shader cores or graphic cores. These cores also support Renderscripts APIs besides supporting OpenCL. Besides the four key competitors, companies such as TI (DSP), Altera (FPGA), and Oracle are providing OpenCL implementations for their respective hardware. We suggest you to get hold of the benchmark performance numbers of the different processor architectures we discussed, and try to compare the performance numbers of each of them. This is an important first step towards comparing different architectures, and in the future you might want to select a particular OpenCL platform based on your application workload.
Read more
  • 0
  • 0
  • 2763

article-image-managing-alerts
Packt
17 Dec 2013
20 min read
Save for later

Managing Alerts

Packt
17 Dec 2013
20 min read
(For more resources related to this topic, see here.) An efficient, correct, and comprehensive alerting configuration is a key to the success of a monitoring system. It's based on an extensive data collection and eventually leads to managing messages, recipients, and delivery media, as we'll see later in this article. But all this revolves around the conditions defined for the checks, and this is the main business of triggers. Understanding trigger expressions Triggers are quite simple to create and configure—choose a name and a severity, define a simple expression using the expression form, and you are done. The expression form, accessible through the Add button, lets you choose an item, a function to perform on the item's data, and some additional parameters, and gives an output as shown in the following screenshot: You can see how there's a complete item key specification, not just the name, to which a function is applied. The result is then compared to a constant using the greater than operator. The syntax for referencing the item keys is very similar to that of a calculated item. In addition to this basic way of referring to item values, triggers also add a comparison operator that wraps all the calculations up to a Boolean expression. This is the one great unifier of all triggers; no matter how complex the expression, it must always return either a True value or a False value. This value is of course directly related to the state of a trigger, which can only be OK if the expression evaluates to False, or PROBLEM, if the expression evaluates to True. There are no intermediate or soft states for triggers. A trigger can also be in an UNKNOWN state if it's impossible to evaluate the trigger expression (because one of the items has no data, for example). A trigger expression has two main components: Functions applied to the item data Arithmetical and logical operations performed on the functions' results. From a syntactical point of view, the item and function component has to be enclosed in curly brackets, as illustrated in the preceding screenshot, while the arithmetical and logical operators stay outside the brackets. Selecting items and functions You can reference as many items as you want in a trigger expression, as long as you apply a single function to every single item. This means that if you want to use the same item twice, you'll need to specify it twice completely, as shown in the following code: {Alpha:log[/tmp/operations.log,,,10,skip].nodata(600)}=1 | {Alpha:log[/tmp/operations.log,,,10,skip].str(error)}=1 The previously discussed trigger will evaluate to PROBLEM if there are no new lines in the operations.log file for more than ten minutes, or if an error string is found in the lines appended to that same file. Zabbix doesn't apply short-circuit evaluation of the and and or ( & and | ) operators—every comparison will be evaluated regardless of the outcome of the preceding ones. Of course, you don't have to reference items from the same host; you can reference different items from different hosts, and on different nodes too, if you can access them, as shown in the following code: {Node1:Alpha:agent.ping.last(0)}=0 & {Node2:Beta:agent.ping.last(0)}=0 Here, the trigger will evaluate to PROBLEM if both the hosts Alpha and Beta are unreachable. It doesn't matter that the two hosts are monitored by two different nodes. Everything will work as expected as long as the node where the trigger is defined has access to the two monitored hosts' historical data. In other words, the trigger has to be configured on a master node that receives data from both Node1 and Node2. You can apply all the same functions available for calculated items to your items' data. The complete list and specification is available on the official Zabbix wiki (https://www.zabbix.com/documentation/2.0/manual/appendix/triggers/functions), so it would be redundant to repeat them here, but a few common aspects among them deserve a closer look. Choosing between seconds or number of measurements Many trigger functions take a sec or #num argument. This means that you can either specify a time period in seconds, or a number of measurements, and the trigger will take all of the item's data in the said period, and apply the function to it. So, the following code will take the minimum value of Alpha's CPU idle time in the last ten minutes: {Alpha:system.cpu.util[,idle].min(600)} The following code, unlike the previous one, will perform the same operation on the last ten measurements: {Alpha:system.cpu.util[,idle].min(#10)} Will perform the same operation on the last ten measurements. Instead of a value in seconds, you can also specify things such as 10m for ten minutes, 2d for two days, and 6h for six hours. Which one should you use in your triggers? While it obviously depends on your specific needs and objectives, each one has its strengths that makes it useful in the right context. For all kinds of passive checks initiated by the server, you'll often want to stick to a time period expressed as an absolute value. A #5 parameter will vary quite dramatically as a time period if you vary the check interval of the relative item. It's not usually obvious that such a change will also affect related triggers. Moreover, a time period expressed in seconds may be closer to what you really mean to check, and thus may be more easy to understand when you visit the trigger definition at a later date. On the other hand, you'll often want to opt for the #num version of the parameter for many active checks, where there's no guarantee that you will have a constant, reliable interval between measurements. This is especially true for trapper items of any kind, and for log files. With these kinds of items, referencing the number of measurements is often the best option. Date and time functions All the functions that return a time value, whether it's the current date, the current time, the day of the month, or the day of the week, still need a valid item as part of the expression. These can be useful to create triggers that may change status only during certain times of day, or during certain specific days, or better yet, to define well known exceptions to common triggers, when we know that some otherwise unusual behavior is to be expected. For example, a case where there's a bug in one of your company's applications that causes a rogue process to quickly fill up a filesystem with huge log files. While the development team is working on it, they ask you to keep an eye on the said filesystem, and kill the process if it's filling the disk up too quickly. Like with many things in Zabbix, there's more than one way to approach this problem, but you decide to keep it simple and find that, after watching the trending data on the host's disk usage, a good indicator that the process is going rogue is that the filesystem has grown by more than 3 percent in 10 minutes: {Alpha:vfs.fs.size[/var,pused].delta(600)}>3 The only problem with this expression is that there's a completely unrelated process that makes a couple of big file transfers to this same filesystem every night at 2 a.m. While this is a perfectly normal operation, it could still make the trigger switch to a PROBLEM state and send an alert. Adding a couple of time functions will take care of that, as shown in the following code: {Alpha:vfs.fs.size[/var,pused].delta(600)}>3 & ({Alpha:vfs.fs.size[/var,pused].time(0)}<020000 | {Alpha:vfs.fs.size[/var,pused].time(0)}>030000 ) Just keep in mind that all the trigger functions return a numerical value, including the date and time ones, so it's not really practical to express fancy dates like "the first Tuesday of the month" or "last month" (instead of the last 30 days). Trigger severity Severity is little more than a simple label that you attach to a trigger. The web frontend will display different severity values with different colors, and you will be able to create different actions based on them, but they have no further meaning or function in the system. This means that the severity of a trigger will not change over time based on how long that trigger has been in a PROBLEM state, nor can you assign a different severity to different thresholds in the same trigger. If you really need a warning alert when a disk is over 90 percent full, and a critical alert when it's 100 percent full, you will need to create two different triggers with two different thresholds and severity. This may not be the best course of action though, as it could lead to either warnings that are ignored and not acted upon, or critical warnings that will fire up when it's already too late and you have already lost service availability, or even just a redundant configuration with redundant messages and more possibilities for mistakes, or an increased signal-to-noise ratio. A better approach would be to clearly assess the actual severity of the possibility for the disk to fill up, and create just one trigger with a sensible threshold, and possibly an escalating action if you fear that the warning could get lost among the others. Choosing between absolute values and percentages If you look at many native agent items, you'll see that a lot of them can express measurements either as absolute values or as percentages. It often makes sense to do the same while creating one's own custom items, as both representations can be quite useful in and on themselves. When it comes to creating triggers on them though, the two can differ quite a lot, especially if you have the task to keep track of available disk space. Filesystems' sizes and disk usage patterns vary quite a lot between different servers, installations, application implementations, and user engagement. While a free space of 5 percent of a hypothetical disk A could be small enough that it would make sense to trigger a warning and act upon it, the same 5 percent could mean a lot more space for a large disk array, enough that you don't really need to act immediately, but can plan a possible expansion without any urgency. This may lead you to think that percentages are not really useful in these cases, and even that you can't really put disk-space-related triggers in templates, as it would be better to evaluate every single case and build triggers that are tailor-made for every particular disk with its particular usage pattern. While this can certainly be a sensible course of action for particularly sensible and critical filesystems, it can quickly become too much work in a large environment where you may need to monitor hundreds of different filesystems. This is where the delta function can help you create triggers that are general enough that you can apply them to a wide variety of filesystems, so that you can still get a sensible warning about each one of them. You will still need to create more specialized triggers for those special, critical disks, but you'd have to anyway. While it's true that the same percentages may mean quite a different thing for disks with a great difference in size, a similar percentage variation of available space on a different disk could mean quite the same thing; the disk is filling up at a rate that can soon become a problem: {Template_fs:vfs.fs.size[/,pfree].last(0)}<5 & ({Template_fs:vfs.fs.size[/,pfree].delta(1d)} / {Template_fs:vfs.fs.size[/,pfree].last(0,1d) } > 0.5) The previously discussed trigger would report a PROBLEM state not just if the available space is less than 5 percent on a particular disk, but also if the available space has been reduced by more than half in the last 24 hours (don't miss the time-shift parameter in the last function). This means that no matter how big the disk is, based on its usage pattern, it could quickly fill up very soon. Note also how the trigger would need progressively smaller and smaller percentages for it to assume a PROBLEM state, so you'd automatically get more frequent and urgent notifications as the disk is filling up. For these kinds of checks, percentage values should prove more flexible and easy to understand than absolute ones, so that's what you probably want to use as a baseline for templates. On the other hand, absolute values may be your best option if you want to create a very specific trigger for a very specific filesystem. Understanding operations as correlations As you may have already realized, practically every interesting trigger expression is built as a logical operation between two or more simpler expressions. Naturally, it is not that this is the only way to create useful triggers. Many simple checks on the status of an agent.ping item can literally save the day when quickly acted upon, but Zabbix also makes it possible, and relatively easy, to define powerful checks that would require a lot of custom coding to implement in other systems. Let's see a few more examples of relatively complex triggers. Going back to the date and time functions, let's say that you have a trigger that monitors the number of active sessions in an application, and fires up an alert if that number drops too low during certain hours, because you know that there should always be a few automated processes creating and using sessions in that window of time (from 10:30 to 12:30 in this example). During the rest of the day, the number of sessions is neither predictable nor that significant, so you keep sampling it but don't want to receive any alert. A first, simple version of your trigger could look like the following code: {Appserver:sessions.active[myapp].min(300)}<5 & {Appserver:sessions.active[myapp].time(0)} > 103000 & {Appserver:sessions.active[myapp].time(0) } < 123000 The session.active item key could reference a custom script, a calculated item or anything else. It's used here as a label to make the example easier to read, and not as an instance of an actual ready-to-use native item. The only problem with this trigger is that if the number of sessions drops below five in that window of time, but it doesn't come up again until after 12:30, the trigger will stay in the PROBLEM state until the next day. This may be a great nuisance if you have set up multiple actions and escalations on that trigger, as they would go on for a whole day no matter what you do to address the actual sessions problems. But even if you don't have escalating actions, you may have to give accurate reports on these event durations, and an event that looks like it's going on for almost 24 hours would be both incorrect in itself and for any SLA reporting. Even if you don't have reporting concerns, displaying a PROBLEM state when it's not there anymore is a kind of false positive that will not let your monitoring team focus on the real problems, and over the time, may reduce their attention on that particular trigger. A possible solution is to make the trigger return to an OK state outside the target hours, if it was in a PROBLEM state, as shown in the following code: ({Appserver:sessions.active[myapp].min(300)}<5 & {Appserver:sessions.active[myapp].time(0)} > 103000 & {Appserver:sessions.active[myapp].time(0) } < 123000)) | ( {TRIGGER.VALUE}=1 & {Appserver:sessions.active[myapp].min(300)}<0 & ({Appserver:sessions.active[myapp].time(0)} < 103000 | {Appserver:sessions.active[myapp].time(0) } > 123000) ) The first three lines are identical to the trigger defined before. This time there is one more complex condition, as follows: The trigger is in a PROBLEM state (see the note about the TRIGGER.VALUE macro) The number of sessions is less than zero (this can never be true) We are outside the target hours (the last two lines are the opposite of those defining the time frame preceding it) The TRIGGER.VALUE macro represents the current value of the trigger expressed as a number. A value of 0 means OK, 1 means PROBLEM, and 2 means UNKNOWN. The macro can be used anywhere you could use an item.function pair, so you'll typically enclose it in curly brackets. As you've seen in the preceding example, it can be quite useful when you need to define different thresholds and conditions depending on the trigger's status itself. The condition about the number of sessions being less than zero makes sure that outside the target hours, if the trigger was in a PROBLEM state, the whole expression will evaluate to false anyway. False means the trigger is switching to an OK state. Here, you have not only made a correlation between an item value and a window of time to generate an event, but you have also made sure that the event will always spin down gracefully instead of potentially going out of control. Another interesting way to build a trigger is to combine different items from the same hosts, or even different items from different hosts. This is often used to spot incongruities in your systems' state that would otherwise be very difficult to identify. An obvious case could be that of a server that serves content over the network. Its overall performance parameters may vary a lot depending on a great number of factors, and so it would be very difficult to identify sensible trigger thresholds that wouldn't generate a lot of false positives, or even worse, missed events. What may be certain though is that if you see a high CPU load while network traffic is low, then you may have a problem, as shown in the following code: {Alpha:system.cpu.load[all,avg5].last(0)} > 5 & {Alpha:net.if.total[eth0].avg(300)} < 1000000 An even better example would be the necessity to check for hanging or freezed sessions in an application. The actual way to do it would depend a lot on the specific implementation of the said application, but for illustrative purposes, let's say that a frontend component keeps a number of temporary session files in a specific directory, while the database component populates a table with the session data. Even if you have created items on two different hosts to keep track of these two sources of data, each number taken alone will certainly be useful for trending analysis and capacity planning, but they need to be compared to check if something's wrong in the application's workflow. Assuming that we have previously defined a local command on the frontend's Zabbix agent that will return the number of files in a specific directory, and an odbc item on the database host that will query the DB for the number of active sessions, we could then build a trigger that compares the two values and report a PROBLEM state if they don't match: {Frontend:dir.count[/var/sessions].last(0)} # {Database:sessions.count.last(0)} The # term in the expression is the not equal operator. Aggregated and calculated items can also be very useful for building effective triggers. The following one will make sure that the ratio between active workers and the available servers doesn't drop too low in a grid or cluster: {ZbxMain:grpsum["grid", "proc.num[listener]", last, 0].last(0)} / {ZbxMain:grpsum["grid", "agent.ping", last, 0].last(0)} < 0.5 All these examples should help drive home the fact that once you move beyond checking for simple thresholds with single item values, and start correlating different data sources together in order to have more sophisticated and meaningful triggers, there is virtually no end to all the possible variations of trigger expressions that you can come up with. By identifying the right metrics and combining them in various ways, you can pinpoint very specific aspects of your systems' behavior; you can check log files together with the login events and network activity to track down possible security breaches, compare a single server performance with the average server performance in the same group to identify possible problems in service delivery, and much more. This is, in fact, one of Zabbix's best kept secrets that really deserves more publicity; its triggering system is actually a sophisticated correlation engine that draws its power from a clear and concise method to construct expressions as well as from the availability of a vast collection of both current and historical data. Spending a bit of your time studying it in detail, and coming up with interesting and useful triggers tailor-made for your needs will certainly pay you back tenfold, as you will end up not only with a perfectly efficient and intelligent monitoring system, but also with a much deeper understanding of your environment. Managing the trigger dependencies It's quite common that the availability of a service or a host doesn't depend only on the said host in itself, but also on the availability of any other machine that may provide connectivity to it. For example, if a router goes down isolating an entire subnet, you would still get alerts about all the hosts in the said network that will suddenly be seen as unavailable from Zabbix's point of view, even if it's really the router's fault. A dependency relationship between the router and the hosts behind it would help alleviate the problem, because it would make the server skip any trigger check for the hosts in the subnet, should the router become unavailable. While Zabbix doesn't support the kind of host-to-host dependencies that other systems do, it does have a trigger-to-trigger dependency feature that can largely perform the same function. For every trigger definition, you can specify a different trigger upon which your new trigger is dependent. If the parent trigger is in a PROBLEM state, the trigger you are defining won't be checked, until the parent returns to an OK state. This approach is certainly quite flexible and powerful, but it also has a couple of downsides. The first one is that one single host can have a significant number of triggers, so if you want to define a host-to-host dependency, you'll need to update every single trigger, which may prove to be quite a cumbersome task. You can of course, rely on the mass update feature of the web frontend as a partial workaround. A second problem is that you won't be able to look at a host definition and see that there is a dependency relationship with another host. Short of looking at a host's trigger configuration, there's simply no easy way to display or visualize this kind of relationship in Zabbix. A distinct advantage of having a trigger-level dependency feature is that you can define dependencies between single services on different hosts. As an example, you could have a database that serves a bunch of web applications on different web servers. If the database is unavailable, none of the related websites will work, so you may want to set up a dependency between the web monitoring triggers and the availability of the database. On the same servers, you may also have some other service that relies on a separate license server, or an identity and authentication server. You could then set up the appropriate dependencies, so that you could end up having some triggers depend on the availability of one server, and other triggers depend on the availability of another one, all in the same host. While this kind of configuration can easily become quite complex and difficult to maintain efficiently, a select few, well-placed dependencies can help cut down the amount of redundant alerts in a large environment. This in turn would help you focus immediately on the real problems where they arise, instead of having to hunt them down in a long list of trigger alerts.
Read more
  • 0
  • 0
  • 12056

article-image-introduction-vmware-horizon-mirage
Packt
17 Dec 2013
12 min read
Save for later

An Introduction to VMware Horizon Mirage

Packt
17 Dec 2013
12 min read
(For more resources related to this topic, see here.) What is Horizon Mirage? Horizon Mirage is a Windows desktop image management solution that centralizes a copy of each desktop image onto the Horizon Mirage Server infrastructure hosted in the datacenter. Apart from copying the image, Horizon Mirage also separates and categorizes it into logical layers. It's like adding a level of abstraction but without a hypervisor. These layers fall into two categories: those owned and managed by the end user, and those owned and managed by the IT department. This allows the IT managed layers, such as the operating system, to be independently updated while leaving the end users' files, profiles, and applications which they have installed all intact. These layers are continuously synchronized with the image in the datacenter, creating either full desktop snapshots or snapshots based on the upload policy applied to that particular device. These snapshots are backed up and ready for recovery or rolled back in case of failure of the endpoint device. So, the question that I get asked all the time is, "How is this different from VDI, and does that mean I don't need Horizon View anymore?" To answer this question there are a couple of points to raise. Firstly, Horizon Mirage does not require a hypervisor; it's an image management tool that can manage an image on a physical desktop PC or laptop. In fact, one of the use cases for Mirage is to provide a user with an IT-managed Windows desktop when there is limited connectivity or bandwidth between the datacenter and the local site, or the end user needs to work offline. The latest version of Horizon Mirage (4.3) launched on 19 November, 2013 also supports a managed image running as a persistent VDI desktop on Horizon View. To summarize, Horizon Mirage has the following three key areas it will deliver against: Horizon View desktops allowing management of VDI-based desktop images Physical desktop and laptop image management and backup and recovery for Microsoft Windows-based endpoints The Bring Your Own Device (BYOD) feature delivering a virtual Windows desktop machine onto a device running VMware Fusion Professional or VMware Workstation The following diagram illustrates the three areas of Horizon Mirage integration: The second and the biggest difference is where the image executes. By that I mean where does that desktop actually run? In a VDI environment, the desktop runs as a virtual machine centrally on a server in the datacenter—central management and central execution. In a Horizon Mirage deployment, the desktop is a physical endpoint device, and so it runs either natively or on that device—central management and local execution. The following diagram shows how Horizon Mirage executes locally and Horizon View executes centrally: Horizon Mirage terminologies and naming conventions Before we start to describe some of the use cases and how Horizon Mirage works, it's worth spending five minutes on covering some of the terminologies used. Endpoint In this context, an endpoint refers to an end user's device that is being managed by Mirage; so, in this case, it can either be a Windows desktop PC/laptop or a virtual instance of Windows running inside VMware Workstation or Fusion Professional. Centralized Virtual Desktop (CVD) The name CVD is a bit misleading really, because the desktop is not actually a virtual machine in the true sense of a VM running on a hypervisor. It more than likely refers to the level of abstraction used in creating the different layers of a desktop image. A CVD is a centralized copy or backup of a desktop or laptop machine that has been copied onto the Horizon Mirage Server in the datacenter. The CVD comprises the following core components: Base layers Driver profiles User-installed applications Machine states User settings and data Application layers Collections A collection is a logical grouping of similar endpoints or CVDs. This could be based on departmental machines, for example, the machines used by the Sales and Marketing departments. Collections can be static or dynamic. Reference CVD A reference CVD or reference machine is effectively the centralized copy of the endpoint that you use to build your "gold image" or "master image". It is used to create your base layers. These base layers are then deployed to a user's CVD which in turn synchronizes with the endpoint. All of your endpoints will now be running the same base layer, that is, the core operating systems and applications. Base layer A base layer is effectively a template from which to build a desktop. By removing any existing identity information, you are able to centrally deploy a base layer to multiple endpoints. A base layer comprises the core operating system, service packs, patches, and any core application. It is captured from a reference CVD. The best practice is to have as few base layers as possible. The ideal solution is being able to have just one single base layer for all endpoints. Application layer An application layer is a feature introduced in Version 4.0 that allows applications to be captured and deployed as separate layers. This allows you to manage and deliver applications independent of the base layer by assigning them to a user's CVD. Driver library / driver profile The driver library is where the Horizon Mirage Server stores the drivers from the different hardware vendors/makes/models of endpoints you have in your environment. The best practice is to download these directly from the vendor's website or driver DVD. A driver profile will contain details of all the drivers required for a particular piece of hardware. For example, you may have a driver profile for a Dell Latitude E6400 containing all the relevant drivers for that particular hardware platform. Managing drivers separately effectively decouples the base layer from the hardware, allowing it to build base layers that are independent of the endpoint hardware. It also means that driver conflicts are prevented when you refresh or migrate users to new or different hardware platforms. Hardware-specific device drivers are stored in the driver library and correct drivers are automatically applied to endpoints based on a set of rules that you create to match drivers to endpoints. The driver library can also detect missing or broken drivers on endpoints and fix them; however, it does not upgrade or take other actions on existing healthy drivers. Single Instance Store (SIS) The SIS contains the deduplicated data from all the uploaded CVDs, including operating systems, applications, and user files/data. It significantly reduces the storage requirements for CVDs, because it only holds one copy of each unique file. For example, if you centralize a Windows 7 endpoint which is 100 GB in size, the first upload will be 100 GB. Any subsequent uploads will only store the files that are different; so, in this case, if the second endpoint is also Windows 7, those files that are already stored will not be copied and, instead, pointers to those files will be created. So, in this example, maybe only 200 MB will be copied. The Horizon Mirage Management Server will show you the dedupe ratio for a centralized CVD. Horizon Mirage use cases In this section, we are going to cover, at a high level, some of the key use cases for Horizon Mirage. These are reflected in the Horizon Mirage Common Wizards page in the Management Server. I have broken these down into three categories: manage, migrate, and protect. Manage These features and components are all about delivering image management to your endpoint devices. Endpoint repair As the user's desktop is backed up in the datacenter, it's very easy to replace missing or corrupt files from the backed up image down to the endpoint device. This could be fixing a single file, application, or directory folder, or a complete restore of the endpoint. For example, a user accidentally deletes the Excel executable file and Excel now fails to load. The IT helpdesk can compare the image in the datacenter with the current state of the endpoint and work out that it's the Excel.exe file that is missing. This file will now be copied back to the endpoint and Excel is now up and running again. Single image management With Horizon Mirage you have the ability to create a layered approach to the operating environment by abstracting operating systems, applications, drivers, user data, and so on. This allows you to manage fewer images; in fact, the idea (in Horizon Mirage-speak) is that you have only one core operating system image or base layer. To build a complete endpoint, you assign any additional layers to a user's CVD, for example, assigning an application layer or driver profile. The layers are merged together and then synchronized with the endpoint device. It's like ordering a pizza. You start with the base, choose your toppings, bake it, and then it gets delivered to you. Application layering A new feature in Horizon Mirage is the ability to deliver an application as an individual layer. Application layers can be added to a user's CVD to create a complete desktop with the correct applications for the user based on their entitlement or the department that they work in. For those familiar with VMware ThinApp and the capturing process, Horizon Mirage captures an application layer in a similar way; however, Mirage does not build a virtual bubble like ThinApp. A Horizon Mirage application layer natively installs the application onto the endpoint device, so you first need to make sure the application is compatible with the operating system. Remote office management with Mirage Branch Reflectors Remote office locations have always been a problem for a traditional VDI solution because connectivity is usually limited or, in some cases, non-existent. So how can you deliver a centralized image with limited connectivity or slow WAN connections? With the Branch Reflectors you can "nominate" a desktop PC in the remote location to act as an intermediary between the local endpoints and the datacenter. The local endpoints connect locally to a Branch Reflector rather than the Horizon Mirage Server and, in turn, the Branch Reflector synchronizes with the datacenter, downloading only the differences between the IT-managed layers and the local endpoints. These newly built layers can then be distributed to the local endpoints. One thing to remember is that this feature does not back up the endpoint devices. It is purely for updating an image and so, for example, is ideal for remotely migrating an operating system. Migrate The second category, migrate, covers two migration areas, one for the desktop operating system and the second for hardware refresh projects or migrating between platforms. Windows XP / Windows Vista to Windows 7 Probably the most important feature of Horizon Mirage today is its ability to migrate operating systems, especially as we are rapidly approaching April 8, 2014 when Windows XP goes end-of-support. By using the layered approach to desktop images, Mirage is able to manage the operating system as a separate layer and can therefore update this layer while leaving the user data, profile, and settings all in place. The migration process is also less intrusive to the end user because the files are copied in the background, keeping the user downtime to complete the migration to a minimum. Hardware refresh Similar to the way that Horizon Mirage can migrate an operating system using a layered approach, it can also manage drivers as a separate layer. This means that Horizon Mirage can also be used if you are refreshing your hardware platform, allowing you to build specific driver profiles to match different hardware models from multiple vendors. It also means that, if your endpoint device became corrupt, unusable, or was even stolen, you could replace it with something entirely different, yet still use your same image. Protect The third and final category is protection. This is something that customers don't typically deploy for their desktop and laptop estates. It's usually left to the user to make sure their machine is backed up and protected. Centralized endpoint backup By installing the Horizon Mirage Client onto an endpoint, meaning that the endpoint will now be managed by Horizon Mirage, the first thing that happens is that the endpoint is copied to the Horizon Mirage Server in the datacenter in the form of a CVD for that endpoint/user. In addition to this, Horizon Mirage can create snapshots of the image and create points in time from which to roll back. Desktop recovery Backing up desktops is only half the story; you also need to think about restoring. Horizon Mirage offers the option of restoring specific layers, while preserving the remaining layers. You can restore an endpoint to a previous snapshot without overwriting user data. If a computer is stolen, damaged, or lost, you can restore the entire image to a replacement desktop computer or laptop. It doesn't even need to be the same make and model. Or, you could just select which layers to restore. For example, if a particular application became corrupted, you could just replace that application layer. In this use case, it doesn't just apply to the physical machines. You could restore a physical computer to a virtual desktop machine either temporarily or as a permanent migration, maybe as a stepping-stone to deploying a full VDI solution. Summary In this article we learned about what Horizon Mirage is and the terminologies used along with the three use case categories: Manage, Migrate, and Protect. Resources for Article: Application Packaging in VMware ThinApp 4.7 Essentials [Article] VMware View 5 Desktop Virtualization [Article] Windows 8 with VMware View [Article]
Read more
  • 0
  • 0
  • 8130

article-image-saying-hello-unity-and-android
Packt
17 Dec 2013
21 min read
Save for later

Saying Hello to Unity and Android

Packt
17 Dec 2013
21 min read
Understanding what makes Unity great Perhaps the greatest feature of Unity is how open-ended it is. Nearly all game engines currently on the market are limited in what one can build. It makes perfect sense but it can limit the capabilities of a team. The average game engine has been highly optimized for creating a specific game type. This is great if all you plan on making is the same game again and again. When one is struck with inspiration for the next great hit, only to find that the game engine can't handle it and everyone has to retrain in a new engine or double the development time to make it capable, it can be quite frustrating. Unity does not suffer this problem. The developers of Unity have worked very hard to optimize every aspect of the engine, without limiting what types of games can be made. Everything ranging from simple 2D platformers to massive online role-playing games is possible in Unity. A development team that just finished an ultra-realistic first-person shooter can turn right around and make 2D fighting games without having to learn an entirely new system. Being so open ended does, however, bring a drawback. There are no default tools optimized for building that perfect game. To combat this, Unity grants the ability to create any tool one can imagine, using the same scripting that creates the game. On top of that, there is a strong community of users that have supplied a wide selection of tools and pieces, both free and paid, to be quickly plugged in and used. This results in a large selection of available content, ready to jump-start you on your way to the next great game. When many prospective users look at Unity, they think that because it is so cheap, it is not as good as an expensive AAA game engine. This is simply not true. Throwing more money at the game engine is not going to make a game any better. Unity supports all of the fancy shaders, normal maps, and particle effects you could want. The best part is, nearly all of the fancy features you could want are included in the free version of Unity and 90 percent of the time beyond that, one does not need to even use the Pro only features. One of the greatest concerns when selecting a game engine, especially for the mobile market, is how much girth it will add to the final build size. Most are quite hefty. With Unity's code stripping, it becomes quite small. Code stripping is the process by which Unity removes every extra little bit of code from the compiled libraries. A blank project, compiled for Android, that utilizes full code stripping ends up being around 7 megabytes. Perhaps one of the coolest features of Unity is the multi-platform compatibility. With a single project one can build for several different platforms. This includes the ability to simultaneously target mobile, PC, and consoles. This allows one to focus on real issues, such as handling inputs, resolution, and performance. In the past, if a company desired to deploy their product on more than one platform, they had to nearly double the development costs in order to essentially reprogram the game. Every platform did, and still does, run by its own logic and language. Thanks to Unity, game development has never been simpler. We can develop games using simple and fast scripting, letting Unity handle the complex translation to each platform. There are of course several other options for game engines. Two major ones that come to mind are cocos2d and Unreal Engine. While both are excellent choices, we can always find them to be a little lacking in certain respects. The engine of Angry Birds, cocos2d, could be a great choice for your next mobile hit. However, as the name suggests, it is pretty much limited to 2D games. A game can look great in it, but if you ever want that third dimension, it can be tricky to add. A second major problem with cocos2d is how bare bones it is. Any tool for building or importing assets needs to be created from scratch, or they need to be found. Unless you have the time and experience, this can seriously slow down development. Then there is the staple of major game development, Unreal Engine. This game engine has been used successfully by developers for many years, bringing great games to the world; Unreal Tournament and Gears of War not the least among them. These are both, however, console and computer games, which is the fundamental problem with the engine. Unreal is a very large and powerful engine. Only so much optimization can be done for mobile platforms. It has always had the same problem; it adds a lot of girth to a project and its final build. The other major issue with Unreal is its rigidity in being a first-person shooter engine. While it is technically possible to create other types of games in it, such tasks are long and complex. A strong working knowledge of the underlying system is a must before achieving such a feat. All in all, Unity definitely stands strong among the rest. But these are still great reasons for choosing Unity for game development. Projects can look just as great as AAA titles. Overhead and girth in the final build is small and very important when working on mobile platforms. The system's potential is open enough to allow you to create any type of game you might want, where other engines tend to be limited to a single type of game. And should your needs change at any point in the project's life cycle, it is very easy to add, remove, or change your choice of target platforms. Understanding what makes Android great With over 30-million devices in the hands of users, why would you not choose the Android platform for your next mobile hit? Apple may have been the first one out of the gate with their iPhone sensation, but Android is definitely a step ahead when it comes to smartphone technology. One of its best features is its blatant ability to be opened up so you can take a look at how the phone works, both physically and technically. One can swap out the battery and upgrade the micro SD card, should the need arise. Plugging the phone into a computer does not have to be a huge ordeal; it can simply function as removable storage media. From the point of view of cost of development, the Android market is superior as well. Other mobile app stores require an annual registration fee of about 100 dollars. Some also have a limit on the number of devices that can be registered for development at one time. The Google Play market has a one-time registration fee, and there is no concern about how many or what type of Android devices you are using for development. One of the drawbacks about some of the other mobile development kits is that you have to pay an annual registration fee before you have access to the SDK. With some, registration and payment are required before you can view their documentation. Android is much more open and accessible. Anybody can download the Android SDK for free. The documentation and forums are completely viewable without having to pay any fee. This means development for Android can start earlier, with device testing being a part of it from the very beginning. Understanding how Unity and Android work together Because Unity handles projects and assets in a generic way, there is no need to create multiple projects for multiple target platforms. This means that you could easily start development with the free version of Unity and target personal computers. Then, at a later date, you can switch targets to the Android platform with the click of a button. Perhaps, shortly after your game is launched, it takes the market by storm and there is a great call to bring it to other mobile platforms. With just another click of the button, you can easily target iOS without changing anything in your project. Most systems require a long and complex set of steps to get your project running on a device. For the first application, we will be going through that process because it is important to know about it. However, once your device is set up and recognized by the Android SDK, a single-button click will allow Unity to build your application, push it to a device, and start running it. There is nothing that has caused more headaches for some developers than trying to get an application on a device. Unity makes it simple. With the addition of a free Android application, Unity Remote, it is simple and easy to test mobile inputs without going through the whole build process. While developing, there is nothing more annoying than waiting for 5 minutes for a build every time you need to test a minor tweak, especially in the controls and interface. After the first dozen little tweaks the build time starts to add up. Unity Remote makes it simple and easy to test it all without ever having to hit the Build button. These are the big three: generic projects, a one-click build process, and Unity Remote. We could, of course, come up with several more great ways in which Unity and Android can work together. But these three are the major time and money savers. You could have the greatest game in the world but, if it takes 10 times as long to build and test, what is the point? Differences between Pro and Basic Unity comes with two licensing options, Pro and Basic, which can be found at https://store.unity3d.com. In order to follow, Unity Basic is all that is required. If you are not quite ready to spend the $3,000 required to purchase a full Unity Pro license with the Android add-on, there are other options. Unity Basic is free and comes with a 30-day free trial of Unity Pro. This trial is full and complete, just as if one has purchased Unity Pro. It is also possible to upgrade your license at a later date. Where Unity Basic comes with mobile options for free, Unity Pro requires the purchase of Pro add-ons for each of the mobile platforms. License comparison overview License comparisons can be found at http://unity3d.com/unity/licenses. This section will cover the specific differences between Unity Android Pro and Unity Android Basic. We will explore what the feature is and how useful it is. NavMeshes, Pathfinding, and crowd Simulation: This feature is Unity's built-in pathfinding system. It allows characters to find their way from point to point around your game. Just bake your navigation data in the editor and let Unity take over at runtime. This feature is great if you don't have the ability or inclination to program a pathfinding system yourself. There is a whole slew of tutorials online about how to program pathfinding and do crowd simulation. It is completely possible to do all of this in Unity Basic; you just need to provide the tools yourself. LOD Support: LOD(Level-of-detail) lets you control how complex a mesh is, based on its distance from the camera. When the camera is close to an object, render a complex mesh with a bunch of detail in it. When the camera is far from that object, render a simple mesh, because all that detail is not going to be seen anyway. Unity Pro provides a built-in system to manage this. However, this is another system that could be created in Unity Basic. Whether using Pro or not, this is an important feature for game efficiency. By rendering less complex meshes at a distance, everything can be rendered faster, leaving more room for awesome gameplay. Audio Filter: Audio filters allow you to add effects to audio clips at runtime. Perhaps you created gravel footstep sounds for your character. Your character is running, and we can hear the footsteps just fine, when suddenly they enter a tunnel and a solar flare hits, causing a time warp and slowing everything down. Audio filters would allow us to warp the gravel footstep sounds to sound like they are coming from within a tunnel and are slowed by a time warp. Of course, you could also just have the audio guy create a new set of tunnel gravel footsteps in the time warp sounds. But this might double the amount of audio in your game and limits how dynamic we can be with it at runtime. We either are or are not playing the time warp footsteps. Audio filters would allow us to control how much time warp is affecting our sounds. Video Playback and Streaming: When dealing with complex or high-definition cut scenes, being able to play a video becomes very important. Including them in a build especially with a mobile target can require a lot of space. This is where the streaming part of this feature comes in. This feature not only lets us play video, it also lets us stream that video from the internet. There is, however, a drawback to this feature. On mobile platforms, the video has to go through the device's builtin, video-playing system. This means the video can only be played full-screen and cannot be used as a texture. Theoretically, though, you could break your video into individual pictures for each frame and flip through them at runtime, but this is not recommended for build size and video quality reasons. Fully Fledged Streaming with Asset Bundles: Asset bundles are a great feature provided by Unity Pro. They allow you to create extra content and stream it to the users, without ever requiring an update to the game. You could add new characters, levels, or just about any other content you can think of. Their only drawback is that you cannot add more code. The functionality cannot change, but the content can. This is one of the best features of Unity Pro. 100,000 Dollar Turnover: This one isn't so much a feature as it is a guideline. According to Unity's End User License Agreement, the basic version of Unity cannot be licensed by any group or individual that made $100,000 in the previous fiscal year. This basically means, if you make a bunch of money, you have to buy Unity Pro. Of course, if you are making that much money, you can probably afford it without issue. That is the view of Unity at least, and the reason why it is there. Mecanim: IK Rigs: Unity's new animation system, Mecanim, supports many exciting new features, one of which is IK. If you are unfamiliar with the term, IK allows one to define the target point of an animation and let the system figure out how to get there. Imagine you have a cup sitting on a table and a character that wants to pick it up. You could animate the character to bend over and pick it up, but what if the character is slightly to the side? Or any number of other slight offsets that a player could cause, completely throwing off your animation. It is simply impractical to animate for every possibility. With IK, it hardly matters that the character is slightly off. We just define the goal point for the hand and leave the arm to the IK system. It calculates for us how the arm needs to move in order to get the hand to the cup. Another fun use is making characters look at interesting things as they walk around a room. A guard could track the nearest person, the player character could look at things that they can interact with, or a tentacle monster could lash out at the player without all the complex animation. This will be an exciting one to play with. Mecanim: Sync Layers & Additional Curves Sync layers, inside Mecanim, allow us to keep multiple sets of animation states in time with each other. Say you have a soldier that you want to animate differently based on how much health he has. When at full health, he walks around briskly. After a little damage, it becomes more of a trudge. If health is below half, a limp is introduced to his walk. And when almost dead, he crawls along the ground. With sync layers, we can create one animation state machine and duplicate it to multiple layers. By changing the animations and syncing the layers, we can easily transition between the different animations while maintaining the state machine. Additional curves are simply the ability to add curves to your animations. This means we can control various values with the animation. For example, in the game world, when a character picks up their feet for a jump, gravity will pull them down almost immediately. By adding an extra curve to that animation, in Unity, we can control how much gravity is affecting the character, allowing them to actually get in the air when jumping. This is a useful feature for controlling such values right alongside the animations, but one could just as easily create a script that holds and controls the curves. Custom Splash Screen: Though pretty self-explanatory, it is perhaps not immediately evident why this feature is specified, unless you have worked with Unity before. When an application built in Unity initializes on any platform, it displays a splash screen. In Unity Basic this will always be the Unity logo. By purchasing Unity Pro, you can substitute the Unity logo with any image you want. Build Size Stripping: This is an important feature for mobile platforms. Build size stripping removes all of the excess from your final build. Unity does a very good job at only including the assets that you have created that are used in the final build. With the stripping, it also only includes the parts of the engine itself that are used in the game. This is of great use when you absolutely have to get under that limit for downloading from the cell towers. On the other hand, you could create something similar to the asset bundles. Just let the users buy the framework, and download the assets later. Realtime Directional Shadows: Lights and shadows add a lot to the mood of a scene. This feature allows us to go beyond blob shadows and use realistic looking shadows. This is all well and good if you have the processing space for it. Most mobile devices do not. This feature should also never be used for static scenery. Instead, use static lightmaps, which is what they are for. But if you can find a good balance between simple needs and quality, this could be the feature that creates the difference between an alright and an awesome game. HDR, tone mapping: HDR(High Dynamic Range) and tone mapping allow us to create more realistic lighting effects. Standard rendering uses values from zero to one to represent how much of each color in a pixel is on. This does not allow for a full spectrum of lighting options to be explored. HDR lets the system use values beyond this range and process them using tone mapping to create better effects, such as a bright morning room or the bloom from a car window reflecting the sun. The downside of this feature is in the processor. The device can still only handle values between zero and one, so converting them takes time. Additionally, the more complex the effect, the more time it takes to render it. It would be surprising to see this used well on handheld devices, even in a simple game. Maybe the modern tablets could handle it. Light Probes: Light probes are an interesting little feature. When placed in the world, light probes figure out how an object should be lit. Then, as a character walks around, they tell it how to be shaded. The character is, of course, lit by the lights in the scene but there are limits on how many lights can shade an object at once. Light probes do all the complex calculations beforehand, allowing for better shading at runtime. Again, however, there are concerns about the processing power. Too little and you won't get a good effect; too much and there will be no processing left for playing the game. Lightmapping with Global Illumination and area lights: All versions of Unity support lightmaps, allowing for the baking of complex static shadows and lighting effects. With the addition of global illumination and area lights, you can add another touch of realism to your scenes. However, every version of Unity also lets you import your own lightmaps. This means, you could use some other program to render the lightmaps and import them separately. Static Batching: This feature speeds up the rendering process. Instead of spending time on each frame grouping objects for faster rendering, this allows the system to save the groups generated beforehand. Reducing the number of draw calls is a powerful step towards making a game run faster. That is exactly what this feature does. Render-to-Texture Effects: This is a fun feature, but of limited use. It simply allows you to redirect the rendering of the camera from going to the screen and instead go to a texture. This texture could then, in its most simple form, be put onto a mesh and act like a surveillance camera. You could also do some custom post processing, such as removing the color from the world as the player loses their health. However, that option could become very processor-intensive. Full-Screen Post-Processing Effects: This is another processor-intensive feature that probably will not make it into your mobile game. But you can add some very cool effects to your scene. Such as, adding motion blur when the player is moving really fast, or a vortex effect to warp the scene as the ship passes through a warped section of space. One of the best is using the bloom effect to give things a neon-like glow. Occlusion Culling: This is another great optimization feature. The standard camera system renders everything that is within the camera's view frustum, the view space. Occlusion culling lets us set up volumes in the space our camera can enter. These volumes are used to calculate what the camera can actually see from those locations. If there is a wall in the way, what is the point of rendering everything behind it? Occlusion culling calculates this and stops the camera from rendering anything behind that wall. Navmesh: Dynamic Obstacles and Priority: This feature works in conjunction with the pathfinding system. In scripts, we can dynamically set obstacles, and characters will find their way around them. Being able to set priorities means different types of characters can take different types of objects into consideration when finding their way around. A soldier must go around the barricades to reach his target. The tank, however, could just crash through, should it desire to. .Net Socket Support: This feature is only useful if you plan on doing fancy things over a user's network. Multiplayer networking is already supported in every version of Unity. The multiplayer that is available, though, does require a master server. With the use of sockets, one could create connections to other devices locally. Profiler and GPU profiling: This is a very useful feature. The profiler provides tons of information about how much load your game puts on the processor. With this information we can get right down into the nitty-gritties and determine exactly how long a script takes to process. Towards the end, though, we will also create a tool for determining how long specific parts of your code take to process. Script Access to Asset Pipeline: This is an alright feature. With full access to the pipeline, there is a lot of custom processing that can be done on assets and builds. The full range of possibilities are beyond our scope. But think of it as being able to tint all of the imported textures slightly blue. Dark Skin: This is entirely a cosmetic feature. Its point and purpose are questionable. But if a smooth, dark-skinned look is what you desire, this is the feature you want. There is an option in the editor to change it to the color scheme used in Unity Basic. For this feature, whatever floats your boat goes. Setting up the development environment Before we can create the next great game for Android, we need to install a few programs. In order to make the Android SDK work, we will first install the JDK. Then, we will be installing the Android SDK. After that is the installation of Unity. We then have to install an optional code editor. To make sure everything is set up correctly, we will connect to our devices and take a look at some special strategies if the device is a tricky one. Finally, we will install Unity Remote, a program that will become invaluable in your mobile development.
Read more
  • 0
  • 0
  • 2531

article-image-moving-your-application-production
Packt
16 Dec 2013
9 min read
Save for later

Moving Your Application to Production

Packt
16 Dec 2013
9 min read
(For more resources related to this topic, see here.) We will start by examining the Sencha Cmd compiler. Compiling with Sencha Cmd This section will focus on using Sencha Cmd to compile our Ext JS 4 application for deployment within a Web Archive (WAR) file. The goal of the compilation process is to create a single JavaScript file that contains all of the code needed for the application, including all the Ext JS 4 dependencies. The index.html file that was created during the application skeleton generation is structured as follows: <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>TTT</title> <!-- <x-compile> --> <!-- <x-bootstrap> --> <link rel="stylesheet" href="bootstrap.css"> <script src = "ext/ext-dev.js"></script> <script src = "bootstrap.js"></script> <!-- </x-bootstrap> --> <script src = "app.js"></script> <!-- </x-compile> --> </head> <body></body> </html> The open and close tags of the x-compile directive enclose the part of the index.html file where the Sencha Cmd compiler will operate. The only declarations that should be contained in this block are the script tags. The compiler will process all of the scripts within the x-compile directive, searching for dependencies based on the Ext.define, requires, or uses directives. An exception to this is the ext-dev.js file. This file is considered to be a "bootstrap" file for the framework and will not be processed in the same way. The compiler ignores the files in the x-bootstrap block and the declarations are removed from the final compiler-generated page. The first step in the compilation process is to examine and parse all the JavaScript source code and analyze any dependencies. To do this the compiler needs to identify all the source folders in the application. Our application has two source folders: Ext JS 4 sources in webapp/ext/src and 3T application sources in webapp/app. These folder locations are specified using the -sdk and -classpath arguments in the compile command: sencha –sdk {path-to-sdk} compile -classpath={app-sources-folder} page -yui -in{index-page-to-compile}-out {output-file-location} For our 3T application the compile command is as follows: sencha –sdk ext compile -classpath=app page -yui -in index.html-out build/index.html This command performs the following actions: The Sencha Cmd compiler examines all the folders specified by the -classpath argument. The -sdk directory is automatically included for scanning. The page command then includes all of the script tags in index.html that are contained in the x-compile block. After identifying the content of the app directory and the index.html page, the compiler analyzes the JavaScript code and determines what is ultimately needed for inclusion in a single JavaScript file representing the application. A modified version of the original index.html file is written to build/index.html. All of the JavaScript files needed by the new index.html file are concatenated and compressed using the YUI Compressor, and written to the build/all-classes.js file. The sencha compile command must be executed from within the webapp directory, which is the root of the application and is the directory containing the index.html file. All the arguments supplied to the sencha compile command can then be relative to the webapp directory. Open a command prompt (or terminal window in Mac) and navigate to the webapp directory of the 3T project. Executing the sencha compile command as shown earlier in this section will result in the following output: Opening the webapp/build folder in NetBeans should now show the two newly generated files: index.html and all-classes.js. The all-classes.js file will contain all the required Ext JS 4 classes in addition to all the 3T application classes. Attempting to open this file in NetBeans will result in the following warning: "The file seems to be too large to open safely...", but you can open the file in a text editor to see the following concatenated and minified content: Opening the build/index.html page in NetBeans will display the following screenshot: You can now open the build/index.html file in the browser after running the application, but the result may surprise you: The layout that is presented will depend on the browser, but regardless, you will see that the CSS styling is missing. The CSS files required by our application need to be moved outside the <!-- <x-compile> --> directive. But where are the styles coming from? It is now time to briefly delve into Ext JS 4 themes and the bootstrap.css file. Ext JS 4 theming Ext JS 4 themes leverage Syntactically Awesome StyleSheets (SASS) and Compass (http://compass-style.org/) to enable the use of variables and mixins in stylesheets. Almost all of the styles for Ext JS 4 components can be customized, including colors, fonts, borders, and backgrounds, by simply changing the SASS variables. SASS is an extension of CSS that allows you to keep large stylesheets well-organized; a very good overview and reference can be found at http://sass-lang.com/documentation/file.SASS_REFERENCE.html. Theming an Ext JS 4 application using Compass and SASS is beyond the scope of this book. Sencha Cmd allows easy integration with these technologies to build SASS projects; however, the SASS language and syntax is a steep learning curve in its own right. Ext JS 4 theming is very powerful and minor changes to the existing themes can quickly change the appearance of your application. You can find out more about Ext JS 4 theming at http://docs.sencha.com/extjs/4.2.2/#!/guide/theming. The bootstrap.css file was created with the default theme definition during the generation of the application skeleton. The content of the bootstrap.css file is as follows: @import 'ext/packages/ext-theme-classic/build/resources/ext-theme-classic-all.css'; This file imports the ext-theme-classic-all.css stylesheet, which is the default "classic" Ext JS theme. All of the available themes can be found in the ext/packages directory of the Ext JS 4 SDK: Changing to a different theme is as simple as changing the bootstrap.css import. Switching to the neptune theme would require the following bootstrap.css definition: @import 'ext/packages/ext-theme-neptune/build/resources/ext-theme-neptune-all.css'; This modification will change the appearance of the application to the Ext JS "neptune" theme as shown in the following screenshot: We will change the bootstrap.css file definition to use the gray theme: @import 'ext /packages/ext-theme-gray/build/resources/ext-theme-gray-all.css'; This will result in the following appearance: You may experiment with different themes but should note that not all of the themes may be as complete as the classic theme; minor changes may be required to fully utilize the styling for some components. We will keep the gray theme for our index.html page. This will allow us to differentiate the (original) index.html page from the new ones that will be created in the following section using the classic theme. Compiling for production use Until now we have only worked with the Sencha Cmd-generated index.html file. We will now create a new index-dev.html file for our development environment. The development file will be a copy of the index.html file without the bootstrap.css file. We will reference the default classic theme in the index-dev.html file as follows: <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>TTT</title> <link rel="stylesh eet" href="ext/packages/ext-theme-classic/build/resources/ext-theme-classic-all. css"> <link rel="stylesheet" href="resources/styles.css"> <!-- <x-compile> --> <!-- <x-bootstrap> --> <script src = "ext/ext-dev.js"></script> <script src = "bootstrap.js"></script> <!-- </x-bootstrap> --> <script src = "app.js"></script> <!-- </x-compile> --> </head> <body></body> </html> Note that we have moved the stylesheet definition out of the <!-- <x-compile> --> directive. If you are using the downloaded source code for the book, you will have the resources/styles.css file and the resources directory structure available. The stylesheet and associated images in the resources directory contain the 3T logos and icons. We recommend you download the full source code now for completeness. We can now modify the Sencha Cmd compile command to use the index-dev.html file and output the generated compile file to index-prod.html in the webapp directory: sencha –sdk ext compile -classpath=app page -yui -in index-dev.html-out index-prod.html This command will generate the index-prod.html file and the all-classes.js files in the webapp directory as shown in the following screenshot: The index-prod.html file references the stylesheets directly and uses the single compiled and minified all-classes.js file. You can now run the application and browse the index-prod.html file as shown in the following screenshot: You should notice a significant increase in the speed with which the logon window is displayed as all the JavaScript classes are loaded from the single all-classes.js file. The index-prod.html file will be used by developers to test the compiled all-classes.js file. Accessing the individual pages will now allow us to differentiate between environments: The logon window as displayed in the browser Page description The index.html page was generated by Sencha Cmd and has been configured to use the gray theme in bootstrap.css. This page is no longer needed for development; use index-dev.html instead. You can access this page at http://localhost:8080/index.html The index-dev.html page uses the classic theme stylesheet included outside the <!-- <x-compile> --> directive. Use this file for application development. Ext JS 4 will dynamically load source files as required. You can access this page at http://localhost:8080/index-dev.html The index-prod.html file is dynamically generated by the Sencha Cmd compile command. This page uses the all-classes.js all-in-one compiled JavaScript file with the classic theme stylesheet. You can access this page at http://localhost:8080/index-prod.html
Read more
  • 0
  • 0
  • 4159
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-magic
Packt
16 Dec 2013
7 min read
Save for later

The Magic

Packt
16 Dec 2013
7 min read
(For more resources related to this topic, see here.) Application flow In the following diagram, from the Angular manual, you find a comprehensive schematic depiction of the program flow inside Angular: After the browser loads the HTML and parses it into a DOM, the angular.js script file is loaded. This can be added before or at the bottom of the <body> tag, although adding it at the bottom is preferred. Angular waits for the browser to fire the DOMContentLoaded event. This is similar to the way jQuery is bootstrapped, as illustrated in the following code: $(document).ready(function(){ // do jQuery }) In the Angular.js file, towards the end, after the entire code has been parsed by the browser, you will find the following code: jqLite(document).ready(function() { angularInit(document, bootstrap); }); The preceding code calls the function that looks for various flavors of the ng-app directive that you can use to bootstrap your Angular application. ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'] Typically, the ng-app directive will be the HTML tag, but in theory, it could be any tag as long as there is only one of them. The module specification is optional and can tell the $injector service which of the defined modules to load. //index.html <!doctype html> <html lang="en" ng-app="tempApp"> <head> …... // app.js ….. angular.module('tempApp', ['serviceModule']) ….. In turn, the $injector service will create $rootscope, the parent scope of all Angular scopes, as the name suggests. This $rootscope is linked to DOM itself as a parent to all other Angular scopes. The $injector service will also create the $compile service that will traverse the DOM and look for directives. These directives are searched for within the complete list of declared Angular internal directives and custom directives at hand. This way, it can recognize directives declared as an element, as attributes, inside the class definition, or as a comment. Now that Angular is properly Bootstrapped, we can actually start executing some application code. This can be done in a variety of ways, shown as follows: In the initial examples, we started creating some Angular code with curly braces using some built-in Angular functions It is also possible to define a controller to control a specific part of the HTML page, as we have shown in the first tempCtrl code snippet We have also shown you how to use Angular's built-in router to manage your application using client-side routing As you can see, Angular extends the capabilities of HTML by providing a clever way to add new directives. The key ingredient here is the $injector service, which provides a way to look up for dependencies and create $rootscope. Different ways of injecting Let's look a bit more at how $injector does its work. Throughout all the examples in this book, we have used the array-style notation to define our controllers, modules, services, and directives. // app/ controllers.js tempApp.controller('CurrentCtrl', ['$scope', 'reading', function ($scope, reading) { $scope.temp = 17; ... This style is commonly referred to as annotation. Each injected value is annotated in the same order inside an array. You may have looked through the AngularJs website and may have seen different ways of defining functions. // angularJs home page JavaScript Projects example functionListCtrl($scope, Project) { $scope.projects = Project.query(); } So, what is the difference and why are we using another way of defining functions? The first difference you may notice is the definition of all the functions in the global scope. For reference, let's call this the simple injection method. The documentation states that this is a concise notation that really is only suited for demo applications because it is nothing but a potential clash waiting to happen. Any other JS library or framework you may have included could potentially have a function with the same name and cause your software to malfunction by executing this function instead of yours. After assigning the Angular module to a variable such as tempApp, we will chain the methods to that variable like we have done in this book so far; you could also just chain them directly as follows: angular.module('tempApp').controller('CurrentCtrl', function($scope) {}) These are essentially the same definitions and don't cause pollution in the global scope. The second difference that you may have noticed is in the way the dependencies are injected in the function. At the time of writing this book, most, if not all of the examples on the AngularJs website use the simple injection method. The dependencies are just parameters in the function definitions. Magically, Angular is able to figure out which parameter is what by the name because the order does not matter. So the preceding example could be rewritten as follows, and it would still function correctly: // reversedangularJs home page JavaScript Projects example functionListCtrl( Project, Scope ) { $scope.projects = Project.query(); } This is not a feature of the JavaScript language, so it must have been added by those smart Angular engineers. The magic behind this can be found in the injector. The parameters of the function are scanned, and Angular extracts the names of the parameters to be able to resolve them. The problem with this approach is that when you deploy a wonderful new application to production, it will probably be minified and even obfuscated. This will rename $scope and Project to something like a and b. Even Angular will then be unable to resolve the dependencies. There are two ways to solve this problem in Angular. You have seen one of them already, but we will explain it further. You can wrap the function in an array and type the names of the dependencies as strings before the function definition in the order in which you supplied them as arguments to the function. // app/ controllers.js tempApp.controller('CurrentCtrl', ['$scope', 'reading', function ($scope, reading) { $scope.temp = 17; ....... The corresponding order of the strings and the function arguments is significant here. Also, the strings should appear before the function arguments. If you prefer the definition without the array notation, there is still some hope. Angular provides a way to inform the injector service of the dependencies you are trying to inject. varCurrentCtrl = function($scope, reading) { $scope.temp = 17; $scope.save = function() { reading.save($scope.temp); } }; CurrentCtrl.$inject = ['$scope', 'reading']; tempApp.controller('CurrentCtrl', CurrentCtrl); As you can see, the definition is a bit more sizable, but essentially the same thing is happening here. The injector is informed by filling the $inject property of the function with an array of the injected dependencies. This is where Angular will then pick them up from. To understand how Angular accomplishes all of this, you should read this excellent blog post by Alex Rothenberg. Here, he explains how all of this works internally. The link to his blog is as follows: http://www.alexrothenberg.com/2013/02/11/the-magic-behind-angularjs-dependency-injection.html. Angular cleverly uses the toString() function of objects to be able to examine in which order the arguments were specified and what their names are. There is actually a third way to specify dependencies called ngmin, which is not native to Angular. It lets you use the simple injection method and parses and translates it to avoid minification problems. https://github.com/btford/ngmin Consider the following code: angular.module('whatever').controller('MyCtrl', function ($scope, $http) { ... }); ngmin will turn the preceding code into the following: angular.module('whatever').controller('MyCtrl', ['$scope','$http', function ($scope, $http) { ... }]);   Summary In this article, we started by looking at how AngularJS is bootstrapped. Then, we looked at how the injector works and why minification might ruin your plans there. We also saw that there are ways to avoid these problems by specifying dependencies differently. Resources for Article: Further resources on this subject: The Need for Directives [Article] Understanding Backbone [Article] Quick start – creating your first template [Article]
Read more
  • 0
  • 0
  • 2348

article-image-further-developments
Packt
16 Dec 2013
11 min read
Save for later

Further Developments

Packt
16 Dec 2013
11 min read
(For more resources related to this topic, see here.) This article zooms out to the level of abstraction to take a little peak into the future by discussing platform services on top of IBM® SmartCloud® Enterprise, acquisitions, and other valuable sources of information. With IBM® SmartCloud® Enterprise, you gain access to both infrastructure services (IaaS) and platform services (PaaS), all in one cloud solution. The platform services, available through the SCE management console under Service Instances, are all bundled under the name of IBM SmartCloud Application Services. Although we cannot fully predict the future, there are some valuable sources of information that I want to share with you so you can stay updated on the latest changes and announcements for future developments. Second, there are some patterns and trends that allow us to look into our crystal ball. IBM® SmartCloud® Application Services IBM® SmartCloud® Application Services, the platform services layer on top of IBM ® SmartCloud® Enterprise, was introduced in December 2012. It delivers a collaborative, cloud-based environment that supports the full lifecycle of accelerated application development, deployment, and delivery. It provides two separate—but complementary—services: Collaborative Lifecycle Management Service and IBM® SmartCloud® Application Workload Service: Collaborative Lifecycle Management Service(CLMS) is a set of seamlessly integrated Rational® tools which provides a real-time cloud-based collaborative environment for accelerated application development and delivery as a platform service. It is designed to help coordinate software development activities throughout the lifecycle of an application, from requirements tracking through design, implementation, build, test, deployment, and maintenance. IBM® SmartCloud® Application Workload Service (SCAWS) allows us to use design patterns. A pattern consists of proven best practices and expertise for complex system tasks that have been captured, lab-tested, and optimized into a deployable form. These patterns can be very powerful because they can include policy-based automated scaling and easy duplication between IBM public and private cloud environments. The IBM SmartCloud® Enterprise Monthly Cost Estimator, supports all IBM® SmartCloud® Application Services prices and content. To learn more on its features and how get started on running your first service instances: pic.dhe.ibm.com/infocenter/scasic/v1r0m0/index.jsp Improving software delivery with DevOps To support DevOps, collaborative tools are needed to support the agile service delivery approach, hence accelerating application deployment from weeks to minutes. When we combine the functionality offered by CLMS and SCAWS together, this is exactly what we get. We get one integrated DevOps solution that promotes communication, collaboration, and integration between software developers and IT operations to more rapidly produce quality software products and services. The name DevOps is derived from a combination of the two words development and operations. DevOps is more than a new development methodology like agile software development; it's about communication and collaboration between boththe two earlier stated stakeholders and the business. It is mainly targeted at product delivery, quality testing, feature development, and maintenance releases in order to improve reliability, security, and faster development and deployment cycles. Download this complementary e-book to gain a better understanding of DevOps and learn how it can improve the IT processes in your organization: ow.ly/lCGGz Valuable sources of information IBM® SmartCloud® Enterprise and Application Services Staying up-to-date with the latest IBM® SmartCloud® Enterprise (and Application Services) developments and announcements is vital for knowing what you can expect in the near future. The three most important sources of information are: The SCE management console, specifically on the Support page, where many resources are directly available or just one click away in the Documentation Library, Video Library, and Asset Catalog. The developerWorks® website, the IBM technical resource and professional network for the developer and IT professional, offers great in-depth articles on many of the capabilities that IBM® SmartCloud® Enterprise has. It can be accessed at www.ibm.com/developerworks. The Thoughts on Cloud blog is also a great place to see what's happening and what can be done with IBM and IBM Business Partner solutions. As with the developerWorks website, the information provided here covers more about IBM® SmartCloud® Enterprise, which gives us a broader perspective on what's happening with IBM and cloud computing. It is available at thoughtsoncloud.com. There is also IBM SmartCloud Enterprise newsletter containing a wealth of information on new features, use-cases, and other news. You can subscribe to these, and more, newsletters via the IBM eNewsletter Subscription Services webpage. Then there is the IBM SmartCloud Enterprise Developers Group. This is a technical community composed of individuals interested in the application programming interfaces (APIs) of IBM® SmartCloud® Enterprise. The group includes IBMers and non-IBMers and covers how the APIs can be used to automate processes and build solutions that integrate with IBM® SmartCloud® Enterprise. It is available at www.ibm.com/developerworks/community/blogs/iaas_cloud. IBM Innovation Center events Additionally there are the IBM Innovation Center events, which offer a wide range of no-charge workshops, seminars, and briefings conducted by highly trained subject matter experts. These events help you build technical skills, learn how to market and sell more effectively with IBM, and connect with Business Partners. Some of the virtual events focus on the new possibilities of IBM® SmartCloud® solutions, and are complementary. Global Technology Outlook The Global Technology Outlook (GTO) is IBM Research's vision of the future for information technology (IT) and its implications on industries. This annual exercise highlights emerging software, hardware, and services technology trends that are expected to significantly impact the IT sector in the next 3-10 years. The research document can be downloaded from www.zurich.ibm.com/pdf/isl/infoportal/Global_Technology_Outlook_2013.pdf. IBM Academy of Technology Lastly there is the IBM Academy of Technology (AoT) which, as the name suggests, consists of almost one thousand of IBM's technical leaders. The academy develops a rich technical agenda each year which consists of studies, conferences, and consultancies. More importantly, the academy also produces a series of TechNotes which explore various areas of current and emerging technology. The TechNotes can be found at www-03.ibm.com/ibm/academy/technotes/technotes.shtml. A glimpse into our crystal ball When looking at the version history of IBM® SmartCloud® we can clearly see a pattern of delivering major releases twice a year, more specifically in May and December. Since the May 2013 release has just been announced and implemented—at the time of writing—it can be expected that the next major release will be announced and implemented in December 2013. In terms of functionality, let's look at what announcements there have been on the IBM® SmartCloud® strategy and which trends there are in the marketplace. Platform services Platform as a service is clearly expanding the range of options you have from the cloud. We can see these IBM products and service developments; just look at the landing page of IBM for platform services— www.ibm.com/cloud-computing/us/en/paas.html—but also on almost all other major cloud service providers. Specifically, we want to mention the platform services—IBM® SmartCloud® Application Services and IBM® SmartCloud® for SAP Applications—that IBM is building on top of the infrastructure services—IBM® SmartCloud® Enterprise and IBM® SmartCloud® Enterprise+. It can be expected that the range of platform services will grow over the years, expanding the possibilities that you have of getting managed and hosted middleware services right from the box (as a service). Open cloud standards Commitment to open standards has been a long running focus for IBM, which has become even more visible with the March 2013 announcement that IBM cloud software and services will be based on open standards. This move will ensure that innovation in cloud computing is not hampered by locking businesses into proprietary islands of insecure and difficult-to-manage offerings. As the first step, IBM will base a new private cloud solution—part of the IBM® SmartCloud® Foundation portfolio segment—on the open sourced OpenStack® software. This will allow organizations to build a private cloud without the fear of being locked in, as well as allowing easier integration with public cloud solutions. It can be expected that this will surely resonate in further IBM® SmartCloud® Enterprise developments as well. Apart from the infrastructure focused OpenStack standard, IBM is also working on platform focused standards such as OASIS® TOSCA and data interface standards such as W3C Linked Data. Not to forget the standardization bodies such as The Open Group® and user groups such as Cloud Standards Customer Council (CSCC) and Cloud Computing Use Case Discussion Group. Find an overview of the all open cloud standards and links to each open standard individually can be found at www.ibm.com/cloud-computing/us/en/open-standards.html and a more in-depth view on the more technical open standards at www.ibm.com/developerworks/cloud/library/cl-open-architecture. SoftLayer Technologies Inc. On July 8th, IBM announced that it completed the acquisition of Softlayer Technologies Inc. (Softlayer), which joins IBM's new cloud services division and will be combined with IBM® SmartCloud® into a global platform. As quoted from the press release, found at www-03.ibm.com/press/us/en/pressrelease/41430.wss you can read the potency of the acquisition: "SoftLayer will enable IBM to deliver an industry first: marrying the security, privacy and reliability of private clouds with the economy and speed of a public cloud. SoftLayer offers a breakthrough capability that provides a cloud "on ramp" for born-on-the-web companies, government, and the Fortune 500." An interesting, analyst, view on the Softlayer acquisition and the growth potential for the IBM® SmartCloud® portfolio can be viewed in the video at www.youtube.com/watch?v=a3uscmcQVTI Hybrid cloud Hybrid cloud, combining both public and private cloud services into a solution, looks like the most powerful delivery form for the years to come. Powerful in the sense that you get to choose from the mix of characteristics that both private and public cloud solutions offer. To underline the trend, many analysts believe that 2013 will be the year that hybrid cloud implementations will truly get traction. With IBM's broad and integrated family of cloud technologies, the IBM® SmartCloud® portfolio, IBM is perfectly placed to deliver hybrid cloud solutions. IBM, for instance, has solutions for integrating multi-source, multi-vendor cloud solutions, allowing application portability and central system and server management. Another example of application portability in a hybrid cloud is the use of design patterns—allowing you to define your infrastructure topology, including application code and scalability characteristics into a reusable asset—in both IBM's public and private cloud solutions. The developerWorks article series Inside the hybrid cloud takes you through all aspects of the value and impact of implementing and using a hybrid cloud. The first article, Redefine services and delivery methods, covers the basics of a hybrid cloud implementation, takes you through the services it makes available, and provides a point of view on the potential business value. The article is available at www.ibm.com/developerworks/cloud/library/cl-hybridcloud1. Federation is key to XaaS, the second article, describes hybrid cloud in more detail and focuses on the principle of a federated cloud: orchestrating multiple cloud solutions as if it were one solution. It is available at www.ibm.com/developerworks/cloud/library/cl-hybridcloud2. The article Administration peeks under the hood of hybrid cloud to see what it takes to make the hybrid powerhouse a reality. It can be viewed at www.ibm.com/developerworks/cloud/library/cl-hybridcloud3. Implementation considerations, the final article of the series, looks into the aspect of implementing and consuming a hybrid cloud setup like governance, network connectivity, and access control. This article is available at www.ibm.com/developerworks/cloud/library/cl-hybridcloud4. Summary This article helped us in closing the loop from the IBM cloud strategy and IBM® SmartCloud® portfolio, through fine-grained information on IBM® SmartCloud® Enterprise, and reaching towards a high-level view where IBM® SmartCloud® might be heading in the near future. Resources for Article: Further resources on this subject: What is Oracle Public Cloud? [Article] Photo Stream with iCloud [Article] Introduction to Oracle Service Bus & Oracle Service Registry [Article]
Read more
  • 0
  • 0
  • 1732

article-image-bootstrap-30-mobile-first
Packt
16 Dec 2013
10 min read
Save for later

Bootstrap 3.0 is Mobile First

Packt
16 Dec 2013
10 min read
(For more resources related to this topic, see here.) But why Mobile First? Why did Bootstrap completely change its course from Desktop First to Mobile First to get into this new way to develop more suitable websites and web applications? Why did the most popular frontend framework embrace this change at a time when responsive web design is continuously growing with better suited and standard techniques such as media-queries, fluid layout, and JavaScript on demand? Mobile browsers are increasing support for the brand new HTML5 and CSS3, with the philosophy to offer, for older browsers, a less stylized but fully functional component, and for capable browsers a rich and full experience that comes from mobiles to larger screens such as TVs. For older browsers (such as IE 8 and IE 9), Bootstrap has functional support, but enhanced features such as rounded corners and a placeholder attribute for tips in input fields are not supported for these browsers. To see the full details on browser support, check the Bootstrap documentation from the Getting started section (http://getbootstrap.com/getting-started/#browsers). We are living at a time when mobile use is increasing at a pace that will soon surpass desktop usage (http://www.businessinsider.com/mobile-will-eclipsedesktop-by-2014-2012-6). Apart from the statistics, one thing we can presume is that the web scenario is changing so fast that we have to embrace the certainty of devices getting better and smarter. In this article, we will explore the main changes in Bootstrap 3. If you are already familiar with Bootstrap 2, check the migration guide (http://getbootstrap.com/getting-started/#migration) to have a practical overview about what has changed. If you're not familiar with Bootstrap, there's nothing that's too difficult for you to understand directly from this article about this new version. The only thing you need to have in mind is the Mobile First approach, which is covered well in this article. You will be guided to design with Mobile First, discover why Mobile First is so important, and how to make Bootstrap a powerful frontend platform to make your site friendly for a wider range of devices. We can take a step further and add to your previous Bootstrap knowledge by thinking of a concrete way to design processes as a continuous layer of capabilities and embrace the constraints and not fight with them. Mobile First with Bootstrap is an elegant solution for frontend development. Combined with server-side techniques, we get a full bag of solutions to get your product better suited to different users and needs in different platforms. This article will cover the following topics: Bootstrap reviewed Desktop to responsive   Bootstrap reviewed In the third era of Bootstrap that is coming, the developers have redesigned the whole framework with a different approach. Let's get started building interface components of small and simple screens, instead of adapting the existent UI components to fit in a constrained environment. From mobile, we will then go to desktop. However, we will not adapt the experience as we usually do with responsive design going from desktop to mobile. Now with Mobile First we will enhance accordingly as we increase the device screens. Why should I do this if my target audience will be using desktops? Going to mobile indirectly benefits desktop users. But how? To better understand this, let's recap Bootstrap history for a while. In 2011, Bootstrap was launched to serve as a live and agnostic style guide that was used by Twitter to create their products. It became an open source framework at that time. It was a time when we worked in pixel-perfect layouts and explored CSS3 animations, and we found in Bootstrap a well-documented and standardized set of features. Bootstrap creates a new design for the browsers because you don't need to define basic interface elements from scratch, such as buttons. At the same time, you have utility elements like badges to cover the most common interface elements. Bootstrap does what a framework is supposed to do: Bootstrapping! The term means the act of taking off a new project; it's like saying, "give me the tools that I will need to start developing my application for different needs". Bootstrap is a toolkit belt with standard conventions from well-defined classes with clean and practical documentation to live code that is ready to use and be customized for your needs. It's not a magic solution to solve the interface element reuse issue, but it's a kick-start. It fits in so many scenarios that developers are increasing its use with their own tools. "CSS moved beyond type, forms and grids. People get tired to create the same stuffs"— Mark Otto, one of Bootstrap's creators, in the Desktop First to Mobile First Bootstrap presentation (https://speakerdeck.com/mdo/desktop-firstto- with-bootstrap) A must-have from this breeding ground of possibilities is the Bootstrap extension font-awesome (http://fortawesome.github.io/Font-Awesome/). It uses font-face, which is widely supported and flexible, instead of sprites for icons. With a single CSS file and font resources used to render the custom fonts, you have a tool that can handle all your icons. This shows the flexibility of Bootstrap tools; for example, font-awesome is independent, works as a standalone project, and is a great fit with Bootstrap. There are a lot of ways to use Bootstrap. You can customize and extend components, from editing the source code in LESS variables or customize via the Bootstrap download page (http://getbootstrap.com/customize/). At the time of this writing, Bootstrap is the most popular project on Github, so it's just one more reason to consider its importance. There's now an official Bootstrap Expo (http://expo.getbootstrap.com/). This is one of the changes in this new version. Bootstrap Expo is the official directory for websites and web applications that are being developed using this framework. A lot of developers get their first touch with the capabilities of HTML5 and CSS3 with this framework. Bootstrap has amazing capabilities such as offering a responsive grid, dozens of JavaScript components, and a customizer in a web interface or through the LESS variables, if you're an experienced developer. It's suitable for any level of developer and designers because it has solutions that suit both scenarios. This is the second of Bootstrap's main philosophies—it's made for everyone. Desktop to responsive With the rise of smart phones, there is a need for responsive content to cover the growing demand. It's possible to add an optional file with media queries and a bunch of CSS code and be adapted to mobile needs. Media queries, a CSS3 module introduced in June 2012, is a basic structure that gives a namespace with a bunch of CSS rules and declarations according to the user resolution, density, and screen capabilities. So, with CSS files, it is possible to manage the ongoing rise of smartphones. It was possible with just one stylesheet file with good support to adapt according with the device and make a website mobile friendly. In Bootstrap Version 2, we used to have an optional file (responsive.less) that used to have all the media queries necessary for Bootstrap to work well with mobiles. Another good news is that we can adapt to tablets as a bonus. We have breakpoints for the most common mobile resolutions—this means we have a range of width (768 px to 979 px) that can represent tablet devices. A breakpoint is the extreme point (minimum and/or maximum) where you can define CSS rules specific to that range and change your layout. This could be achieved with a simple declaration of media queries in your CSS: @media (min-width: 768px) and (max-width: 979px) { ... } But sometimes it's indispensable to rethink some elements—some of those already developed only for desktops—in a pixel-perfect scenario. There's no flexibility in a pixel-width accommodation. No matter how much the screen is different, the website will behave like you were using a desktop when we work with fixed units. This is when we can use a bunch of media queries to get more flexible. Even with this solution, redefining dimensions and CSS rules according to the device using media queries will solve screen flexibility issues but not solve performance issues on mobiles. Performance is one of the main concerns when we go mobile. We have to consider scenarios where the Internet connection is slow and it is a recurrent issue. You will have to perform reverse engineering to make your JavaScript optimize loading, and combine it with server-side solutions. A worse solution would be to just hide content after considering what could be painful for your page load; for example, images have a deep impact on the final performance. Lower page response time is equivalent to more money spent, as we can see in this article about page loading versus user patience (http://blog.kissmetrics.com/loading-time/). One of the curious things this research points to is that mobile Internet users expect their browsing experience in phones to be comparable to what they get on their desktops. We are living at a time when the Web is filled with rich content and we have faster Internet connections. We have to be prepared to offer the closest thing to a fast and optimized loading, at least for our most important content. This does not involve just the use of CSS to hide content and show content depending on the device, as we can do using media queries. It's all about keeping the concepts simple and focused and developing each interface component thoughtfully from scratch—the primary use, with the constraints and its enhanced capabilities. It's not just about adapting, it's exploring the device's capabilities and delivering the best user experience across platforms. Sounds familiar? Yes, for sure, the same concept as progressive enhancement, you might think. You're not wrong. Progressive enhancement was a term widely used at a time when we talked about HTML page dependency on JavaScript to be functional. Progressive enhancement is a strategy for web design that relies on semantic markup and technologies such as JavaScript. Nowadays, progressive enhancement is a longer term for Mobile First because it's not just about JavaScript disabled, as it was vastly talked before. A hundred of articles tried to show its benefits in a no JavaScript environment scenarios. Now progressive enhancement is about to be faster (http://coding.smashingmagazine.com/2013/09/03/progressive-enhancement-is-faster/). Progressive enhancement is one of the three keys of Mobile First, together with responsive design and giving priority to content over navigation. So, these three rationales are at the background of all the details of Bootstrap 3, from your CSS components to your grid structure. Summary In this article we saw the Twitter Bootstrap's latest version Mobile First. We also saw how developers developed this framework. The growing world of smartphones have forced for the need for Mobile First. Resources for Article: Further resources on this subject: Downloading and setting up Bootstrap [Article] Introduction to RWD frameworks [Article] Getting started with using Chef [Article]
Read more
  • 0
  • 44
  • 29027

article-image-home-security-beaglebone
Packt
13 Dec 2013
7 min read
Save for later

Home Security by BeagleBone

Packt
13 Dec 2013
7 min read
(For more resources related to this topic, see here.) One of the best kept secrets of the security and access control industry is just how simple the monitoring hardware actually is. It is the software that runs on the monitoring hardware that makes it seem cool. The original BeagleBone or the new BeagleBone Black, have all the computing power you need to build yourself an extremely sophisticated access control, alarm panel, home automation, and network intrusion detection system. All for less than a year's worth of monitoring charges from your local alarm company! Don't get me wrong, monitored alarm systems have their place. Your elderly mother, for example, or your convenience store in a bad part of town. There is no substitute for a live human on the other end of the line. That said, if you are reading this, you are probably a builder or a hobbyist with all the skills required to do it yourself. BeagleBone is used as the development platform. The modular design of the alarm system allows the hardware to be used with any of the popular single board computers available in the market today. Any single board computer with at least eight accessible input/output pins will work. For example, the Arduino series of boards, the Gumstix line of hardware, and many others. The block diagram of the alarm system is shown in the following diagram: Block Diagram The adapter board is what is used to connect the single board computer to the alarm system. The adapter board comes with connectors for adding two more zones and four more outputs. Instructions are provided for adding zone inputs and panel outputs to the software. An alarm zone can be thought of as having two properties. The first is the actual hardware sensors connected to the panel. The second is the physical area being protected by the sensors. There are three or four types of sensors found in home and small business alarm systems. The first and most common is the magnetic door or window contact. The magnet is attached to the moving part (the window or the door) and the contacts are attached to the frame of the door or window. When the door or window is opened past a certain point the magnet can no longer hold the contacts closed, and they open to signal an alarm. The second most common sensor is the active sensor. The PIR or passive infrared motion sensor is installed in the corner of a room in order to detect the motion of a body which is warmer than the ambient temperature. Two other common sensors are temperature rise and CO detectors. These can both be thought of as life saving detectors. They are normally on a separate zone so that they are not disabled when the alarm system is not armed. The temperature rise detector senses a sudden rise in the ambient temperature and is intended to replace the old ionization type smoke detectors. No more burnt toast false alarms! The CO detector is used to detect the presence of Carbon Monoxide, which is a byproduct of combustion. Basically, faulty oil or gas furnaces and wood or coal burning stoves are the main culprit. Temperature Rise or CO Detector Physical zones are the actual physical location that the sensors are protecting. For example "ground floor windows" could be a zone. Other typical zones defended by a PIR could be garage or rear patio. In the latter case, outdoor PIR motion sensors are available at about twice the price of an indoor model. Depending on your climate, you may be able to install an indoor sensor outside, provided that it is sheltered from rain. The basic alarm system comes with four zone inputs and four alarm outputs. The outputs are just optically isolated phototransistors. So you can use them for anything you like. The first output is reserved in software for the siren, but you can do whatever you like with the other outputs. All four outputs are accessible from the alarm system web page, so you can remotely turn on or off any number of things. For example, you can use the left over three outputs to turn on and off lawn sprinklers, outdoor lighting or fountains and pool pumps. That's right. The alarm system has its own built in web server which provides you with access to the alarm system from anywhere with an internet connection. You could be on the other side of the world and if anything goes wrong, the alarm system will send you an e-mail telling you that something is wrong. Also, if you leave for the airport and forget to turn on or off the lights or lawn sprinkler, simply connect to the alarm system and correct the problem. You can also connect to the system via SSH or secure shell. This allows you to remotely run terminal applications on your BeagleBone. The alarm system, actually has very little to do so long as no alarms occur. The alarm system hardware generates an interrupt which is detected by the BeagleBone, so the BeagleBone spends most of its time idle. This is a waste of computing resources, so the system can also run network intrusion detection software. Not only can this alarm system protect you physical property, it can also keep your network safe as well. Can any local alarm system company claim that? Iptraf Iptraf is short for IP Traffic Monitor. This is a terminal-based program which monitors traffic on any of the interfaces connected to your network or the BeagleBone. My TraceRoute (mtr-0.85) Anyone who has ever used trace route on either Linux or Windows will know that it is used to find the path to a given IP address. MTR is a combination of trace route and ping in one single tool. Wavemon Wavemon is a simple ASCII text-based program that you can use to monitor your WiFi connections to the BeagleBone. Unlike the first two programs, Wavemon requires an Angstrom compatible WiFi adapter. In this case I used an AWUS036H wireless adapter. hcitool Bluetooth monitoring can be done in much the same way as WiFi monitoring; with hcitool. For example: hcitool scan will scan any visible Bluetooth devices in range. As with Wavemon, an external Bluetooth adapter is required. Your personal security system These are just some of the features of the security system you can build and customize for yourself. With advanced programming skills, you can create a security system with fingerprint ID access, that not only monitors and controls its physical surroundings but also the network that it is connected to. It can also provide asset tracking via RFID, barcode, or both; all for much less than the price of a commercial system. Not only that but you designed built and installed it. So tech support is free and should be very knowledgeable! Summary A block diagram of the alarm system is explained. The adapter board is what is used to connect the single board computer to the alarm system. The adapter board comes with connectors for adding two more zones and four more outputs. Instructions are provided for adding zone inputs and panel outputs to the software. Resources for Article: Further resources on this subject: Building a News Aggregating Site in Joomla! [Article] Breaching Wireless Security [Article] Building HTML5 Pages from Scratch [Article]
Read more
  • 0
  • 0
  • 7973
article-image-working-aspnet-web-api
Packt
13 Dec 2013
5 min read
Save for later

Working with ASP.NET Web API

Packt
13 Dec 2013
5 min read
(For more resources related to this topic, see here.) The ASP.NET Web API is a framework that you can make use of to build web services that use HTTP as the protocol. You can use the ASP.NET Web API to return data based on the data requested by the client, that is, you can return JSON or XML as the format of the data. Layers of an application The ASP.NET Framework runs on top of the managed environment of the .NET Framework. The Model, View, and Controller (MVC) architectural pattern is used to separate the concerns of an application to facilitate testing, ease the process of maintenance of the application's code, and to provide better support for change. The model represents the application's data and the business objects; the view is the presentation layer component, and the controller binds the model and the view together. The following figure illustrates the components of Model View Architecture: The MVC Architecture The ASP.NET Web API architecture The ASP.NET Web API is a lightweight web-based architecture that uses HTTP as the application protocol. Routing in the ASP.NET Web API works a bit differently compared to the way it works in ASP.NET MVC. The basic difference between routing in MVC and routing in a Web API is that, Web API uses the HTTP method, and not the URI path, to select the action. The Web API Framework uses a routing table to determine which action is to be invoked for a particular request. You need to specify the routing parameters in the WebApiConfig.cs file that resides in the App_Start directory. Here's an example that shows how routing is configured: routes.MapHttpRoute(    name: "Packt API Default",     routeTemplate: "api/{controller}/{id}",     defaults: new { id = RouteParameter.Optional } ); The following code snippet illustrates how routing is configured by action names: routes.MapHttpRoute(     name: "PacktActionApi",     routeTemplate: "api/{controller}/{action}/{id}",     defaults: new { id = RouteParameter.Optional } ); The ASP.NET Web API generates structured data such as JSON and XML as responses. It can route the incoming requests to the actions based on HTTP verbs and not only action names. Also, the ASP.NET Web API can be hosted outside of the ASP.NET runtime environment and the IIS Web Server context. Routing in ASP.NET Web API Routing in the ASP.NET Web API is very much the same as in the ASP.NET MVC. The ASP.NET Web API routes URLs to a controller. Then, the control is handed over to the action that corresponds to the HTTP verb of the request message. Note that the default route template for an ASP.NET Web API project is {controller}/{id}—here the {id} parameter is optional. Also, the ASP.NET Web API route templates may optionally include an {action} parameter. It should be noted that unlike the ASP.NET MVC, URLs in the ASP.NET Web API cannot contain complex types. It should also be noted that complex types must be present in the HTTP message body, and that there can be one, and only one, complex type in the HTTP message body. Note that the ASP.NET MVC and the ASP.NET Web API are two distinctly separate frameworks which adhere to some common architectural patterns. In the ASP.NET Web API framework, the controller handles all HTTP requests. The controller comprises a collection of action methods—an incoming request to the Web API framework, the request is routed to the appropriate action. Now, the framework uses a routing table to determine the action method to be invoked when a request is received. Here is an example: routes.MapHttpRoute(     name: "Packt Web API",     routeTemplate: "api/{controller}/{id}",     defaults: new { id = RouteParameter.Optional } ); Refer to the following UserController class. public class UserController <UserAuthentication>: BaseApiController<UserAuthentication> {     public void GetAllUsers() { }     public IEnumerable<User> GetUserById(int id) { }     public HttpResponseMessage DeleteUser(int id){ } } The following table illustrates the HTTP method and the corresponding URI, Actions, and so on: HTTP Method URI Action Parameter GET api/users GetAllUsers None GET api/users/1 GetUserByID 1 POST api/users     DELETE api/users/3 DeleteUser 3 The Web API Framework matches the segments in the URI path to the template. The following steps are performed: The URI is matched to a route template. The respective controller is selected. The respective action is selected. The IHttpControllerSelector.SelectController method selects the controller, takes an HttpRequestMessage instance and returns an HttpControllerDescriptor. After the controller has been selected, the Web API framework selects the action by invoking the IHttpActionSelector.SelectAction method. This method in turn accepts HttpControllerContext and returns HttpActionDescriptor. You can also explicitly specify the HTTP method for an action by decorating the action method using the HttpGet, HttpPut, HttpPost, or HttpDelete attributes. Here is an example: public class UsersController : ApiController {     [HttpGet]     public User FindUser(id) {} } You can also use the AcceptVerbs attribute to enable HTTP methods other than GET, PUT, POST, and DELETE. Here is an example: public class UsersController : ApiController {     [AcceptVerbs("GET", "HEAD")]     public User FindUser(id) { } } You can also define route by an action name. Here is an example: routes.MapHttpRoute(     name: "PacktActionApi",     routeTemplate: "api/{controller}/{action}/{id}",     defaults: new { id = RouteParameter.Optional } ); You can also override the action name by using the ActionName attribute. The following code snippet illustrates two actions: one that supports GET and the other that supports POST: public class UsersController : ApiController {     [HttpGet]     [ActionName("Token")]     public HttpResponseMessage GetToken(int userId);     [HttpPost]     [ActionName("Token")]     public void AddNewToken(int userId); }  
Read more
  • 0
  • 0
  • 10474

article-image-clojure-domain-specific-languages-design-concepts-clojure
Packt
13 Dec 2013
3 min read
Save for later

Clojure for Domain-specific Languages - Design Concepts with Clojure

Packt
13 Dec 2013
3 min read
(For more resources related to this topic, see here.) Every function is a little program When I first started getting deep into Clojure development, my friend Tom Marble taught me a very good lesson with a single sentence. I'm not sure if he's the originator of this idea, but he told me to think of writing functions as though "every function is a small program". I'm not really sure what I thought about functions before I heard this, but it all made sense the very moment he told me this. Why write a function as if it were its own program? Because both a function and a program are created to handle a specific set of problems, and this method of thinking allows us to break down our problems into a simpler group of problems. Each set of problems might only need a very limited collection of functions to solve them, so to make a function that fits only a single problem isn't really any different from writing a small program to get the very same result. Some might even call this the Unix philosophy, in the sense that you're trying to build small, extendable, simple, and modular code. A pure function What are the benefits of a program-like function? There are many benefits to this approach of development, but the two clear advantages are that the debugging process can be simplified with the decoupling of task, and this approach can make our code more modular. This approach also allows us to better build pure functions. A pure function isn't dependent on any variable outside the function. Anything other than the arguments passed to the function can't be realized by a pure function. Because our program will cause side effects as a result of execution, not all of our functions can be truly pure. This doesn't mean we should forget about trying to develop program-like functions. Our code inherently becomes more modular because pure functions can survive on their own. This is key when needing to build flexible, extendable, and reusable code components. Floor to roof development It is also known as bottom-up development and is the concept of building basic low- level pieces of a program and then combining them to build the whole program. This approach leads to more reusable code that can be more easily tested because each part of the program acts as an individual building block and doesn't require a large portion of the program to be completed to run a test. Each function only does one thing When a function is written to perform a specific task, that function shouldn't do anything unrelated to the original problem it's needed to solve. For example, if you were to write a function named parse-xml, the function should be able to act as a program that can only parse XML data. If the example function does anything else other than parse lines of XML input, it is probably badly designed and will cause confusion when trying to debug errors in our programs. This practice will help us keep our functions to a more reasonable size and can also help simplify the debugging process.
Read more
  • 0
  • 0
  • 18828

article-image-handling-authentication
Packt
13 Dec 2013
9 min read
Save for later

Handling Authentication

Packt
13 Dec 2013
9 min read
(for more resources related to this topic, see here.) Understanding Authentication methods In a world where security on the Internet is such a big issue, the need for great authentication methods is something that cannot be missed. Therefore, Zend Framework 2 provides a range of authentication methods that suits everyone's needs. Getting ready To make full use of this, I recommend a working Zend Framework 2 skeleton application to be set up. How to do it… The following is a list of authentication methods—or as they are called adapters—that are readily available in Zend Framework 2. We will provide a small overview of the adapter, and instructions on how you can use it. The DbTable adapter Constructing a DbTable adapter is pretty easy, if we take a look at the following constructor: public function __construct( // The ZendDbAdapterAdapter DbAdapter $zendDb, // The table table name to query on $tableName = null, // The column that serves as 'username' $identityColumn = null, // The column that serves as 'password' $credentialColumn = null, // Any optional treatment of the password before // checking, such as MD5(?), SHA1(?), etcetera $credentialTreatment = null ); The HTTP adapter After constructing the object we need to define the FileResolver to make sure there are actually user details parsed in. Depending on what we configured in the accept_schemes option, the FileResolver can either be set as a BasicResolver, a DigestResolver, or both. Let's take a quick look at how to set a FileResolver as a DigestResolver or BasicResolver (we do this in the /module/Application/src/Application/Controller/IndexController.php file): <?php namespace Application; // Use the FileResolver, and also the Http // authentication adapter. use ZendAuthenticationAdapterHttpFileResolver; use ZendAuthenticationAdapterHttp; use ZendMvcControllerAbstractActionController; class IndexController extends AbstractActionController { public function indexAction() { // Create a new FileResolver and read in our file to use // in the Basic authentication $basicResolver = new FileResolver(); $basicResolver->setFile( '/some/file/with/credentials.txt' ); // Now create a FileResolver to read in our Digest file $digestResolver = new FileResolver(); $digestResolver->setFile( '/some/other/file/with/credentials.txt' ); // Options doesn't really matter at this point, we can // fill them in to anything we like $adapter = new Http($options); // Now set our DigestResolver/BasicResolver, depending // on our $options set $adapter->setBasicResolver($basicResolver); $adapter->setDigestResolver($digestResolver); } } How it works… After two short examples, let's take a look at the other adapters available. The DbTable adapter Let's begin with probably the most used adapter of them all, the DbTable adapter. This adapter connects to a database and pulls the requested username/password combination from a table and, if all went well, it will return to you an identity, which is nothing more than the record that matched the username details. To instantiate the adapter, it requires a ZendDbAdapterAdapter in its constructor to connect with the database with the user details; there are also a couple of other options that can be set. Let's take a look at the definition of the constructor: The second (tableName) option speaks for itself as it is just the table name, which we need to use to get our users, the third and the fourth (identityColumn, credentialColumn) options are logical and they represent the username and password (or what we use) columns in our table. The last option, the credentialTreatment option, however, might not make a lot of sense. The credentialTreatment tells the adapter to treat the credentialColumn with a function before trying to query it. Examples of this could be to use the MD5 (?) function, PASSWORD (?), or SHA1 (?) function, if it was a MySQL database, but obviously this can differ per database as well. To give a small example on how the SQL can look like (the actual adapter builds this query up differently) with and without a credential treatment, take a look at the following examples: With credential treatment: SELECT * FROM `users` WHERE `username` = 'some_user' AND `password` = MD5('some_password'); Without credential treatment: SELECT * FROM `users` WHERE `username` = 'some_user' AND `password` = 'some_password'; When defining the treatment we should always include a question mark for where the password needs to come, for example, MD5 (?) would create MD5 ('some_password'), but without the question mark it would not insert the password. Lastly, instead of giving the options through the constructor, we can also use the setter methods for the properties: setTableName(), setIdentityColumn(), setCredentialColumn(), and setCredentialTreatment(). The HTTP adapter The HTTP authentication adapter is an adapter that we have probably all come across at least once in our Internet lives. We can recognize the authentication when we go to a website and there is a pop up showing where we can fill in our usernames and passwords to continue. This form of authentication is very basic, but still very effective in certain implementations, and therefore, a part of Zend Framework 2. There is only one big massive but to this authentication, and that is that it can (when using the basic authentication) send the username and password clear text through the browser (ouch!). There is however a solution to this problem and that is to use the Digest authentication, which is also supported by this adapter. If we take a look at the constructor of this adapter, we would see the following code line: public function __construct(array $config); The constructor accepts a load of keys in its config parameter, which are as follows: accept_schemes: This refers to what we want to accept authentication wise; this can be basic, digest, or basic digest. realm: This is a description of the realm we are in, for example Member's area. This is for the user only and is only to describe what the user is logging in for. digest_domains: These are URLs for which this authentication is working for. So if a user logs in with his details on any of the URLs defined, they will work. The URLs should be defined in a space-separated (weird, right?) list, for example /members/area /members/login. nonce_timeout: This will set the number of seconds the nonce (the hash users login with when we are using Digest authentication) is valid. Note, however, that nonce tracking and stale support are not implemented in Version 2.2 yet, which means it will authenticate again every time the nonce times out. use_opaque: This is either true or false (by default is true) and tells our adapter to send the opaque header to the client. The opaque header is a string sent by the server, which needs to be returned back on authentication. This does not work sometimes on Microsoft Internet Explorer browsers though, as they seem to ignore that header. Ideally the opaque header is an ever-changing string, to reduce predictability, but ZF 2 doesn't randomize the string and always returns the same hash. algorithm: This includes the algorithm to use for the authentication, it needs to be a supported algorithm that is defined in the supportedAlgos property. At the moment there is only MD5 though. proxy_auth: This boolean (by default is false) tells us if the authentication used is a proxy Authentication or not. It should be noted that there is a slight difference in files when using either Digest or Basic. Although both files have the same layout, they cannot be used interchangeably as the Digest requires the credentials to be MD5 hashed, while the Basic requires the credentials to be plain text. There should also always be a new line after every credential, meaning that the last line in the credential file should be empty. The layout of a credential file is as follows: username:realm:credentials For example: some_user:My Awesome Realm:clear text password Instead of a FileResolver, one can also use the ApacheResolver which can be used to read out htpasswd generated files, which comes in handy when there is already such a file in place. The Digest adapter The Digest adapter is basically the Http adapter without any Basic authentication. As the idea behind it is the same as the Http adapter, we will just go on and talk about the constructor, as that is a bit different in implementation: public function __construct($filename = null, $realm = null, $identity = null, $credential = null); As we can see the following options can be set when constructing the object: filename: This is the direct filename of the file to use with the Digest credentials, so no need to use a FileResolver with this one. realm: This identifies to the user what he/she is logging on to, for example My Awesome Realm or The Dragonborn's lair. As we are immediately trying to log on when constructing this, it does need to correspond with the credential file. identity: This is the username we are trying to log on with, and again it needs to resemble a user that is defined in the credential file to work. credential: This is the Digest password we try to log on with, and this again needs to match the password exactly like the one in the credential file. We can then, for example, just run $digestAdapter->getIdentity() to find out if we are successfully authenticated or not, resulting in NULL if we are not, and resulting in the identity column value if we are. The LDAP adapter Using the LDAP authentication is obviously a little more difficult to explain, so we will not go in to that full as that would take quite a while. What we will do is show the constructor of the LDAP adapter and explain its various options. However, if we want to know more about setting up an LDAP connection, we should take a look at the documentation of ZF2, as it is explained in there very well: public function __construct(array $options = array(), $identity = null, $credential = null); The options parameter in the construct refers to an array of configuration options that are compatible with the ZendLdapLdap configuration. There are literally dozens of options that can be set here so we advice to go and look at the LDAP documentation of ZF2 to know more about that. The next two parameters identity and credential are respectively the username and password again, so that explains itself really. Once you have set up the connection with the LDAP there isn't much left to do but to get the identity and see whether we were successfully validated or not. About Authentication Authentication in Zend Framework 2 works through specific adapters, which are always an implementation of the ZendAuthenticationAdapterAdapterInterface and thus, always provides the methods defined in there. However, the methods of Authentication are all different, and strong knowledge of the methods displayed previously is always a requirement. Some work through the browser, like the Http and Digest adapter, and others just require us to create a whole implementation like the LDAP and the DbTable adapter.
Read more
  • 0
  • 0
  • 4516
article-image-building-queries
Packt
12 Dec 2013
10 min read
Save for later

Building Queries

Packt
12 Dec 2013
10 min read
(For more resources related to this topic, see here.) Understanding DQL DQL is the acronym of Doctrine Query Language. It's a domain-specific language that is very similar to SQL, but is not SQL. Instead of querying the database tables and rows, DQL is designed to query the object model's entities and mapped properties. DQL is inspired by and similar to HQL, the query language of Hibernate, a popular ORM for Java. For more details you can visit this website: http://www.hibernate.org/. Learn more about domain-specific languages at: http://en.wikipedia.org/wiki/Domain-specific_language To better understand what it means, let's run our first DQL query. Doctrine command-line tools are as genuine as a Swiss Army knife. They include a command called orm:run-dql that runs the DQL query and displays it's result. Use it to retrieve title and all the comments of the post with 1 as an identifier: php vendor/bin/doctrine.php orm:run-dql "SELECT p.title,c.bodyFROM BlogEntityPost p JOIN p.comments c WHERE p.id=1" It looks like a SQL query, but it's definitely not a SQL query. Examine the FROM and the JOIN clauses; they contain the following aspects: A fully qualified entity class name is used in the FROM clause as the root of the query All the Comment entities associated with the selected Post entities are joined, thanks to the presence of the comments property of the Post entity class in the JOIN clause As you can see, data from the entities associated with the main entity can be requested in an object-oriented way. Properties holding the associations (on the owning or the inverse side) can be used in the JOIN clause. Despite some limitations (especially in the field of subqueries), DQL is a powerful and flexible language to retrieve object graphs. Internally, Doctrine parses the DQL queries, generates and executes them through Database Abstraction Layer (DBAL) corresponding to the SQL queries, and hydrates the data structures with results. Until now, we only used Doctrine to retrieve the PHP objects. Doctrine is able to hydrate other types of data structures, especially arrays and basic types. It's also possible to write custom hydrators to populate any data structure. If you look closely at the return of the previous call of orm:run-dql, you'll see that it's an array, and not an object graph, that has been hydrated. As with all the topics covered in this book, more information about built-in hydration modes and custom hydrators is available in the Doctrine documentation on the following website: http://docs.doctrine-project.org/en/latest/reference/dql-doctrine-query-language.html#hydration-modes Using the entity repositories Entity repositories are classes responsible for accessing and managing entities. Just like entities are related to the database rows, entity repositories are related to the database tables. All the DQL queries should be written in the entity repository related to the entity type they retrieve. It hides the ORM from other components of the application and makes it easier to re-use, refactor, and optimize the queries. Doctrine entity repositories are an implementation of the Table Data Gateway design pattern. For more details, visit the following website: http://martinfowler.com/eaaCatalog/tableDataGateway.html A base repository, available for every entity, provides useful methods for managing the entities in the following manner: find($id): It returns the entity with $id as an identifier or null It is used internally by the find() method of the Entity Managers. findAll(): It retrieves an array that contains all the entities in this repository findBy(['property1' => 'value', 'property2' => 1], ['property3' => 'DESC', 'property4' => 'ASC']): It retrieves an array that contains entities matching all the criteria passed in the first parameter and ordered by the second parameter findOneBy(['property1' => 'value', 'property2' => 1]): It is similar to findBy() but retrieves only the first entity or null if none of the entities match the criteria Entity repositories also provide shortcut methods that allow a single property to filter entities. They follow this pattern: findBy*() and findOneBy*(). For instance, calling findByTitle('My title') is equivalent to calling findBy(['title' => 'My title']). This feature uses the magical __call() PHP method. For more details visit the following website: http://php.net/manual/en/language.oop5.overloading.php#object.call In our blog app, we want to display comments in the detailed post view, but it is not necessary to fetch them from the list of posts. Eager loading through the fetch attribute is not a good choice for the list, and Lazy loading slows down the detailed view. A solution to this would be to create a custom repository with extra methods for executing our own queries. We will write a custom method that collates comments in the detailed view. Creating custom entity repositories Custom entity repositories are classes extending the base entity repository class provided by Doctrine. They are designed to receive custom methods that run the DQL queries. As usual, we will use the mapping information to tell Doctrine to use a custom repository class. This is the role of the repositoryClass attribute of the @Entity annotation. Kindly perform the following steps to create a custom entity repository: Reopen the Post.php file at the src/Blog/Entity/ location and add a repositoryClass attribute to the existing @Entity annotation like the following line of code: @Entity(repositoryClass="PostRepository") Doctrine command-line tools also provide an entity repository generator. Type the following command to use it: php vendor/bin/doctrine.php orm:generate:repositories src/ Open this new empty custom repository, which we just generated in the PostRepository.phpPostRepository.php file, at the src/Blog/Entity/ location. Add the following method for retrieving the posts and comments: /** * Finds a post with its comments * * @param int $id * @return Post */ public function findWithComments($id) { return $this ->createQueryBuilder('p') ->addSelect('c') ->leftJoin('p.comments', 'c') ->where('p.id = :id') ->orderBy('c.publicationDate', 'ASC') ->setParameter('id', $id) ->getQuery() ->getOneOrNullResult() ; } Our custom repository extends the default entity repository provided by Doctrine. The standard methods, described earlier in the article, are still available. Getting started with Query Builder QueryBuilder is an object designed to help build the DQL queries through a PHP API with a fluent interface. It allows us to retrieve the generated DQL queries through the getDql() method (useful for debugging) or directly use the Query object (provided by Doctrine). To increase performance, QueryBuilder caches the generated DQL queries and manages an internal state. The full API and states of the DQL query are documented on the following website: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html We will give an in-depth explanation of the findWithComments() method that we created in the PostRepository class. Firstly, a QueryBuilder instance is created with the createQueryBuilder() method inherited from the base entity repository. The QueryBuilder instance takes a string as a parameter. This string will be used as an alias of the main entity class. By default, all the fields of the main entity class are selected and no other clauses except SELECT and FROM are populated. The leftJoin() call creates a JOIN clause that retrieves comments associated with the posts. Its first argument is the property to join and its second is the alias; these will be used in the query for the joined entity class (here, the letter c will be used as an alias for the Comment class). Unless the SQL JOIN clause is used, the DQL query automatically fetches the entities associated with the main entity. There is no need for keywords like ON or USING. Doctrine automatically knows whether a join table or a foreign-key column must be used. The addSelect() call appends comment data to the SELECT clause. The alias of the entity class is used to retrieve all the fields (this is similar to the * operator in SQL). As in the first DQL query of this article, specific fields can be retrieved with the notation alias.propertyName. You guessed it, the call to the where() method sets the WHERE part of the query. Under the hood, Doctrine uses prepared SQL statements. They are more efficient than the standard SQL queries. The id parameter will be populated by the value set by the call to setParameter(). Thanks again to prepared statements and this setParameter() method, SQL Injection attacks are automatically avoided. SQL Injection Attacks are a way to execute malicious SQL queries using user inputs that have not escaped. Let's take the following example of a bad DQL query to check if a user has a specific role: $query = $entityManager->createQuery('SELECT ur FROMUserRole urWHERE ur.username = "' . $username . '" ANDur.role = "' . $role . '"'); $hasRole = count($query->getResult()); This DQL query will be translated into SQL by Doctrine. If someone types the following username: " OR "a"="a the SQL code contained in the string will be injected and the query will always return some results. The attacker has now gained access to a private area. The proper way should be to use the following code: $query = $entityManager->createQuery("SELECT ur FROMUserRole WHEREusername = :username and role = :role"); $query->setParameters([ 'username' => $username, 'role' => $role ]); $hasRole = count($query->getResult()); Thanks to prepared statements, special characters (like quotes) contained in the username are not dangerous, and this snippet will work as expected. The orderBy() call generates an ORDER BY clause that orders results as per the publication date of the comments, older first. Most SQL instructions also have an object-oriented equivalent in DQL. The most common join types can be made using DQL; they generally have the same name. The getQuery() call tells the Query Builder to generate the DQL query (if needed, it will get the query from its cache if possible), to instantiate a Doctrine Query object, and to populate it with the generated DQL query. This generated DQL query will be as follows: SELECT p, c FROM BlogEntityPost p LEFT JOIN p.comments cWHEREp.id = :id ORDER BY c.publicationDate ASC The Query object exposes another useful method for the purpose of debugging: getSql(). As its name implies, getSql() returns the SQL query corresponding to the DQL query, which Doctrine will run on DBMS. For our DQL query, the underlying SQL query is as follows: SELECT p0_.id AS id0, p0_.title AS title1, p0_.bodyAS body2,p0_.publicationDate AS publicationDate3,c1_.id AS id4, c1_.bodyAS body5, c1_.publicationDate AS publicationDate6,c1_.post_id ASpost_id7 FROM Post p0_ LEFT JOIN Commentc1_ ON p0_.id =c1_.post_id WHERE p0_.id= ? ORDER BY c1_.publicationDate ASC The getOneOrNullResult() method executes it, retrieves the first result, and returns it as a Post entity instance (this method returns null if no result is found). Like the QueryBuilder object, the Query object manages an internal state to generate the underlying SQL query only when necessary. Performance is something to be very careful about while using Doctrine. When set in production mode, ORM is able to cache the generated queries (DQL through the QueryBuilder objects, SQL through the Query objects) and results of the queries. ORM must be configured to use one of the blazing, fast, supported systems (APC, Memcache, XCache, or Redis) as shown on the following website: http://docs.doctrine-project.org/en/latest/reference/caching.html We still need to update the view layer to take care of our new findWithComments() method. Open the view-post.php file at the web/location, where you will find the following code snippet: $post = $entityManager->getRepository('BlogEntityPost')->find($_GET['id']); Replace the preceding line of code with the following code snippet: $post = $entityManager->getRepository('BlogEntityPost')->findWithComments($_GET['id']);
Read more
  • 0
  • 0
  • 3280

article-image-creating-your-first-campaign
Packt
12 Dec 2013
6 min read
Save for later

Creating Your First Campaign

Packt
12 Dec 2013
6 min read
(For more resources related to this topic, see here.) Eloqua is a Software as a Service (SaaS) platform, specifically referred to as a marketing automation platform. It offers a set of tools to manage scalable digital campaigns consisting of emails, landing pages, forms, and automated processes. Utilizing marketing automation software allows marketers to collect data and digital activity, sometimes referred to as digital body language. This information can then be used for campaign performance analysis. Additionally, marketing automation helps to reduce the time and effort spent on campaign execution. Let's say that you, as a marketer, have been tasked to send e-mails inviting prospects to an event your company is sponsoring. This event is four weeks away, and you would like to remind people if they do not respond to the first e-mail within a week before the event date. By using marketing automation, you are able to set up a work flow within a campaign, which would send the first e-mail at a scheduled date and the reminder e-mail at another scheduled date (to those prospects who do not respond to the first e-mail). This can be set up once, turned on, and left to perform the scheduled actions. Ultimately, by leveraging the power of marketing automation, marketers gain more time to focus on their message and strategy. This article will cover creating the components of a very simple e-mail campaign. The purpose of this campaign will be to send an e-mail to a group of contacts. We will build the campaign workflow, activate the campaign, and measure our results. Let us take a closer look at the following two basic elements of our campaign: Segment: This will be the target audience who will be receiving the e-mail Email: This will contain the actual marketing content we are delivering Because our campaign is very simple, and we know the two elements that will be used, it makes sense to build the elements first, and then build the campaign using them. With more complex campaigns, it can be helpful to design the work flow and add place holders for the assets to understand the overall design and scope of the campaign, before setting up the actual components themselves. Navigation overview We'll start by logging into Eloqua by going to https://login.eloqua.com. This will redirect us to the login page, where you will need to enter your login credentials. Before creating our email and segment, let us take some time to review the navigation within Eloqua. Once logged in, you will see a navigation bar across the top of the application. Each of the following five icons in the middle of the navigation bar can be used to move to different areas: Campaigns: This will open Launchpad to create a new campaign or open an existing campaign. Once a selection is made, the campaign editor will open. Assets: This has several subcategories. Emails, Landing Pages, and Forms are the primary digital assets you can build and manage in Eloqua. Each of the links in the navigation will bring you to Launchpad. Here, you can create, open, or upload new assets for Emails and Landing Pages. You can create, open, or integrate website forms for Forms from Launchpad. After any of these selections are made, you will be taken to the respective editors in Eloqua. Component Library contains separate components that can be used within the primary digital assets. The examples include images or blocks of HTML content that can be used across several assets. Contacts: This has several subcategories as well. Contacts, Accounts, and Custom Objects, all take you to sections where you can view and manage the respective records in the system. Lead Scoring opens Launchpad that will take you to the lead scoring editor. Segments also open Launchpad, but it will take you to the segment editor. Data Tools and Shared Library offer additional tools and mechanisms to manage contacts, accounts, and custom objects. Insight: This opens Eloqua's reporting engine in a separate window. This is where the data inside the system can be analyzed. Setup: This takes you to the area where you can perform system administration tasks. Here, the fields for objects can be managed, integration with your customer relationship management (CRM) system can be con figured, and many other configurations for Eloqua can be set. The buttons on the right of the navigation bar allow you to search, access support resources and account information, and log out of the system respectively. On clicking on the Eloqua icon on the left-hand side of the navigation bar, you will always be taken to the My Eloqua page, which has various containers of links for quick access to different specific assets, campaigns, and reports. Campaign overview Eloqua campaigns serve two purposes. Campaigns can provide reporting on the assets belonging to them and campaigns can be used to create work flows for members that are added to them. For example, a campaign can do the following tasks: Send an e-mail. Identify whether an e-mail was clicked through. Send an exclusive offer if the first e-mail was clicked through on a landing page that may have been visited due to the first e-mail or through another source, such as an offline advertisement. The digital assets that a campaign may include are e-mails, forms, and landing pages. Because landing pages hosted outside of Eloqua cannot be included as assets for campaigns, it is strongly recommended that you host your landing pages in Eloqua. This increases the data captured and available for campaign analysis. In addition to controlling a workflow, campaigns can also be used to capture and report on metrics. Assuming there is one e-mail, one landing page, one form, and one offline advertisement as part of a campaign, we can carry out the following tasks: Report on e-mail activity, landing page activity, and form submissions We can also potentially report on metrics for the offline advertisement Summary In this article, we set up a very basic digital campaign. We created an e-mail using Eloqua's WYSIWYG editor. Resources for Article: Implementing Software Engineering Best Practices and Techniques with Apache Maven [Article] Knowing the prebuilt marketing, sales, and service organizations [Article] Pentaho Reporting: Building Interactive Reports in HTML [Article]
Read more
  • 0
  • 0
  • 873
Modal Close icon
Modal Close icon