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

How-To Tutorials

7018 Articles
article-image-building-winrt-components-be-consumed-any-language-become-expert
Packt
30 May 2013
5 min read
Save for later

Building WinRT components to be consumed from any language (Become an expert)

Packt
30 May 2013
5 min read
(For more resources related to this topic, see here.) Getting ready Please refer to the WinRTCalculator project for the full working code to create a WinRT component and consume it in Javascript. How to do it... Perform the following steps to create a WinRT component and consume it in Javascript: Launch Visual Studio 2012 and create a new project. Expand Visual C++ from the left pane and then select the node for Windows Store apps. Select the Windows Runtime component and then name the project as WinRTCalculator. Open Class1.h and add the following method declarations: double ComputeAddition(double num1, double num2);double ComputeSubstraction(double num1, double num2);double ComputeMultiplication(double num1, double num2);double ComputeDivision(double num1, double num2); Open Class1.cpp and add the following method implementations: double Class1::ComputeAddition(double num1, double num2){return num1+num2;}double Class1::ComputeSubstraction(double num1, double num2){if(num1>num2)return num1-num2;else return num2-num1;}double Class1::ComputeMultiplication(double num1, double num2){return num1*num2;}double Class1::ComputeDivision(double num1, double num2){if (num2 !=0){ return num1/num2; } else return 0; } Now save the project and build it. Now we need to create a Javascript project where the preceding WinRTCalculator component will be consumed. To create the Javascript project, follow these steps: Right-click on Solution Explorer and go to Add | New Project. Expand JavaScript from the left pane, and choose Blank App. Name the project as ConsumeWinRTCalculator. Right-click on ConsumeWinRTCalculator and set it as Startup Project . Add a project reference to WinRTCalculator, as follows: Right-click on the ConsumeWinRTCalculator project and choose Add Reference. Go to Solution | Projects from the left pane of the References Manager dialog box. Select WinRTCalculator from the center pane and then click on the OK button. Open the default.html file and add the following HTML code in the body: <p>Calculator from javascript</p> <div id="inputDiv"> <br /><br /> <span id="inputNum1Div">Input Number - 1 : </span> <input id="num1" /> <br /><br /> <span id="inputNum2Div">Input Number - 2 : </span> <input id="num2" /> <br /><br /> <p id="status"></p> </div> <br /><br /> <div id="addButtonDiv"> <button id="addButton" onclick= "AdditionButton_Click()">Addition of Two Numbers </button> </div> <div id="addResultDiv"> <p id="addResult"></p> </div> <br /><br /> <div id="subButtonDiv"> <button id= "subButton" onclick="SubsctractionButton_Click()"> Substraction of two numbers</button> </div> <div id="subResultDiv"> <p id="subResult"></p> </div> <br /><br /> <div id="mulButtonDiv"> <button id= "mulButton" onclick="MultiplicationButton_Click()"> Multiplcation of two numbers</button> </div> <div id="mulResultDiv"> <p id="mulResult"></p> </div> <br /><br /> <div id="divButtonDiv"> <button id= "divButton" onclick="DivisionButton_Click()"> Division of two numbers</button> </div> <div id="divResultDiv"> <p id="divResult"></p> </div> Open the default.css style file from 5725OT_08_CodeWinRTCalculatorConsumeWinRTCalculatorcss default.css and copy-paste the styles to your default.css style file. Add JavaScript event handlers that will call the WinRTCalculator component DLL. Add the following code at the end of the default.js file: var nativeObject = new WinRTCalculator.Class1(); function AdditionButton_Click() { var num1 = document.getElementById('num1').value; var num2 = document.getElementById('num2').value; if (num1 == '' || num2 == '') { document.getElementById('status').innerHTML = 'Enter input numbers to continue'; } else { var result = nativeObject.computeAddition(num1, num2); document.getElementById('status').innerHTML = ''; document.getElementById('addResult').innerHTML = result; } } function SubsctractionButton_Click() { var num1 = document.getElementById('num1').value; var num2 = document.getElementById('num2').value; if (num1 == '' || num2 == '') { document.getElementById('status').innerHTML = 'Enter input numbers to continue'; } else { var result = nativeObject.computeSubstraction (num1, num2); document.getElementById('status').innerHTML = ''; document.getElementById('subResult').innerHTML = result; } } function MultiplicationButton_Click() { var num1 = document.getElementById('num1').value; var num2 = document.getElementById('num2').value; if (num1 == '' || num2 == '') { document.getElementById('status').innerHTML = 'Enter input numbers to continue'; } else { var result = nativeObject.computeMultiplication (num1, num2); document.getElementById('status').innerHTML = ''; document.getElementById('mulResult').innerHTML = result; } } Now press the F5 key to run the application. Enter the two numbers and click on the Addition of Two Numbers button or on any of the shown buttons to display the computation. How it works... The Class1.h and Class1.cpp files have a public ref class. It's an Activatable class that JavaScript can create by using a new expression. JavaScript activates the C++ class Class1 and then calls its methods and the returned values are populated to the HTML Div. There's more... While debugging a JavaScript project that has a reference to a WinRT component DLL, the debugger is set to enable either stepping through the script or through the component native code. To change this setting, right-click on the JavaScript project and go to Properties | Debugging | Debugger Type. If a C++ Windows Runtime component project is removed from a solution, the corresponding project reference from the JavaScript project must also be removed manually. Summary In this article, we learned how to reate a WinRT component and call it from JavaScript. Resources for Article : Further resources on this subject: Installation and basic features of EnterpriseDB [Article] Editing DataGrids with Popup Windows in Flex [Article] Monitoring Windows with Zabbix 1.8 [Article]
Read more
  • 0
  • 0
  • 1739

Packt
30 May 2013
11 min read
Save for later

Release Planning – Tuning Product Development

Packt
30 May 2013
11 min read
(For more resources related to this topic, see here.) People in traditional projects attempt to define and then control scope during the project, while Agile teams approach the problem differently: figure out enough to get started, embrace changes, and then proceed as the way opens. Agile teams, by definition, try to respond to changing market or user needs as soon as those needs are discovered, yet business requires them to plan ahead from time to time. Agile teams know that they cannot predict a project's outcome, so they use pragmatic planning approaches to tune their development efforts to the latest and greatest needs. This is somewhat like what your local meteorologist does every night on the six o'clock news—his next-day forecast is usually spot on, but the seventh day is always off! Unfortunately, no team (or weatherman) can predict the future, which is why I keep a backup umbrella in my car. The traditional project metrics of all planned scope , on budget , and by the deadline don't work for complex technical projects. Here's a quick example out of thousands: if the project team changes direction because a customer's needs change halfway through the project, is this a failure? Agile teams would say certainly not, and that it's actually a success to respond to changing needs, but I've actually heard the counterargument that if the team members would have spent more time in requirements gathering, they would have been able to predict all the customer's needs up front rather than encounter a surprise downstream (as if someone can simply throw out the cast net and drag all the requirements in with the fishes!). This traditional project management logic says that we fail when we don't achieve the holy trinity of scope, time, and cost. Unfortunately, there are still many organizations, managers, and teams that have this embedded mind-set; this can disrupt the best Agile planning attempts. I'd give anything to have the ability to see the future of a project, and I'm sure most of you reading this article would as well. Why do you think this is? Humans love to have the perfect plan, and we want the security of knowing what will happen next. We feel safe and secure when we have a tidy Gantt chart, risk logs, and resource plans. It feels good to think about the problem for a long time until we're sure that we have the perfect solution. We're problem solvers, after all, so isn't this what we're supposed to do? Plans make us feel secure. That is, until they change. If the real world didn't exist, my advice to you and your team would be to plan your projects barely enough to deliver value early and spend more of your time adapting to the realities that unfold as a result of delivery. I'd also recommend that you help your teams resist the temptation of estimating tasks to the nth level and to committing to anything more than a week's worth of work; and please, thwart any attempt by your organization to put you or your colleagues on more than one task or project at a time! Stage a revolt if you must! Since you live in the real world, and you're not likely to stage a revolt, I have to give advice that's a bit more useful than "go ahead, break all the rules." First, think differently about planning. Consider that, in your current work environment, you are most likely asked to plan projects because the business requires it. Constraints such as budgets, deadlines, and resources (human or not) are finite entities that a ScrumMaster must work with or around in a project. Or are they? Agile gives us the opportunity to pause to think that budgets, deadlines, and people assigned to the project can change based on the adaptations that the organization needs to make in order to win. Be aware that there is a growing trend of modern organizations moving away from the traditional mind-set of projects, and I fully attribute this to the Agile movement. This movement from "crystal-balling" to "continuous adaptation " is a real, modern business adaptation. Mary Poppendieck, author of Lean Software Development: An Agile Toolkit , says that successful companies don't create a plan and execute it; rather, they create capacity and respond to reality as it unfolds. Scrum provides two activities for understanding capacity and planning: release planning for long-term and sprint planning for short-term. Both utilize the product backlog as an input. This article will teach you how to use release planning techniques, but in parallel, also think of Scrum as your quiet revolt; use its philosophies and tools to change the way your organization thinks about projects and value(s). The Scrum framework is the Deming Cycle incarnate: plan-do-check-act. ( Wash. Rinse. Repeat.) The reasons for doing so are as clear as a sunny day: knowledge about requirements, technology, and personal interactions emerge throughout the lifecycle of a project. Owing to this emergence, it makes sense to plan with just enough detail for the timeframe and expected outcome. In other words, long-term plans are coarse in their level of planning and estimation, while near-term plans are very detailed. The following figure illustrates the idea of narrowing the view and focus for the time horizon; roadmaps have wide swaths of possibilities—the roadmap's range is long-term (years, in some cases). Release plans are usually one to three months (although they can be longer) into the future and the possibilities aren't so robust; in fact, release plans are just as much about what a team won't do, as what they will try to do. Finally, you can see that the sprint really nails it down; a team commits to a specific amount of work for a near-term goal. I used to play violin. Every day before I could practice, I had to tune my instrument. Tuning is physically done by first using the wooden pegs by the scroll, matching the pitch with that of a piano or a tuning fork. I'd get as close to the standard pitch as I could for the A string and then use the fine tuners near th e chin rest to make it perfect. From a perfectly tuned A string, it was easy to tune the other strings because when tuned, the sound waves synchronize and notes would blend into a beautiful synthesis of sound. If you've ever watched an orchestra, I'm sure you've noticed the string players tuning their instruments several times throughout. This is because the circumstances of the concert change while the concert is in play—the wood of the violin expands from the heat of the player's body and fingers, strings loosen, and bow hair relaxes through intense pizzicato and crescendo; or perhaps the musician noticed that his instrument was just a bit off while playing the previous piece. Musicians see tuning as part of the concert, part of playing the piece or movement. While getting the instrument back on pitch, the musician is also getting his mind in tune as well. A release plan is similar to the tuning fork; it represents the direction, goal, or outcomes to which teams should align. Sprint planning is like fine-tuning; turning the little metal fine-tuners at the bottom of the violin bridge in order to get perfect pitch; planning for exactly what we can commit to for one, two, or four weeks of time. I wouldn't fine-tune my violin today and think that I could play in an orchestra five months from now without re-tuning. I have to re-tune to account for changes in the instrument. So while I dislike the word plan because it has the connotations of finality, exactness, deadlines, and fixedness, I like the concept of tuning product development to the needs of users and customers by use of adaptive planning techniques such as release and sprint planning. And just as tuning is part of playing the piece or movement, think of release planning and sprint planning as part of doing the project. To make it even more interesting, there are non-standard tuning techniques, called scordatura, evident in French composer Camille Saint-Saens' Danse Macabre, where the violin's E string is tuned down to E flat ( http://en.wikipedia.org/wiki/Violin#Tuning ). Likewise, there are different methods and styles of planning releases and sprints. The simple answer is to keep planning simple and efficient; think of planning sessions as times for tuning product development in accordance with the stakeholders' needs. Since those needs are certain to change, tuning will be a continuous process much like you observe in the string section at the concert. This article focuses on the long-term release plan. It is your responsibility as ScrumMaster to find the best tuning techniques for your team and organization. Carry on, ScrumMaestro. Start at the beginning – product backlog A product backlog is an ordered list of features or work to be implemented in a product. It could be infinite in length; that is, there could always be new requirements for a product. The product owner is an actual customer or an internal representation thereof (think of an iPad product owner representing many millions of users), maintains, updates, administers, and ranks the product backlog. Based on market research, a product vision statement, industry analytics, technical innovations, or simply ideas to test, the product backlog represents the product owner's most valuable ideas and features for a product. Once the team has selected, planned, and committed product backlog items to a sprint, the product owner cannot make any changes to those items. However, the product owner is given free reign to change the priority, requirements, and even remove any product backlog item that hasn't been committed and planned in a sprint. This simple game rule drives the product owner into a routine behavior of just-in-time preparedness: the product owner must rank and prepare detail for the most important product backlog items for the next sprint planning meeting. Likewise, the product owner should prioritize and prepare a set of features desired for a release in anticipation of that release's planning discussion. Product backlogs are very useful for managing change because work that hasn't started can easily be re-ordered (tuned) to the market needs at any given point in time. If the team needs to react to an emergency competitor situation, the product owner can defer any not-started items to make way for the features to meet the competitive demand in the very next sprint. Since we know that market needs will change, it's in the product owner's best interest to put more planning effort and detail into the most important items the team will need to implement next. In the following figure, the product backlog is depicted as the basis for both long and short-term planning. The product backlog facilitates both levels of planning; that is, product backlog can be quickly and easily re-ordered for long-term forecasting, while in sprint planning, the highest priority backlog items will be planned with utmost detail (tasks, hours, owners, and so forth) because they are ready to be implemented at that time. The leanest implementation of a product backlog is to pull the top item from the backlog, finish it, release to production, followed by the next item, and so on, with no planning other than for one item at a time. This scenario is actually a reality for some companies. However, most teams at most companies engage in both long-term and short-term planning activities and use the product backlog as the main input. Summary Release planning is not a crystal ball into which someone can look and predict the outcome of a project. Rather, release planning provides a way for the team and product owner to tune committed work to users' and customers' needs without planning for too much detail too soon. The team and product owner must revisit the release plan periodically during the release and work together to deliver features that delight customers. Resources for Article : Further resources on this subject: How to Focus on Business Results [Article] Planning Your CRM Implementation Using CiviCRM [Article] IBM Rational Team Concert 2: Agile Development [Article]
Read more
  • 0
  • 0
  • 1206

article-image-article-optimizing-programs
Packt
29 May 2013
6 min read
Save for later

Optimizing Programs

Packt
29 May 2013
6 min read
(For more resources related to this topic, see here.) Using transaction SAT to find problem areas In this recipe, we will see the steps required to analyze the execution of any report, transaction, or function module using the transaction SAT. Getting ready For this recipe, we will analyze the runtime of a standard program RIBELF00 (Display Document Flow Program). The program selection screen contains a number of fields. We will execute the program on the order number (aufnr) and see the behavior. How to do it... For carrying out runtime analysis using transaction SAT, proceed as follows: Call transaction SAT. The screen appears as shown: Enter a suitable name for the variant (in our case, YPERF_VARIANT) and click the Create button below it. This will take you to the Variant creation screen. On the Duration and Type tab, switch on Aggregation by choosing the Per Call Position radio-button. Then, click on the Statements tab. On the Statements tab, make sure Internal Tables, the Read Operations checkbox and the Change Operations checkbox, and the Open SQL checkbox under Database Access are checked. Save your variant. Come back to the main screen of SAT. Make sure that within Data Formatting on the initial screen of SAT, the checkbox for Determine Names of Internal Tables is selected. Next, enter the name of the program that is to be traced in the field provided (in our case, it is RIBELF00). Then click the   button. The screen of the program appears as shown. We will enter an order number range and execute the program. Once the program output is generated, click on the Back key to come back to program selection screen. Click on the Back key once again to generate the evaluation results. How it works... We carried out the execution of the program through the transaction SAT and the evaluation results were generated. On the left are the Trace Results (in tree form) listing the statements/ events with the most runtime. These are like a summary report of the entire measurement of the program. They are listed in descending order of the Net time in microseconds and the percentage of the total time. For example, in our case, the OPEN CURSOR event takes 68 percent of the total runtime of the program. Selecting the Hit List tab will show the top time consumer components of the program. In this example, the access of database tables AFRU and VBAK takes most of the time. Double-clicking any item in the Trace Results window on the left-hand side will display (in the Hit List area on the right-hand pane) details of contained items along with execution time of each item. From the Hit List window, double-clicking a particular item will take us to the relevant line in the program code. For example, when we double-click the Open Cursor VBAK line, it will take us to the corresponding program code. We have carried out analysis with Aggregation switched on. The switching on of Aggregation shows one single entry for a multiple calls of a particular line of code. Because of this, the results are less detailed and easier to read, since the hit list and the call hierarchy in the results are much more simplified. Also within the results, by default, the names of the internal table used are not shown. In order for the internal table names to appear in the evaluation result, the Determine Names checkbox of Internal tables indicator is checked. As a general recommendation, the runtime analysis should be carried out several times for best results. The reason being that the DB-measurement time could be dependent on a variety of factors, such as system load, network performance, and so on. Creation of secondary indexes in database tables Very often, the cause of a long running report is full-scan of a database table specified within the code, mainly because no suitable index exists. In this recipe, we will see the steps required in creating a new secondary index in database table for performance improvement. Creating indexes lets you optimize standard reports as well as your own reports. In this recipe, we will create a secondary index on a test table ZST9_VBAK (that is simply a copy of VBAK). How to do it... For creating a secondary index, proceed as follows: Call transaction SE11. Enter the name of the table in the field provided, in our case, ZST9_VBAK. Then click the Display button. This will take you to the Display Table screen. Next, choose the menu path Goto | Indexes. This will display all indexes that currently exist for the table. Click the Create button and then choose the option Create Extension Index The dialog box appears. Enter a three-digit name for the index. Then, press Enter. This will take you to the extension index maintenance screen. On the top part, enter the short description in the Short Description field provided. We will create a non-unique index so the Non-unique index radio button is selected (on the middle part of the screen). On the lower part of the screen, specify the field names to be used in the index. In our case, we use MANDT and AUFNR . Then, activate your index using keys Ctrl + F3. The index will be created in the database with appropriate message of creation shown below Status. How it works... This will create the index on the database. Since we created an extension index, the index will not be overwritten by SAP during an upgrade. Now any report that accesses ZST9_VBAK table specifying MANDT and AUFNR in the WHERE clause, will take advantage of index scan using our new secondary index. There's more... It is recommended by SAP that the index be first created in development system and then transport to quality, and to the production system. Secondary indexes are not automatically generated on target systems after being transported. We should check the status on the Activation Log in the target systems, and use the Database Utility to manually activate the index in question. A secondary index, preferably, must have fields that are not common (or as much as uncommon as possible) with other indexes. Too many redundant secondary indexes (that is, too many common fields across several indexes) on a table has a negative impact on performance. For instance, a table with 10 secondary indexes is sharing more than three fields. In addition, tables that are rarely modified (and very often read) are the ideal candidates for secondary indexes. See also http://help.sap.com/saphelp_erp2005/helpdata/EN/85/685a41cdbf80 47e10000000a1550b0/content.htm http://help.sap.com/saphelp_nw04/helpdata/en/cf/21eb2d446011d1 89700000e8322d00/frameset.htmhttp://docs.oracle.com/cd/ SELECT clause E17076_02/html/programmer_reference/am_second.html http://forums.sdn.sap.com/thread.jspa?threadID=1469347
Read more
  • 0
  • 0
  • 2086

article-image-introduction-citrix-xendesktop
Packt
29 May 2013
23 min read
Save for later

Introduction to Citrix XenDesktop

Packt
29 May 2013
23 min read
(For more resources related to this topic, see here.) Configuring the XenDesktop policies Now that the XenDesktop infrastructure has been configured, it's time to activate and populate the VDI policies. This is an extremely important part of the implementation process, because with these policies you will regulate the resource use and assignments, and you will also improve the general virtual desktops performance. Getting ready All the policies will be applied to the deployed virtual desktop instances and the assigned users, so you need an already existing XenDesktop infrastructure on which you will enable and use the configuration rules. How to do it... In this recipe we will explain the configuration for the user and machine policies offered by Citrix XenDesktop. Perform the following steps: Connect to the XenDesktop Director machine with domain administrative credentials, then navigate to Start | All Programs | Citrix and run the Desktop Studio. On the left-hand side menu expand the HDX Policy section and select the Machines link. Click on the New button to create a new policy container, or select the default unfiltered policies and click on Edit to modify them. In the first case, you have to assign a descriptive name to the created policy. In the Categories menu, click on the following sections and configure the values for the policies that will be applied to the clients, in terms of network flow optimization and resource usage monitoring: The ICA section ICA listener connection timeout: Insert a value in milliseconds; default is 12000. ICA listener port number: This is the TCP/IP port number on which the ICA protocol will try to establish the connection. The default value is 1494. The Auto Client Reconnect subsection Auto client reconnect: (Values Allowed or Prohibited) Specify whether or not to automatically reconnect in case of a broken connection from a client. Auto client reconnect authentication: (Values Do not require authentication or Require authentication) Decide whether to let the Citrix infrastructure ask you for the credentials each time you have to reperform the login operation. Auto client reconnect logging: (Values Do Not Log auto-reconnect events or Log auto-reconnect events) This policy enables or disables the logging activities in the system log for the reconnection process. In case of active autoclient reconnect, you should also activate its logging. End User Monitoring subsection ICA round trip calculation: (Values Enabled or Disabled) This decides whether or not to enable the calculation of the ICA network traffic time. ICA round trip calculation interval: Insert the time interval in seconds for the period of the round trip calculation. ICA round trip calculations for idle connections: (Values Enabled or Disabled) Decide whether to enable the round trip calculation for connections that are not performing traffic. Enable this policy only if necessary. The Graphics subsection Display memory limit: Configure the maximum value in KB to assign it to the video buffer for a session. Display mode degrade preference: (Values Degrade color depth first or Degrade resolution first) Configure a parameter to lower the resolution or the color quality in case of graphic memory overflow. Dynamic Windows Preview: (Values Enabled or Disabled) With this policy you have the ability to turn on or turn off the high-level preview of the windows open on the screen. Image caching: (Values Enabled or Disabled) With this parameter you can cache images on the client to obtain a faster response. Notify user when display mode is degraded: (Values Enabled or Disabled) In case of degraded connections you can display a pop up to send a notification to the involved users. Queueing and tossing: (Values Enabled or Disabled) By enabling this policy you can stop the processing of the images that are replaced by other pictures. In presence of slow or WAN network connections, you should create a separate policy group which will reduce the display memory size, configure the degrade color depth policy, activate the image caching, and remove the advanced Windows graphical features. The Keep Alive subsection ICA keep alive timeout: Insert a value in seconds to configure the keep alive timeout for the ICA connections. ICA keep alives: (Values Do not send ICA keep alive messages or Send ICA keep alive messages) Configure whether or not to send keep-alive signals for the running sessions. The Multimedia subsection Windows Media Redirection: (Values Allowed or Prohibited) Decide whether or not to redirect the multimedia execution on the Citrix server(s) and then stream it to the clients. Windows Media Redirection Buffer Size: Insert a value in seconds for the buffer used to deliver multimedia contents to the clients. Windows Media Redirection Buffer Size Use: (Values Enabled or Disabled) This policy decides whether or not to let you use the previously configured media buffer size. The Multi-Stream Connections subsection Audio UDP Port Range: Specify a port range for the UDP connections used to stream audio data. The default range is 16500 to 16509. Multi-Port Policy: This policy configures the traffic shaping to implement the quality of service (QoS). You have to specify from two to four ports and assign them a priority level. Multi-Stream: (Values Enabled or Disabled) Decide whether or not to activate the previously configured multistream ports. You have to enable this policy to activate the port configuration in the Multi-Port Policy. The Session Reliability subsection Session reliability connections: (Values Allowed or Prohibited) By enabling this policy you allow the sessions to remain active in case of network problems. Session reliability port number: Specify the port used by ICA to check the reliability of incoming connections. The default port is 2598. Session reliability timeout: Specify a value in seconds used by the session reliability manager component to wait for a client reconnection. You cannot enable the ICA keep alives policy if the policies under the Session Reliability subsection have been activated. The Virtual Desktop Agent Settings section Controller Registration Port: Specify the port used by Virtual Desktop Agent on the client to register with the Desktop Controller. The default value is 80. Changing this port number will require you to also modify the port on the controller machine by running the following command: <BrokerInstallationPath>BrokerService.exe / VdaPort <newPort> Controller SIDs: Specify a single controller SID or a list of them used by Virtual Desktop Agent for registration procedures. Controllers: Specify a single or a set of Desktop Controllers in the form of FQDN, used by Virtual Desktop Agent for registration procedures. Site GUID: Specify the XenDesktop unique site identifier used by Virtual Desktop Agent for registration procedures. In presence of more than one Desktop Controller, you should create multiple VDA policies with different controllers for a load-balanced infrastructure.   The CPU Usage Monitoring subsection Enable Monitoring: (Values Allowed or Prohibited) With this policy you can enable or disable the monitoring for the CPU usage. Monitoring Period: Insert a value in seconds to configure the time period to run the CPU usage recalculation. Threshold: Configure a percentage value to activate the high CPU usage alert. The default value is 95 percent. Enable the CPU Usage Monitoring policies in order to better troubleshoot machine load issues. After configuring, click on the OK button to save the modifications. On the left-hand side menu, click on the Users policy link in the HDX Policy section. Click on the New button to create a new policy container, or select the default unfiltered policies and click on Edit to modify them. In the first case, you have to assign a descriptive name to the created policy. In the Categories menu click on the following sections and configure the associated values: The ICA section Client clipboard redirection: (Values Allowed or Prohibited) This policy permits you to decide whether or not to enable the use of the client clipboard in the XenDesktop session, and to perform copy and paste operations from the physical device to the remote Citrix session. The active clipboard redirection could be a security issue; be sure about its activation! The Flash Redirection subsection Flash acceleration: (Values Enabled or Disabled) This policy permits you to redirect the Flash rendering activities to the client. This is possible only with the legacy mode. Enable this policy to have a better user experience for the Flash contents. Flash backwards compatibility: (Values Enabled or Disabled) With this policy you can decide whether or not to activate the compatibility of older versions of Citrix Receiver with the most recent Citrix Flash policies and features. Flash default behavior: (Values Enable Flash acceleration, Disable Flash acceleration, or Block Flash player) This policy regulates the use of the Adobe Flash technology, respectively enabling the most recent Citrix for Flash features (including the client-side processing), permitting only server-side processed contents, or blocking any Flash content. Flash event logging: (Values Enabled or Disabled) Decide whether or not to create system logs for the Adobe Flash events. Flash intelligent fallback: (Values Enabled or Disabled) This policy, if enabled, is able to activate the server-side Flash content processing when the client side is not required. The Flash Redirection features have been strongly improved starting from XenDesktop Version 5.5. The Audio subsection Audio over UDP Real-time transport: (Values Enabled or Disabled) With this policy you can decide which protocols to transmit the audio packets, RTP/UDP (policy enabled) or TCP (policy disabled). The choice depends on the kind of audio traffic to transmit. UDP is better in terms of performance and bandwidth consumption. Audio quality: (Values Low, Medium, or High) This parameter depends on a comparison between the quality of the network connections and the audio level, and they respectively cover the low-speed connections, optimized for speech and high-definition audio cases. Client audio redirection: (Values Allowed or Prohibited) Allowing or prohibiting this policy permits applications to use the audio device on the client's machine(s). Client microphone redirection: (Values Allowed or Prohibited ) This policy permits you to map client microphone devices to use within a desktop session. Try to reduce the network and load impact of the multimedia components and devices where the high user experience is not required. The Bandwidth subsection Audio redirection bandwidth limit: Insert a value in kilobits per second (Kbps) to set the maximum bandwidth assigned to the playing and recording audio activities. Audio redirection bandwidth limit percent: Insert a maximum percentage value to play and record audio. Client USB device redirection bandwidth limit: Insert a value in Kbps to set the maximum bandwidth assigned to USB devices redirection. Client USB device redirection bandwidth limit percent: Insert a maximum percentage value for USB devices redirection. Clipboard redirection bandwidth limit: Insert a value in Kbps to set the maximum bandwidth assigned to the clipboard traffic from the local client to the remote session. Clipboard redirection bandwidth limit percent: Insert a maximum percentage value for the clipboard traffic from the local client to the remote session. COM port redirection bandwidth limit: Insert a value in Kbps to set the maximum bandwidth assigned to the client COM port redirected traffic. COM port redirection bandwidth limit percent: Insert a maximum percentage value for the client COM port redirected traffic. File redirection bandwidth limit: Insert a value in Kbps to set the maximum bandwidth assigned to client drives redirection. File redirection bandwidth limit percent: Insert a maximum percentage value for client drives redirection. HDX MediaStream Multimedia Acceleration bandwidth limit: Insert a value in Kbps to set the maximum bandwidth assigned to the multimedia content redirected through the HDX MediaStream acceleration. HDX MediaStream Multimedia Acceleration bandwidth limit percent: Insert a maximum percentage value for the multimedia content redirected through the HDX MediaStream acceleration. Overall session bandwidth limit: Specify a value in Kbps for the total bandwidth assigned to the client sessions. In presence of both bandwidth limit and bandwidth limit percent enabled policies, the most restrictive value will be used. The Desktop UI subsection Aero Redirection: (Values Enabled or Disabled) This policy decides whether or not to activate the redirection of the Windows Aero graphical feature to the client device. If Aero has been disabled, this policy has no value. Aero Redirection Graphics Quality: (Values High, Medium, Low, and Lossless) If Aero has been enabled, you can configure its graphics level. Desktop wallpaper: (Values Allowed or Prohibited) Through this policy you can decide whether or not to permit the users having the desktop wallpaper in your session. Disable this policy if you want to standardize your desktop deployment. Menu animation: (Values Allowed or Prohibited) This policy permits you to decide whether or not to have the animated menu of the Microsoft operating systems. The choice depends on what kind of performances you need for your desktops. View window contents while dragging: (Values Allowed or Prohibited) This policy gives you the ability to see the entire window contents during the drag-and-drop activities between windows, if enabled. Otherwise you'll see only the window's border. Enabling the Aero redirection will have impact only on the LAN-based connection; on WAN, Aero will not be redirected by default. The File Redirection subsection Auto connect client drives: (Values Enabled or Disabled) With this policy the local drives of your client will or will not be automatically connected at logon time. Client drive redirection: (Values Allowed or Prohibited) The drive redirection policy allows you to decide whether it is permitted or not to save files locally on the client machine drives. Client fixed drives: (Values Allowed or Prohibited) This policy decides whether or not to permit you to read data from and save information to the fixed drives of your client machine. Client floppy drives: (Values Allowed or Prohibited) This policy decides whether or not to permit you to read data from and save information to the floppy drives of your client machine. This should be allowed only in presence of an existing floppy drive, otherwise it has no value to your infrastructure. Client network drives: (Values Allowed or Prohibited) With this policy you have the capability of mapping the remote network drives from your client. Client optical drives: (Values Allowed or Prohibited) With this policy you can enable or disable the access to the optical client drives, such as CD-ROM or DVD-ROM. Client removable drives: (Values Allowed or Prohibited) This policy allows or prohibits you to map, read, and save removable drives from your client, such as USB keys. Preserve client drive letters: (Values Enabled or Disabled) Enabling this policy offers you the possibility of maintaining the client drive letters when mapping them in the remote session, whenever possible. Read-only client drive access: (Values Enabled or Disabled) Enabling this policy will not permit you to access the mapped client drivers in write mode. By default, this policy is disabled to permit the full drive access. To reduce the impact on the client security, you should enable it. You can always modify it when necessary. These are powerful policies for regulating the access to the physical storage resources. You should configure them to be consistent with your company security policies. The Multi-Stream connections subsection Multi-Stream: (Values Enabled or Disabled) As seen earlier for the machine section, this policy enables or disables the multistreamed traffic for specific users. The Port Redirection subsection Auto connect client COM ports: (Values Enabled or Disabled) If enabled, this policy automatically maps the client COM ports. Auto connect client LPT ports: (Values Enabled or Disabled) This policy, if enabled, autoconnects the client LPT ports. Client COM port redirection: (Values Allowed or Prohibited) This policy configures the COM port redirection between the client and the remote session. Client LPT port redirection: (Values Allowed or Prohibited) This policy configures the LPT port redirection between the client and the remote session. You have to enable only the necessary ports, so disable the policies for the missing COM or LPT ports. The Session Limits subsection Disconnected session timer: (Values Enabled or Disabled) This policy enables or disables the counter used to migrate from a locked workstation to a logged off session. For security reasons, you should enable the automatic logoff of the idle sessions. Disconnected session timer interval: Insert a value in minutes, which will be used as a counter reference value to log off locked workstations. Set this parameter based on a real inactivity time for your company employees. Session connection to timer: (Values Enabled or Disabled) This policy will or will not use a timer to measure the duration of active connections from clients to the remote sessions. The Time Zone Control subsection Use local time of client: (Values Use server time zone or Use client time zone) With this policy you can decide whether to use the time settings from your client or from the server. XenDesktop uses the user session's time zone. The USB Devices subsection Client USB device redirection: (Values Allowed or Prohibited) With this important policy you can permit or prohibit USB drives redirection. Client USB device redirection rules: Through this policy you can generate rules for specific USB devices and vendors, in order to filter or not; and if yes, what types of external devices mapping. The Visual Display subsection Max Frame Per Second: Insert a value, in terms of frames per second, which will define the number of frames sent from the virtual desktop to the user client. This parameter could dramatically impact the network performance, so be careful about it and your network connection. The Server Session Settings section Single Sign-On: (Values Enabled or Disabled) This policy decides whether to turn on or turn off the SSO for the user sessions. Single Sign-On central store: Specify the SSO store server to which the user will connect for the logon operations, in the form of a UNC path. The Virtual Desktop Agent Settings section The HDX3DPro subsection EnableLossLess: (Values Allowed or Prohibited) This policy permits or prohibits the use of a lossless codec. HDX3DPro Quality Settings: Specify two values, Minimum Quality and Maximum Quality (from 0 to 100), as HDX 3D Pro quality levels. In the absence of a valid HDX 3D Pro license, this policy has no effect. The ICA Latency Monitoring subsection Enable Monitoring: (Values Allowed or Prohibited) This rule will or will not monitor the ICA latency problems. Monitoring Period: Define a value in seconds to run the ICA latency monitor. Threshold: Insert a threshold value in milliseconds to check if the ICA latency has arrived to the highest level. The Profile Load Time Monitoring subsection Enable Monitoring: (Values Allowed or Prohibited) With this policy you can monitor the time required to load a user profile. Threshold: Specify a value in seconds to activate the trigger for the high profile loading time event. These are important policies to troubleshoot performance issues in the profile loading activities, especially referred to the centralized profiles. After configuring click on the OK button to save the modifications. For both the edited policy categories (Machines and Users), click on the Edit button, select the Filters tab, and add one or more of the following filters: Access Control: (Mode: Allow or Deny, Connection Type: With Access Gateway or Without Access Gateway) Insert the parameters for the type of connection to which you are applying the policies, using or not using Citrix Access Gateway. Branch Repeater: (Values Connections with Branch Repeater or Connections without Branch Repeater) This policy decides whether or not to apply the policies to the connection that passes or doesn't pass through a configured Citrix Branch Repeater. Client IP Address: (Mode: Allow or Deny) Specify a client IP address to which you are allowing or denying the policy application. Client Name: (Mode: Allow or Deny) Specify a client name to which you are allowing or denying the policy application. Desktop Group: (Mode: Allow or Deny) Select from the drop-down list an existing desktop or application group to which you are applying or not applying the configured policies. Desktop Type: (Mode: Allow or Deny) This policy decides to allow or deny the policy application to the existing deployed resources (Private Desktop or Shared Desktop, Private Applications or Shared Applications). Organizational Unit: (Mode: Allow or Deny) Browse for an existing domain OU to which you are applying or not applying the configured policies. Tag: (Mode: Allow or Deny) This policy decides to allow or deny the application of the policies to specific tags applied to the desktops. User or Group: (Mode: Allow or Deny) Browse for existing domain users and groups to which you are applying or not applying the configured policies. For the machine section, you'll only have the desktop group, desktop type, organizational unit, and tag categories of filters. After completing this, click on the OK button to save the changed filters. How it works... The Citrix XenDesktop policies work at two different levels of components, machines and users, and for each of them you can apply a set of filters to decide when and where to permit or not to permit the policy utilization. These configurations should be strongly oriented to the performance and security optimization, so the best practices to apply is to generate different sets of policies and specifically apply them to different kinds of virtual desktops, clients, and users. The following is the explanation of the previously applied configurations: Machines policy level: These kinds of policies apply at the machine level, trying to regulate and optimize the session management, and the multimedia resources redirection. With this group of settings you are able to configure the standard ICA port to listen, and the relative connection timeouts. It's possible to decide whether or not to automatically reconnect a client in case of broken connections. Enabling Auto client reconnect policy could be right in some cases, especially when you have interrupted an important working session, but on the other hand, you could not have calculated waste of resources, because the Citrix broker could run a new session in the presence of issues with the session cookies. With the ICA round trip policies, you can monitor and measure the response time taken by the users for the operations. This data permits you to understand the responsiveness of your Citrix infrastructure. In case it allows you to apply remediation to the configuration, especially for the policies that involve graphics components, you can size the display memory and the image caching area, or turn on or off specific Windows advanced graphical features, such as the Dynamic Windows Preview (DWP). With the queuing and tossing policy active, you could have problems of lost frames when reproducing animations. The Windows media redirection policy optimizes the reproduction of multimedia objects; by applying a correct sizing to its buffer size you should obtain evident improvements in the streaming and reproduction operations. So, you should consider disabling this policy, demanding the processing of audio and video to the clients only when you can see no particular benefits. Another important feature offered by these policies is the QoS implementation; you can enable the multistream connection configurations and apply the traffic priority levels to them, permitting to give precedence and more bandwidth to the traffic that is considered more critical than others. The Multi-Stream policy for the QoS can be considered a less powerful alternative to Citrix Branch Repeater. As the last part of this section, the Virtual Desktop Agent Settings section permits you to restrict the access to only pre-configured resources, such as specific Desktop Controllers. Users policy level: Combined with the machines policies we have the users policies. These policies apply settings from a user session perspective, so you can configure, for instance, processing the Adobe Flash contents, deciding whether or not to activate the compatibility with the oldest version of this software, and whether to elaborate the Flash multimedia objects on the user's clients or on the Citrix servers. Moreover, you can configure the audio settings, such as audio and microphone client redirection (in the sense of using the local device resources), the desktop settings (Aero parameters, desktop wallpapers, and so on), or the HDX protocol quality settings. Be careful when applying policies for the desktop graphical settings. To optimize the information transmission for the desktops the bandwidth policy is extremely important; by this you can assign, in the form of maximum Kbps or percentage, the values for the traffic types such as audio, USB, clipboard, COM and LPT ports, and file redirection. These configurations require a good analysis of the traffic levels and their priorities within your organization. The last great configuration is the redirection of the client drives to the remote Citrix sessions; in fact, you can activate the mount (automatic or not) and the users rights (read only or read/write) on the client drives, removable or not, such as CD-ROM or DVD-ROM, removable USB devices, and fixed drives as the client device operating system root. This option gives you the flexibility to transfer information from the local device to the XenDesktop instance through the use of properly configured Virtual Desktop Agent. This last device policy could make your infrastructure more secure, thanks to the use of the USB device redirection rules; through it, in fact, you could only permit the use of USB keys approved by your company, prohibiting any other nonpolicy-compliant device. The granularity of the policy application is granted by the configuration of the filters; by using these-you can apply the policies to specific clients, desktop or application groups, or domain users and groups. In this way you can create different policies with different configurations, and apply them to specific areas of your company, without generalizing and overriding settings. There's more... To verify the effective running of the policies applied to your VDI infrastructure, there's a tool called Citrix Group Policy Modeling Wizard inside the HDX Policy section, which performs this task. This tool performs a simulation for the policy applications, returning a report with the current configuration. This is something similar to Microsoft Windows Domain Group Policy Results. The simulations apply to one or all the domain controllers configured within your domain, being able to test the application for a specific user or computer object, including organizational units containing them. Moreover, you can apply filters based on the client IP address, the client name, the type of machine (private or shared desktop, private or shared application), or you can apply the simulation to a specific desktop group. In the Advanced Options section you can simulate slow network connections and/or loopback processing (basically, a policy application only based on the computer object locations, instead of both the user and computer object positions) for a configured XenDesktop site. After running the policy application test, you can check the results by right-clicking on the generated report name, and selecting the View Report option. This tool is extremely powerful when you have to verify unexpected behaviors of your desktop instances or user rights because of the application of incorrect policies. Summery In this article we discussed the configuration of the XenDesktop infrastructural policies. Resources for Article : Further resources on this subject: Linux Thin Client : Considering the Network [Article] Designing a XenApp 6 Farm [Article] Getting Started with XenApp 6 [Article]
Read more
  • 0
  • 0
  • 2926

article-image-deploying-html5-applications-gnome
Packt
28 May 2013
10 min read
Save for later

Deploying HTML5 Applications with GNOME

Packt
28 May 2013
10 min read
(For more resources related to this topic, see here.) Before we start Most of the discussions in this article require a moderate knowledge of HTML5, JSON, and common client-side JavaScript programming. One particular exercise uses JQuery and JQuery Mobile to show how a real HTML5 application will be implemented. Embedding WebKit What we need to learn first is how to embed a WebKit layout engine inside our GTK+ application. Embedding WebKit means we can use HTML and CSS as our user interface instead of GTK+ or Clutter. Time for action – embedding WebKit With WebKitGTK+, this is a very easy task to do; just follow these steps: Create an empty Vala project without GtkBuilder and no license. Name it hello-webkit. Modify configure.ac to include WebKitGTK+ into the project. Find the following line of code in the file: PKG_CHECK_MODULES(HELLO_WEBKIT, [gtk+-3.0]) Remove the previous line and replace it with the following one: PKG_CHECK_MODULES(HELLO_WEBKIT, [gtk+-3.0 webkitgtk-3.0]) Modify Makefile.am inside the src folder to include WebKitGTK into the Vala compilation pipeline. Find the following lines of code in the file: hello_webkit_VALAFLAGS = --pkg gtk+-3.0 Remove it and replace it completely with the following lines: hello_webkit_VALAFLAGS = --vapidir . --pkg gtk+-3.0 --pkg webkit-1.0 --pkglibsoup-2.4 Fill the hello_webkit.vala file inside the src folder with the following lines: using GLib;using Gtk;using WebKit;public class Main : WebView{public Main (){load_html_string("<h1>Hello</h1>","/");}static int main (string[] args){Gtk.init (ref args);var webView = new Main ();var window = new Gtk.Window();window.add(webView);window.show_all ();Gtk.main ();return 0;}} Copy the accompanying webkit-1.0.vapi file into the src folder. We need to do this, unfortunately, because the webkit-1.0.vapi file distributed with many distributions is still using GTK+ Version 2. Run it, you will see a window with the message Hello, as shown in the following screenshot: What just happened? What we need to do first is to include WebKit into our namespace, so we can use all the functions and classes from it. using WebKit; Our class is derived from the WebView widget. It is an important widget in WebKit, which is capable of showing a web page. Showing it means not only parsing and displaying the DOM properly, but that it's capable to run the scripts and handle the styles referred to by the document. The derivation declaration is put in the class declaration as shown next: public class Main : WebView In our constructor, we only load a string and parse it as an HTML document. The string is Hello, styled with level 1 heading. After the execution of the following line, WebKit will parse and display the presentation of the HTML5 code inside its body: public Main (){load_html_string("<h1>Hello</h1>","/");} In our main function, what we need to do is create a window to put our WebView widget into. After adding the widget, we need to call the show_all() function in order to display both the window and the widget. static int main (string[] args){Gtk.init (ref args);var webView = new Main ();var window = new Gtk.Window();window.add(webView); The window content now only has a WebView widget as its sole displaying widget. At this point, we no longer use GTK+ to show our UI, but it is all written in HTML5. Runtime with JavaScriptCore An HTML5 application is, most of the time, accompanied by client-side scripts that are written in JavaScript and a set of styling definition written in CSS3. WebKit already provides the feature of running client-side JavaScript (running the script inside the web page) with a component called JavaScriptCore, so we don't need to worry about it. But how about the connection with the GNOME platform? How to make the client-side script access the GNOME objects? One approach is that we can expose our objects, which are written in Vala so that they can be used by the client-side JavaScript. This is where we will utilize JavaScriptCore. We can think of this as a frontend and backend architecture pattern. All of the code of business process which touch GNOME will reside in the backend. They are all written in Vala and run by the main process. On the opposite side, the frontend, the code is written in JavaScript and HTML5, and is run by WebKit internally. The frontend is what the user sees while the backend is what is going on behind the scene. Consider the following diagram of our application. The backend part is grouped inside a grey bordered box and run in the main process. The frontend is outside the box and run and displayed by WebKit. From the diagram, we can see that the frontend creates an object and calls a function in the created object. The object we create is not defined in the client side, but is actually created at the backend. We ask JavaScriptCore to act as a bridge to connect the object created at the backend to be made accessible by the frontend code. To do this, we wrap the backend objects with JavaScriptCore class and function definitions. For each object we want to make available to frontend, we need to create a mapping in the JavaScriptCore side. In the following diagram, we first map the MyClass object, then the helloFromVala function, then the intFromVala, and so on: Time for action – calling the Vala object from the frontend Now let's try and create a simple client-side JavaScript code and call an object defined at the backend: Create an empty Vala project, without GtkBuilder and no license. Name it hello-jscore. Modify configure.ac to include WebKitGTK+ exactly like our previous experiment. Modify Makefile.am inside the src folder to include WebKitGTK+ and JSCore into the Vala compilation pipeline. Find the following lines of code in the file: hello_jscore_VALAFLAGS = --pkg gtk+-3.0 Remove it and replace it completely with the following lines: hello_jscore_VALAFLAGS = --vapidir . --pkg gtk+-3.0 --pkg webkit-1.0 --pkglibsoup-2.4 --pkg javascriptcore Fill the hello_jscore.vala file inside the src folder with the following lines of code: using GLib;using Gtk;using WebKit;using JSCore;public class Main : WebView{public Main (){load_html_string("<h1>Hello</h1>" +"<script>alert(HelloJSCore.hello())</script>","/");window_object_cleared.connect ((frame, context) => {setup_js_class ((JSCore.GlobalContext) context);});}public static JSCore.Value helloFromVala (Context ctx,JSCore.Object function,JSCore.Object thisObject,JSCore.Value[] arguments,out JSCore.Value exception) {exception = null;var text = new String.with_utf8_c_string ("Hello fromJSCore");return new JSCore.Value.string (ctx, text);}static const JSCore.StaticFunction[] js_funcs = {{ "hello", helloFromVala, PropertyAttribute.ReadOnly },{ null, null, 0 }};static const ClassDefinition js_class = {0, // versionClassAttribute.None, // attribute"HelloJSCore", // classNamenull, // parentClassnull, // static valuesjs_funcs, // static functionsnull, // initializenull, // finalizenull, // hasPropertynull, // getPropertynull, // setPropertynull, // deletePropertynull, // getPropertyNamesnull, // callAsFunctionnull, // callAsConstructornull, // hasInstancenull // convertToType};void setup_js_class (GlobalContext context) {var theClass = new Class (js_class);var theObject = new JSCore.Object (context, theClass,context);var theGlobal = context.get_global_object ();var id = new String.with_utf8_c_string ("HelloJSCore");theGlobal.set_property (context, id, theObject,PropertyAttribute.None, null);}static int main (string[] args){Gtk.init (ref args);var webView = new Main ();var window = new Gtk.Window();window.add(webView);window.show_all ();Gtk.main ();return 0;}} Copy the accompanied webkit-1.0.vapi and javascriptcore.vapi files into the src folder. The javascriptcore.vapi file is needed because some distributions do not have this .vapi file in their repositories. Run the application. The following output will be displayed: What just happened? The first thing we do is include the WebKit and JavaScriptCore namespaces. Note, in the following code snippet, that the JavaScriptCore namespace is abbreviated as JSCore: using WebKit;using JSCore; In the Main function, we load HTML content into the WebView widget. We display a level 1 heading and then call the alert function. The alert function displays a string returned by the hello function inside the HelloJSCore class, as shown in the following code: public Main (){load_html_string("<h1>Hello</h1>" +"<script>alert(HelloJSCore.hello())</script>","/"); In the preceding code snippet, we can see that the client-side JavaScript code is as follows: alert(HelloJSCore.hello()) And we can also see that we call the hello function from the HelloJSCore class as a static function. It means that we don't instantiate the HelloJSCore object before calling the hello function. In WebView, we initialize the class defined in the Vala class when we get the window_object_cleared signal. This signal is emitted whenever a page is cleared. The initialization is done in setup_js_class and this is also where we pass the JSCore global context into. The global context is where JSCore keeps the global variables and functions. It is accessible by every code. window_object_cleared.connect ((frame, context) => {setup_js_class ((JSCore.GlobalContext)context);}); The following snippet of code contains the function, which we want to expose to the clientside JavaScript. The function just returns a Hello from JSCore string message: public static JSCore.Value helloFromVala (Context ctx,JSCore.Object function,JSCore.Object thisObject,JSCore.Value[] arguments,out JSCore.Value exception) {exception = null;var text = new String.with_utf8_c_string ("Hello from JSCore");return new JSCore.Value.string (ctx, text);} Then we need to put a boilerplate code that is needed to expose the function and other members of the class. The first part of the code is the static function index. This is the mapping between the exposed function and the name of the function defined in the wrapper. In the following example, we map the hello function, which can be used in the client side, with the helloFromVala function defined in the code. The index is then ended with null to mark the end of the array: static const JSCore.StaticFunction[] js_funcs = {{ "hello", helloFromVala, PropertyAttribute.ReadOnly },{ null, null, 0 }}; The next part of the code is the class definition. It is about the structure that we have to fill, so that JSCore would know about the class. All of the fields are filled with null, except for those we want to make use of. In this example, we use the static function for the hello function. So we fill the static function field with js_funcs, which we defined in the preceding code snippet: static const ClassDefinition js_class = {0, // versionClassAttribute.None, // attribute"HelloJSCore", // classNamenull, // parentClassnull, // static valuesjs_funcs, // static functionsnull, // initializenull, // finalizenull, // hasPropertynull, // getPropertynull, // setPropertynull, // deletePropertynull, // getPropertyNamesnull, // callAsFunctionnull, // callAsConstructornull, // hasInstancenull // convertToType}; After that, in the the setup_js_class function, we set up the class to be made available in the JSCore global context. First, we create JSCore.Class with the class definition structure we filled previously. Then, we create an object of the class, which is created in the global context. Last but not least, we assign the object with a string identifier, which is HelloJSCore. After executing the following code, we will be able to refer HelloJSCore on the client side: void setup_js_class (GlobalContext context) {var theClass = new Class (js_class);var theObject = new JSCore.Object (context, theClass,context);var theGlobal = context.get_global_object ();var id = new String.with_utf8_c_string ("HelloJSCore");theGlobal.set_property (context, id, theObject,PropertyAttribute.None, null);}
Read more
  • 0
  • 0
  • 14101

article-image-developing-web-project-jasperreports
Packt
27 May 2013
11 min read
Save for later

Developing a Web Project for JasperReports

Packt
27 May 2013
11 min read
(For more resources related to this topic, see here.) Setting the environment First, we need to install the required software, Oracle Enterprise Pack for Eclipse 12c, from http://www.oracle.com/technetwork/middleware/ias/ downloads/wls-main-097127.html using Installers with Oracle WebLogic Server, Oracle Coherence and Oracle Enterprise Pack for Eclipse, and download the Oracle Database 11g Express Edition from http://www.oracle.com/technetwork/products/express-edition/overview/index.html. Setting the environment requires the following tasks: Creating database tables Configuring a data source in WebLogic Server 12c Copying JasperReports required JAR files to the server classpath First create a database table, which shall be the data source for creating the reports, with the following SQL script. If a database table has already been created, the table may be used for this article too. CREATE TABLE OE.Catalog(CatalogId INTEGER PRIMARY KEY, Journal VARCHAR(25), Publisher VARCHAR(25),Edition VARCHAR(25), Title Varchar(45), Author Varchar(25)); INSERT INTO OE.Catalog VALUES('1', 'Oracle Magazine', 'Oracle Publishing', 'Nov-Dec 2004', 'Database Resource Manager', 'Kimberly Floss'); INSERT INTO OE.Catalog VALUES('2', 'Oracle Magazine', 'Oracle Publishing', 'Nov-Dec 2004', 'From ADF UIX to JSF', 'Jonas Jacobi'); INSERT INTO OE.Catalog VALUES('3', 'Oracle Magazine', 'Oracle Publishing', 'March-April 2005', 'Starting with Oracle ADF ', 'Steve Muench'); Next, configure a data source in WebLogic server with JNDI name jdbc/OracleDS. Next, we need to download some JasperReports JAR files including dependencies. Download the JAR/ZIP files listed below and extract the zip/tar.gz to a directory, c:/jasperreports for example.   JAR/ZIP Donwload URL jasperreports-4.7.0.jar http://sourceforge.net/projects/ jasperreports/files/jasperreports/JasperReports%204.7.0/ itext-2.1.0 http://mirrors.ibiblio.org/pub/mirrors/maven2/com/ lowagie/itext/2.1.0/itext-2.1.0.jar commons-beanutils-1.8.3-bin.zip http://commons.apache.org/beanutils/download_beanutils.cgi commons-digester-2.1.jar http://commons.apache.org/digester/download_digester.cgi commons-logging-1.1.1-bin http://commons.apache.org/logging/download_logging.cgi  poi-bin-3.8-20120326 zip or tar.gz http://poi.apache.org/download.html#POI-3.8 All the JasperReports libraries are open source. We shall be using the following JAR files to create a JasperReports report: JAR File Description commons-beanutils-1.8.3.jar JavaBeans utility classes commons-beanutils-bean-collections-1.8.3.jar Collections framework extension classes commons-beanutils-core-1.8.3.jar JavaBeans utility core classes commons-digester-2.1.jar Classes for processing XML documents. commons-logging-1.1.1.jar Logging classes iText-2.1.0.jar PDF library jasperreports-4.7.0.jar JasperReports API poi-3.8-20120326.jar, poi-excelant-3.8-20120326.jar, poi-ooxml-3.8-20120326.jar, poi-ooxml-schemas-3.8-20120326.jar, poi-scratchpad-3.8-20120326.jar Apache Jakarta POI  classes and dependencies. Add the Jasper Reports required by the JAR files to the user_projectsdomains base_domainbinstartWebLogic.bat script's CLASSPATH variable: set SAVE_CLASSPATH=%CLASSPATH%;C:jasperreportscommonsbeanutils- 1.8.3commons-beanutils-1.8.3.jar;C:jasperreportscommonsbeanutils- 1.8.3commons-beanutils-bean-collections-1.8.3.jar;C: jasperreportscommons-beanutils-1.8.3commons-beanutils-core- 1.8.3.jar;C:jasperreportscommons-digester-2.1.jar;C:jasperreports commons-logging-1.1.1commons-logging-1.1.1.jar;C:jasperreports itext-2.1.0.jar;C:jasperreportsjasperreports-4.7.0.jar;C: jasperreportspoi-3.8poi-3.8-20120326.jar;C:jasperreportspoi- 3.8poi-scratchpad-3.8-20120326.jar;C:jasperreportspoi-3.8poiooxml- 3.8-20120326.jar;C:jasperreportspoi-3.8.jar;C:jasperreports poi-3.8poi-excelant-3.8-20120326.jar;C:jasperreportspoi-3.8poiooxml- schemas-3.8-20120326.jar Creating a Dynamic Web project in Eclipse First, we need to create a web project for generating JasperReports reports. Select File | New | Other. In New wizard select Web | Dynamic Web Project. In Dynamic Web Project configuration specify a Project name (PDFExcelReports for example), select the Target Runtime as Oracle WebLogic Server 11g R1 ( 10.3.5). Click on Next. Select the default Java settings; that is, Default output folder as build/classes, and then click on Next. In WebModule, specify ContextRoot as PDFExcelReports and Content Directory as WebContent. Click on Finish. A web project for PDFExcelReports gets generated. Right-click on the project node in ProjectExplorer and select Project Properties. In Properties, select Project Facets. The Dynamic Web Module project facet should be selected by default as shown in the following screenshot: Next, create a User Library for JasperReports JAR files and dependencies. Select Java Build Path in Properties. Click on Add Library. In Add Library, select User Library and click on Next. In User Library, click on User Libraries. In User Libraries, click on New. In New User Library, specify a User library name (JasperReports) and click on OK. A new user library gets added to User Libraries. Click on Add JARs to add JAR files to the library. The following screenshot shows the JasperReports that are added: Creating the configuration file We require a JasperReports configuration file for generating reports. JasperReports XML configuration files are based on the jasperreport.dtd DTD, with a root element of jasperReport. We shall specify the JasperReports report design in an XML configuration bin file, which we have called config.xml. Create an XML file config.xml in the webContent folder by selecting XML | XML File in the New wizard. Some of the other elements (with commonly used subelements and attributes) in a JasperReports configuration XML file are listed in the following table: XML Element Description Sub-Elements Attributes jasperReport Root Element reportFont, parameter, queryString, field, variable, group, title, pageHeader, columnHeader, detail, columnFooter, pageFooter. name, columnCount, pageWidth, pageHeight, orientation, columnWidth, columnSpacing, leftMargin, rightMargin, topMargin, bottomMargin. reportFont Report level font definitions - name, isDefault, fontName, size, isBold, isItalic, isUnderline, isStrikeThrough, pdfFontName, pdfEncoding, isPdfEmbedded parameter Object references used in generating a report. Referenced with P${name} parameterDescription, defaultValueExpression name, class queryString Specifies the SQL query for retrieving data from a database. - - field Database table columns included in report. Referenced with F${name} fieldDescription name, class variable Variable used in the report XML file. Referenced with V${name} variableExpression, initialValueExpression name,class. title Report title band - pageHeader Page Header band - columnHeader Specifies the different columns in the report generated. band - detail Specifies the column values band - columnFooter Column footer band - A report section is represented with the band element. A band element includes staticText and textElement elements. A staticText element is used to add static text to a report (for example, column headers) and a textElement element is used to add dynamically generated text to a report (for example, column values retrieved from a database table). We won't be using all or even most of these element and attributes. Specify the page width with the pageWidth attribute in the root element jasperReport. Specify the report fonts using the reportFont element. The reportElement elements specify the ARIAL_NORMAL, ARIAL_BOLD, and ARIAL_ITALIC fonts used in the report. Specify a ReportTitle parameter using the parameter element. The queryString of the example JasperReports configuration XML file catalog.xml specifies the SQL query to retrieve the data for the report. <queryString><![CDATA[SELECT CatalogId, Journal, Publisher, Edition, Title, Author FROM OE.Catalog]]> </queryString> The PDF report has the columns CatalogId, Journal, Publisher, Edition, Title, and Author. Specify a report band for the report title. The ReportTitle parameter is invoked using the $P {ReportTitle} expression. Specify a column header using the columnHeader element. Specify static text with the staticText element. Specify the report detail with the detail element. A column text field is defined using the textField element. The dynamic value of a text field is defined using the textFieldExpression element: <textField> <reportElement x="0" y="0" width="100" height="20"/> <textFieldExpression class="java.lang.String"><![CDATA[$F{Cata logId}]]></textFieldExpression> </textField> Specify a page footer with the pageFooter element. Report parameters are defined using $P{}, report fields using $F{}, and report variables using $V{}. The config. xml file is listed as follows: <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE jasperReport PUBLIC "-//JasperReports//DTD Report Design// EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd"> <jasperReport name="PDFReport" pageWidth="975"> The following code snippet specifies the report fonts: <reportFont name="Arial_Normal" isDefault="true" fontName="Arial" size="15" isBold="false" isItalic="false" isUnderline="false" isStrikeThrough="false" pdfFontName="Helvetica" pdfEncoding="Cp1252" isPdfEmbedded="false"/> <reportFont name="Arial_Bold" isDefault="false" fontName="Arial" size="15" isBold="true" isItalic="false" isUnderline="false" isStrikeThrough="false" pdfFontName="Helvetica-Bold" pdfEncoding="Cp1252" isPdfEmbedded="false"/> <reportFont name="Arial_Italic" isDefault="false" fontName="Arial" size="12" isBold="false" isItalic="true" isUnderline="false" isStrikeThrough="false" pdfFontName="Helvetica-Oblique" pdfEncoding="Cp1252" isPdfEmbedded="false"/> The following code snippet specifies the parameter for the report title, the SQL query to generate the report with, and the report fields. The resultset from the SQL query gets bound to the fields. <parameter name="ReportTitle" class="java.lang.String"/> <queryString><![CDATA[SELECT CatalogId, Journal, Publisher, Edition, Title, Author FROM Catalog]]></queryString> <field name="CatalogId" class="java.lang.String"/> <field name="Journal" class="java.lang.String"/> <field name="Publisher" class="java.lang.String"/> <field name="Edition" class="java.lang.String"/> <field name="Title" class="java.lang.String"/> <field name="Author" class="java.lang.String"/> Add the report title to the report as follows: <title> <band height="50"> <textField> <reportElement x="350" y="0" width="200" height="50" /> <textFieldExpression class="java.lang. String">$P{ReportTitle}</textFieldExpression> </textField> </band> </title> <pageHeader> <band> </band> </pageHeader> Add the column's header as follows: <columnHeader> <band height="20"> <staticText> <reportElement x="0" y="0" width="100" height="20"/> <textElement> <font isUnderline="false" reportFont="Arial_Bold"/> </textElement> <text><![CDATA[CATALOG ID]]></text> </staticText> <staticText> <reportElement x="125" y="0" width="100" height="20"/> <textElement> <font isUnderline="false" reportFont="Arial_Bold"/> </textElement> <text><![CDATA[JOURNAL]]></text> </staticText> <staticText> <reportElement x="250" y="0" width="150" height="20"/> <textElement> <font isUnderline="false" reportFont="Arial_Bold"/> </textElement> <text><![CDATA[PUBLISHER]]></text> </staticText> <staticText> <reportElement x="425" y="0" width="100" height="20"/> <textElement> <font isUnderline="false" reportFont="Arial_Bold"/> </textElement> <text><![CDATA[EDITION]]></text> </staticText> <staticText> <reportElement x="550" y="0" width="200" height="20"/> <textElement> <font isUnderline="false" reportFont="Arial_Bold"/> </textElement> <text><![CDATA[TITLE]]></text> </staticText> <staticText> <reportElement x="775" y="0" width="200" height="20"/> <textElement> <font isUnderline="false" reportFont="Arial_Bold"/> </textElement> <text><![CDATA[AUTHOR]]></text> </staticText> </band> </columnHeader> The following code snippet shows how to add the report detail, which consists of values retrieved using the SQL query from the Oracle database: <detail> <band height="20"> <textField> <reportElement x="0" y="0" width="100" height="20"/> <textFieldExpression class="java.lang.String"><![CDATA[$F{Cata logId}]]></textFieldExpression> </textField> <textField pattern="0.00"> <reportElement x="125" y="0" width="100" height="20"/> <textFieldExpression class="java.lang.String"><![CDATA[$F{Jour nal}]]></textFieldExpression> </textField> <textField pattern="0.00"> <reportElement x="250" y="0" width="150" height="20"/> <textFieldExpression class="java.lang.String"><![CDATA[$F{Publ isher}]]></textFieldExpression> </textField> <textField> <reportElement x="425" y="0" width="100" height="20"/> <textFieldExpression class="java.lang.String"><![CDATA[$F{Edit ion}]]></textFieldExpression> </textField> <textField pattern="0.00"> <reportElement x="550" y="0" width="200" height="20"/> <textFieldExpression class="java.lang. String"><![CDATA[$F{Title}]]></textFieldExpression> </textField> <textField> <reportElement x="775" y="0" width="200" height="20"/> <textFieldExpression class="java.lang. String"><![CDATA[$F{Author}]]></textFieldExpression> </textField> </band> </detail> Add the column and page footer including the page number as follows: <columnFooter> <band> </band> </columnFooter> <pageFooter> <band height="15"> <staticText> <reportElement x="0" y="0" width="40" height="15"/> <textElement> <font isUnderline="false" reportFont="Arial_Italic"/> </textElement> <text><![CDATA[Page #]]></text> </staticText> <textField> <reportElement x="40" y="0" width="100" height="15"/> <textElement> <font isUnderline="false" reportFont="Arial_Italic"/> </textElement> <textFieldExpression class="java.lang. Integer"><![CDATA[$V{PAGE_NUMBER}]]></textFieldExpression> </textField> </band> </pageFooter> <summary> <band> </band> </summary> </jasperReport> We need to create a JAR file for the config.xml file and add the JAR file to the WebLogic Server's domain's lib directory. Create a JAR file using the following command from the directory containing the config.xml as follows: >jar cf config.jar config.xml Add the config.jar file to the user_projectsdomainsbase_domainlib directory, which is in the classpath of the server.
Read more
  • 0
  • 0
  • 5964
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime
article-image-connecting-backend-servers-should-know
Packt
27 May 2013
5 min read
Save for later

Connecting to backend servers (Should know)

Packt
27 May 2013
5 min read
(For more resources related to this topic, see here.) Getting ready If you have a server architecture diagram, that's a good place to start listing all the required servers and grouping them, but you'll also need some technical data about those servers. You may find this information in a server monitoring diagram, where you will find the IP addresses, ports, and luckily a probing URL for health checks. In our case, the main VCL configuration file default.vcl is located at /etc/varnish and defines the configuration that the Varnish Cache will use during the life cycle of the request, including the backend servers list. How to do it... Open the default vcl file by using the following command: # sudo vim /etc/varnish/default.vcl A simple backend declaration would be: backend server01 {.host = "localhost";.port = "8080";} This small block of code indicates the name of the backend (server01), and also the hostname or IP, and which port to connect to. Save the file and reload the configuration using the following command: # sudo service varnish reload At this point, Varnish will proxy every request to the first declared backend using its default VCL file. Give it a try and access a known URL (like the index of your website) through the Varnish Cache and make sure that the content is delivered as it would be without Varnish. For testing purposes, this is an okay backend declaration, but we need to make sure that our backend servers are up and waiting for requests before we really start to direct web traffic to them. Let's include a probing request to our backend: backend website {.host = "localhost";.port = "8080";.probe = {.url = "/favicon.ico";.timeout = 60ms;.interval = 2s;.window = 5;.threshold = 3;}} Varnish will now probe the backend server using the provided URL with a timeout of 60 ms, every couple of seconds. To determine if a backend is healthy, it will analyze the last five probes. If three of them result in 200 – OK, the backend is marked as Healthy and the requests are forwarded to this backend; if not, the backend is marked as Sick and will not receive any incoming requests until it's Healthy again. Probe the backend servers that require additional information: In case your backend server requires extra headers or has an HTTP basic authentication, you can change the probing from URL to Request and specify a raw HTTP request. When using the Request probe, you'll always need to provide a Connection: close header or it will not work. This is shown in the following code snippet: backend api {.host = "localhost";.port = "8080";.probe = {.request ="GET /status HTTP/1.1""Host: www.yourhostname.com""Connection: close""X-API-Key: e4d909c290d0fb1ca068ffaddf22cbd0""Accept: application/json".timeout = 60ms;.interval = 2s;.window = 5;.threshold = 3;}} Choose a backend server based on incoming data: After declaring your backend servers, you can start directing the clients' requests. The most common way to choose which backend server will respond to a request is according to the incoming URL, as shown in the following code snippet: vcl_recv {if ( req.url ~ "/api/") {set req.backend = api;} else {Set req.backend = website;}} Based on the preceding configuration, all requests that contain /api/ (www.yourdomain.com/api/) in the URL will be sent to the backend named api and the others will reach the backend named website. You can also pick the correct backend server, based on User-agent header, Client IP (geo-based), and pretty much every information that comes with the request. How it works... By probing your backend servers, you can automate the removal of a sick backend from your cluster, and by doing so, you avoid delivering a broken page to your customer. As soon as your backend starts to behave normally, Varnish will add it back to the cluster pool. Directing requests to the appropriate backend server is a great way to make sure that every request reaches its destination, and gives you the flexibility to provide content based on the incoming data, such as a mobile device or an API request. There's more... If you have lots of servers to be declared as backend, you can declare probes as a separated configuration block and make reference to that block later at the backend specifications, avoiding repetition and improving the code's readability. probe favicon {.url = "/favicon.ico";.timeout = 60ms;.interval = 2s;.window = 5;.threshold = 3;}probe robots {.url = "/robots.txt";.timeout = 60ms;.interval = 2s;.window = 5;.threshold = 3;}backend server01 {.host = "localhost";.port = "8080";.probe = favicon;}backend server02 {.host = "localhost";.port = "8080";.probe = robots;} The server01 server will use the probe named favicon, and the server02 server will use the probe named robots. Summary This article explained how to connect to backend servers. Resources for Article : Further resources on this subject: Security in Plone Sites [Article] Professional Plone Development: Foreword by Alexander Limi [Article] Microsoft SQL Server 2008 High Availability: Understanding Domains, Users, and Security [Article]
Read more
  • 0
  • 0
  • 9433

article-image-designer-friendly-templates
Packt
24 May 2013
11 min read
Save for later

Designer Friendly Templates

Packt
24 May 2013
11 min read
(For more resources related to this topic, see here.) Designer friendly templates (Simple) Inherent to web applications is this breach in technology. We need to combine business logic on the server with HTML pages and JavaScript on the client side. The nicely encapsulated server-side business logic then hits a client-side technology that really was intended to structure pages of text. You somehow need to weave the backend functionality into these web pages. Countless approaches exist that try to bridge the two. Lift is also unique in this regard in that it lets you create valid HTML5 or XHTML templates that contain absolutely no business functionality, yet it manages to combine the two in an inspiring and clear way. Getting ready Again, we will use the example application from the Preparing your development environment (Simple) recipe to talk about the different concepts. You will find the templates under the webapp directory inside src/main. If you open them, you will see they're plain and simple HTML files. It's easy for designers to edit them with the tools they know. How to do it... Lift's page templates are valid XHTML or HTML5 documents that are parsed and treated as NodeSeq documents (XML, basically) until served to the browser. The standard path for everything webby is src/main/webapp inside your project. Say you enter a URL liftapp.com/examples/templates and provide the user with access to this page (see the SiteMap task for details), Lift will search the templates.html page inside the examples directory located at src/main/webapp. That's the normal case. Of course you can rewrite URLs and point to something entirely different, but let's now consider the common case. Let's look at a simple template for the example applications' home page, http://localhost:8080: <!DOCTYPE html><html><head><meta content="text/html; charset=UTF-8"http-equiv="content-type" ></meta><title>Home</title></head><body class="lift:content_id=main"><div id="main"data-lift="surround?with=default;at=content"><h2>Welcome to your project!</h2><p><span data-lift="helloWorld.howdy">Welcome to your Lift app at<span id="time">Time goes here</span></span></p></div></body></html> Granted, this page doesn't do much, but that's all there is to this page. In most applications you have some common parts on a page and some that change content. It's easy to define these hierarchies of templates. In your page template you define by which parent template you want it to be surrounded with and at which place. The parent template itself can also be surrounded by another template, and so on. This is a useful feature to extract common parts of a page into base templates and build on top of these to finally define the structure and surrounding chrome of your pages. The parent template for this page is called default.html and is searched for in the templates-hidden folder. Any file that is embedded into a page is searched underneath templates-hidden. We omit the CSS and some of the Boilerplate and just show the interesting parts of the parent template's content: <body><div class="container">...<div class="column span-6 colborder sidebar"><hr class="space" ><span data-lift="Menu.builder?group=main"></span><hr class="space" ><span data-lift="Menu.builder?group=examples"></span><hr class="space" ><span data-lift="Menu.builder?group=PostingUsers"></span><div data-lift="Msgs?showAll=true"></"></"></div><hr class="space" ></div><div class="column span-17 last"><div id="content">The main content goes here</div></div>...</body> This template defines a sidebar and places our menus there. It defines a place where messages are shown that are sent from Lift with its S.notice, S.warning, and S.error methods. And finally, it defines an ID (content) that marks the element receiving the page content. How it works... Let's walk through the code snippet given in the preceding section and see how the pieces fit together. <body class="lift:content_id=main"> In the page template we tell Lift where the template actually starts. You can create complete, valid HTML pages and then make Lift cut the central piece out for its rendering process, and your designers can still work with complete pages that they can process in isolation from the rest. This line tells Lift that the content starts with the element with the ID, main. The next thing we do is to define a parent template that we use to surround the page with. This way, we define essential page layout markup only once and include it everywhere it's needed. Here's how you surround a page with a parent template: <div id="main" data-lift="lift:surround?with=default;at=content">… your content here…</div> In the class attribute of the div element you call the surround snippet and hand it over the with=default and at=content parameters. The surround snippet now knows that it should find a template called default.html and insert the content of this div element into the parent template at the point defined by the ID, content. Speaking of snippets, it is a mechanism to process parts of your HTML files the same way for built-in snippets as it is for your own. Snippets are pieces of logic that get weaved into the markup. We'll get to this integral part of Lift development really soon. Lift templates are the files that are not defined in the SiteMap. They are located at a subfolder called templates-hidden. They cannot be accessed directly from the URL, but only through code by directly opening it or through the surround-and-embed mechanisms inside other templates or pages. Have a look at the parent template default.html shown previously. This file, along with the other files we discuss here, is available in the source code that comes with the book. It's a standard HTML5 file defining some styles and finally defining a div element to bind the child content: <div id="content">The main content will get bound here</div> Lift will remove the text inside the DIV and replace it with the actual content, as shown in the following screenshot: A few other things at the top of the template are worth noting: <style class="lift:CSS.blueprint"></style><style class="lift:CSS.fancyType"></style><script id="jquery" src = "/classpath/jquery.js""type="text/javascript"></script> Lift comes bundled with the Blueprint CSS framework (http://blueprintcss.org/) and a version of jQuery (http://jquery.com/). It's intended to make it easier for you to start, but by no means are you bound to using Blueprint or the included jQuery version. Just use your own CSS framework (there's a recipe on using Twitter's Bootstrap) or jQuery where it makes sense. For instance, to use a hosted version of the latest jQuery library, you would replace the script tag from the preceding code snippet with the following: <script type="text/javascript" src = "http://code.jquery.com/jquery-1.8.2.min.js"></script> Lift provides some standard snippets which you can use to build up your pages. The default.html template utilizes a snippet to render a menu and another snippet to place messages on the page: <span data-lift="Menu.builder?group=main"></span> When you define the element that encloses the menu, Lift will automatically render it. If you omit the group parameter, all menu entries will be rendered. Having that parameter will restrict the menu only to the items within that group. You can assign a menu group (called LocGroup) in the SiteMap you defined in the Boot class. <div data-lift="Msgs?showAll=true"></div> This snippet call will render messages that are produced by the backend application in this spot. There's more... We will now have a look at execution order. In normal execution mode, Lift first evaluates the outer snippets and then layer by layer moves to the inner snippets. If you want to include the result of some inner snippet evaluations to the input of the outer snippets, you need to reverse that process. For that very reason, Lift provides a snippet parameter, eager_eval=true, that you add to the outer snippet: <div data-lift="ImOuter?eager_eval=true">...<div data-lift="ImInner">...</div>...</div> Adding that parameter causes Lift to first evaluate the inner snippet and then add the result of the inner snippet call to the input that is processed by the outer snippet. You can also embed templates into your page or other templates. That's the opposite operation of surrounding a page, but equally simple. In your page, use the embed snippet to embed a template: <div data-lift="embed?what=/examples/templates/awesome"></div> The what parameter defines the path to the template, which is searched for within the webapp directory. We will now see the programmatic embedding of templates. You can easily search a template and process it programmatically. In that case you need to specify the templates-hidden directory; that way you are able to access top-level pages as well. val ns:Box[NodeSeq] = S.runTemplate(List("templates-hidden","examples", "templates", "awesome")) Please see the EmbedTemplates snippet for an example of how to programmatically access templates and apply transformations before embedding it. <div data-lift="EmbedTemplate?what=/examples/templates/awesome"></div> As you can see, our own templates are called just the same way as Lift's default templates, and they can do the same things. Programmatic access to templates is useful, for instance when you want to send HTML e-mails. Inside the mail sender you would grab the template, process it (see CSS Selectors), and send the complete HTML to the recipient. There are a myriad more reasons or use cases when you want to access your templates from your Scala code. Just keep in the back of your mind that you can do it. The S.runTemplate method will fetch the template and process it. That means it will look for any embedded Lift snippet calls and execute them. These snippet calls could potentially embed other templates recursively. If you do not want the template to be processed, you can retrieve it like this: val tpl:Box[NodeSeq] = Templates(List("templates-hidden", "examples","templates", "awesome") Lift templates are very powerful, and they have to be. They are at the basis of every web application and need to handle a lot of different scenarios. The separation between the markup and the logic keeps the templates clean and prohibits your designers from breaking code. It might take a while to adopt to this template style if you come from a framework that mixes markup and code. We believe, especially in larger applications, you will soon see the benefits of a clear separation and encapsulation of your logic in reusable pieces. Speaking of reusable pieces, let's head over to snippets, Lift's way to plug functionality into templates. The Lift wiki offers further information about templates and binding at the following links: http://www.assembla.com/spaces/liftweb/wiki/Designer_Friendly_ Templates http://www.assembla.com/spaces/liftweb/wiki/Templates_and_ Binding Summary In this article, we learned about designer friendly templates. Resources for Article : Further resources on this subject: RESTful Web Service Implementation with RESTEasy [Article] Spring Roo 1.1: Working with Roo-generated Web Applications [Article] Deploying your Applications on WebSphere Application Server 7.0 (Part 1) [Article]
Read more
  • 0
  • 0
  • 2426

article-image-html5-presentations-creating-our-initial-presentation
Packt
24 May 2013
10 min read
Save for later

HTML5 Presentations: Creating our initial presentation

Packt
24 May 2013
10 min read
Creating our initial presentation This recipe will teach you how to create a basic HTML5 presentation using reveal.js. We will cover the initial markup and setup. The presentation created here will be used throughout the rest of the book. Getting ready Before we start, we need to download the reveal.js script and assets. To do that, simply visit https://github.com/hakimel/reveal.js/downloads and get the latest version of reveal. Now open your favorite text editor and let's work on the presentation markup. How to do it... To create our initial presentation perform the following steps: The first step is to create an HTML file and save it as index.html. Then copy the reveal.js files to the same directory of our HTML file, keeping the following structure (highlighted files are the ones we are using in this recipe): index.html -css ---reveal.min.css ---print ---shaders ---theme -----default.css -----source -----template -js ---reveal.min.js -lib ---css ---font ---js -----head.min.js -plugin ---highlight ---markdown ---notes ---notes-server ---postmessage ---remotes ---zoom-js Now we need to write our initial HTML5 markup, as follows: <!doctype html> <html> <head> <meta charset="utf-8"> <title>HTML5 Presentations How-To</title> </head> <body> <div class="reveal"> <div class="slides"> </div> </div> </body> </html> With our initial markup ready we include the reveal.js base stylesheet and script file plus the default theme stylesheet. We will also need to include the HeadJS JavaScript loader in order to manage reveal.js plugins. The stylesheets will go directly below the title tag, while the script files must be included before the closing body tag: <head> <meta charset="utf-8"> <title>HTML5 Presentations How-To</title> <link rel="stylesheet" href = "css/reveal.min.css"> <link rel="stylesheet" href = "css/theme/default.css"> </head> <body> ... <script src = "lib/js/head.min.js"></script> <script src = "js/reveal.min.js"></script> </body> The fourth step is to create the elements for our slides. Our first presentation will have four slides, so we must add four section elements to our slides div, as follows: <div class="reveal"> <div class="slides"> <section> <h1>HTML5 Presentations</h1> <h3>How to create presentations for web browsers</h3> </section> <section> <h1>About this presentation</h1> <p>This is the example presentation for the book HTML5 Presentations How-To</p> </section> <section> <h1>reveal.js</h1> <ul> <li>created by Hakim El Hattab</li> <li>open source</li> </ul> </section> <section> <h1>References</h1> <ol> <li><a href = "http://hakim.se/">http://hakim.se/</a></li> <li><a href = "https://github.com/hakimel/reveal. js">https://github.com/hakimel/reveal.js</a></li> </ol> </section> </div> </div> After that, we initialize the reveal.js JavaScript object, right after the reveal.js script tag, as follows: <body> ... <script src = "js/reveal.min.js"></script> <script> Reveal.initialize({ controls: true, keyboard: true, center: true, transition: 'default' }); </script> </body> For the last step, open index.html using the browser of your choice and check out how our initial HTML5 presentation looks, as shown in the following screenshot: How it works... reveal.js is a powerful JavaScript library that allows us to create presentations using a web browser. It was created by Hakim El Hattab, a web developer known for his experiments with CSS3 transitions and JavaScript animations. By performing the preceding steps we created a regular HTML5 presentation. We have used reveal.js default themes and some minor configurations just to get started. We started with a basic HTML5 structure. It is important to bear in mind that our presentation is, before anything else, an HTML and it should be rendered normally in the browser. The presentation must follow a structure expected by the reveal.js script. First, our HTML must have one div with reveal as a class attribute. That div must contain another div with slides as a class attribute. The slides div must contain one or more section elements, each one representing a slide. As we will see in the Creating vertical/nested slides (Simple) recipe, it is possible to nest slides, creating a vertical navigation. Each slide can contain any HTML or markdown content. We started with just a few elements but we will enrich our presentation through each recipe. reveal.js comes with multiple themes, available under the css/theme directory. For our initial presentation, we are using the default.css theme. Other options would be beige, night, serif, simple, and sky. Theming will be covered in the Theming (Medium) recipe. With all the markup and styles set, we initialized the reveal.js JavaScript object by using the initialize method. We used only four options, as follows: Reveal.initialize({ controls: true, keyboard: true, center: true, transition: 'default' }); First we enabled the navigation controls at the user interface, setting the controls option to true. We activated keyboard navigation using the arrow keys and also centered the slides' content. The last option sets the transition between slides to default. The next recipe will cover the full list of available options. There's more... reveal.js will work on any browser, but modern browsers are preferred due to animations and 3D effects. We will also need to use external plugins in order to extend our presentation features. Dependencies As previously mentioned, reveal.js uses the HeadJS library to manage plugins and dependencies. You can use only reveal.js if you want, but some useful resources (such as speaker notes and zoom) are only enabled using plugins. The plugins can be loaded through the initialize method and we will see more about them in the Plugins and extensions (Medium) recipe. Overview and blackout modes While on our presentation, pressing the Esc key will switch to overview mode where you can interact with every slide. Another useful resource is the blackout mode. If you want to pause and draw attention from your audience, you can press the B key to alternate between normal and blackout modes, and hide your current slide data. Browser support reveal.js will work better on browsers with full support for CSS 3D animations (Chrome, Safari, Firefox, and Internet Explorer 10), but fallbacks (such as 2D transitions) are available for older browsers. Presentations will not work on Internet Explorer 7 or lower. In this recipe we have created our initial HTML5 presentation using reveal.js default options and theme. Using reveal.js JavaScript API reveal.js provides an extended API to control our presentation behavior. With reveal.js API methods we can move to previous and next slides, get the current index, toggle overview mode, and more. How to do it… To use reveal.js JavaScript API perform the following steps: Using reveal.js API we will create a navigation bar that will be positioned at the bottom of our presentation screen, containing links to our main slides plus links to the first, next, previous, and last slides. We will start by adding some HTML5 markup, including reveal.js API method calls inside the onclick attribute of our navigation elements: <body> <div id="navigation-bar"> <nav> <a href="#" onclick="Reveal.slide(0);">&laquo;&laquo; first</a> <a href="#" onclick="Reveal.prev();">&laquo; previous</a> <a href="#" onclick="Reveal.slide(0);">html5 presentations</ a> <a href="#" onclick="Reveal.slide(1);">about this presentation</a> <a href="#" onclick="Reveal.slide(2);">reveal.js</a> <a href="#" onclick="Reveal.slide(3);">references</a> <a href="#" onclick="Reveal.slide(4);">about the author</a> <a href="#" onclick="Reveal.slide(5);">why use reveal.js</a> <a href="#" onclick="Reveal.next();">next &raquo;</a> <a href="#" onclick="Reveal.slide(5);">last &raquo;&raquo;</ a> </nav> </div> … </body> Our navigation bar will need a CSS of its own. Let's add some new style rules to our style tag: <style> … #navigation-bar { position: fixed; left: 0; bottom: 2px; width: 100%; height: 50px; z-index: 20; background-color: #fff; border-top: 6px solid #df0d32; font-family: Helvetica, Arial, sans-serif; } #navigation-bar nav { padding: 15px 0; text-align: center; } #navigation-bar a { display: inline-block; padding: 0 10px; border-right: 2px solid #ccc; text-decoration: none; color: #df0d32; } #navigation-bar a:last-child { border-right: none; } #navigation-bar a:hover { text-decoration: underline; } </style> If you reload the presentation now, you will see our brand new navigation bar at the bottom, and if you click on the links, you will be taken directly to the referenced slides or actions (first, next, previous, last). How it works... reveal.js JavaScript API allows us to control our presentation behavior using JavaScript code. In the preceding example we have used almost all methods available. Let's take a closer look at them: Option Description Reveal.slide(indexh, indexv, indexf) Slides to the specified index (the indexh parameter). The first slide will have 0 as index, the second has 1, and so on. You can also specify the vertical index (the indexv parameter) in case of nested slides and the fragment index (the indexf parameter) inside the slide. Reveal.left() Goes to the previous slide in the horizontal line of the presentation. Reveal.right() Goes to the next slide in the horizontal line of the presentation. Reveal.up() Changes to the following nested slide. Reveal.down() Returns to the previous nested slide. Reveal.prev() Goes to the previous slide, horizontal or vertical. Reveal.next() Goes to the next slide, horizontal or vertical. Reveal.prevFragment() Switches to the previous fragment inside the current slide. Reveal.nextFragment() Switches to the next fragment inside the current slide. Reveal.toggleOverview() Toggles overview mode. Reveal.getPreviousSlide() Returns the DOM element of the previous slide. Reveal.getCurrentSlide() Returns the DOM element of the next slide. Reveal.getIndices() Returns an object with the current indices, for example {h: 2, v: 1}. The preceding methods are available to use in any JavaScript code after the reveal.js object has been initialized. You can either use it directly on elements' attributes (such as onclick) or call it directly from JavaScript functions and listeners. Summary In this article, the Creating our initial presentation recipe explained how we can create a basic HTML5 presentation and the Using reveal.js JavaScript API recipe explored Reveal.js JavaScript API by creating a custom navigation bar. Resources for Article : Further resources on this subject: HTML5: Audio and Video Elements [Article] HTML5: Developing Rich Media Applications using Canvas [Article] Building HTML5 Pages from Scratch [Article]
Read more
  • 0
  • 0
  • 9640

article-image-article-magento-performance-optimization
Packt
24 May 2013
5 min read
Save for later

Magento Performance Optimization

Packt
24 May 2013
5 min read
(For more resources related to this topic, see here.) Using the Magento caching system A cache is a system that stores data so that future requests for that data can be served faster. Having cache is definitely a good thing, but the caching system of Magento is not super effective. How to do it... Let's begin with cache enabling, even if most users are well aware of this one. Go to your backend console and then go to System | Cache Management. By default, all caches are enabled; but some have a negative impact. You have to disable caches for the following items: Collections Data EAV types and attributes Web Services Configuration The following table shows the improvement made due to the previous settings, that is, by disabling the selected caches: Another little win, 200 milliseconds, just enough to fulfill the promise made in the previous recipes. How it works... A cache is a system that stores data so that future requests for that data can be served faster. A web cache stores copies of documents passing through it, and subsequent requests may be satisfied from the cache if a set of conditions exists. There are many hypotheses out there to explain this weird optimization. The main one is that the Magento core has to parse the cache and check in MySQL to compare updated data, and this causes a huge delay. In fact, by allowing Magento to do these kinds of operations, we don't use the full resources of our systems. Using a memory-based filesystem for caching We can easily say that the slowest component of a computer is its hard drive. Moreover, the Magento caching system makes massive use of this component. It would be amazing if we could store the Magento cache files directly inside the memory. How to do it... Open a new console on your Unix server and enter the following command: code1 The path is based on a common installation of Apache with Magento; pay attention to your configuration when typing this command. You have to repeat this command every time the server starts up or you can automatize it by adding the following line into your /etc/fstab file: code1 All the caching mechanisms of Magento will now work with a memory-based filesystem instead of the classical filesystem. How it works... This newly created filesystem is intended to appear as a mounted filesystem, but takes place in the RAM. Of course, the access time of this kind of filesystem is extremely slow in comparison with a classical hard drive. However, all files updated or created are temporary because of the nature of this filesystem. Nothing will be written in the hard drive, and if you reboot everything will be lost. If you plan to reboot your server, you have to save the volatile files in your hard drive, unmount the memory-based system, and then copy the saved data from tmpfs in the cache folder. With the second command, the folder will be remounted automatically after the reboot. Clustering If you have successfully applied all the techniques and your Magento is still slow, it means that you are a very prosperous online retailer and it's time to leave the comfortable world where there is a single server. To keep your customers satisfied, you have to invest in hardware; the tweaking time is now over. How to do it... If you own a single server, you can begin by separating your database in a dedicated server. In order to do this, you have to invest in another server and install MySQL on it (get your host to do it for you), and then extract your database from your first server and import it to your new server. Magento stays on your first server; you have to modify the database connection. Go to /app/etc/local.xml and modify the following lines to fit the new server parameters: code1 As simple as that. You now use a dedicated database server and improve your store performance. The second step in clustering our environment could be using a CDN for our images, CSS, and scripts. A CDN is an independent server optimized for delivering static content such as images, CSS, and scripts. In this way, our web server can focus on running Magento and the CDN can focus on displaying static content. The good news is that Magento has native support to do this. In your Magento backend, navigate to System | General | Web | Unsecure. If you still have CSS and JavaScript compressed from the previous recipes, you just have to copy your media directory from your main server to your CDN server. If it's not the case anymore, you have to modify the Base Skin URL field and the Base JavaScript URL field. Also, if for some reason you use the secure URL for that kind of content, don't forget to apply the changes to the secure part as well. How it works... That's a very good start. Let's summarize it. We were using a single server for all requests, and now, depending on the request, we use three different servers. The first one handles all the Magento work for building pages, the second one handles the data-related operations, and the last one provides static content. With this kind of architecture, each server can focus on only one purpose. Summary This article helped you learn Magento's built-in caching system for saving frequently asked requests. It also introduced you on Magento makes massive use of hard drive which lets you use your available RAM. It also helped you on how to configure a set of loosely connected computers working together for handling more and more customers. Resources for Article : Further resources on this subject: Magento: Exploring Themes [Article] Getting Started with Magento Development [Article] Integrating Facebook with Magento [Article]
Read more
  • 0
  • 0
  • 1725
article-image-quick-start-using-core-puppet-resource-types
Packt
23 May 2013
7 min read
Save for later

Quick start – Using the core Puppet resource types

Packt
23 May 2013
7 min read
(For more resources related to this topic, see here.) Enabling the Puppet service At this point in the process, it would be essential for me to tell you how to ensure that Puppet runs after reboot. It would be chkconfig on the RHEL systems, or update-rc.d on Debian, or smf on Solaris. But hey, why don't we use Puppet itself and let you see how Puppet saves you time and effort? Use your favorite editor to edit/etc/puppet/manifests/site.pp. Add the following code: node default {service { 'puppet':ensure => running,enable => true,}} /etc/puppet/manifests/site.pp is the one and only filename known by the Puppet server. All other files will be sourced or named from this file. I refer to this file as the origin of the Puppet policy. ensure => running means that the Puppet agent daemon should be running. This might sound like a catch-22, but it's not really. You can run the Puppet agent manually (we will do this throughout the book.) This service resource ensures that the daemon is running, and starts it if it is not. enable => true ensures that the process is configured to start up at boot time. This means different things on different platforms, but Puppet allows us to not focus on those details. Now go to a client node and run the following command. You will see it apply this policy to the system: $ sudo puppet agent –-test You will get the following response: Info: Retrieving pluginInfo: Caching catalog for myhost.example.netInfo: Applying configuration version '1357518358'Notice: /Stage[main]//Node[default]/Service[puppet]/ensure: ensurechanged 'stopped' to 'running'Notice: Finished catalog run in 0.95 seconds If you want to stop the Puppet daemon, you could easily change the policy to the following code. During the next Puppet run it will disable the service and stop the daemon: service { 'puppet':ensure => stopped,enable => false,} Let's stop for a moment and talk about the catalog, which is mentioned in the second line of preceding output. The catalog is a distilled, compiled version of the Puppet policy which contains only those directives necessary for the client node. Obviously our previously mentioned test policy would apply to every node, so they would receive very similar catalogs. We will show you how to differentiate the policy given to each node in step 3. Step 2 – Managing software and services You can't start services if their packages aren't installed. So why don't we tweak the default node and add a little bit more code? The following segment ensures that the Puppet package is installed, and is the latest version. If the Puppet package is updated, the Puppet service will restart itself to get the new version: package { 'puppet':ensure => latest,notify => Service['puppet'],}service { 'puppet':ensure => running,enable => true,subscribe => Package['puppet'],} Notice how easy it is to set up dependencies between items? notify and subscribe are actually redundant here. You only need one or the other to build the linkage between these two resources. But if you're a belt-and-suspenders kind of person, it never hurts to list the dependency in both the places. We have introduced another important concept here. By default, declarations in the Puppet policy can happen in any order. You use statements like require, before, notify, and subscribe to define dependencies that ensure that resources are applied in the appropriate order. We will cover ordering and dependencies in the next section. Step 3 – Customizing one node Now let's go a little further and customize the policy for one node. In the following section, we are going to ensure that the Puppet server is running the latest version of the Puppet master. Just below the default node block, let's add the following code: node puppet-server-name inherits default {package { 'puppet-server':ensure => latest,notify => Service['puppetmaster'],}service { 'puppetmaster':ensure => running,enable => true,subscribe => Package['puppet-server'],}} The inherits syntax of the node line says "do everything most nodes do, and also include this policy". You could leave off inherits default and the node would only execute the policy specifically within the node block. In this step we have now customized the catalog, which will be given to this one node. The name you put in the node block is not the certname from the previous section, but the hostname of the box where the Puppet server is running. The Puppet server is really just the policy keeper. Policies are applied by the Puppet agent, even on the node which is running the server. Step 4 – Synchronizing files and directories Let's enable file synchronization down to the client node. First, we need to enable the file server. Use your favorite editor to edit /etc/puppet/fileserver.conf: [files]path /etc/puppet/filesallow * Now let's create some test files for this example. We'll make the directory owned by you so that we don't have to sudo every command: $ sudo mkdir /etc/puppet/files$ sudo chown `id –u` /etc/puppet/files$ cp /etc/hosts /etc/puppet/files/$ cp /etc/motd /etc/puppet/files/ Now let's put some file resources here as examples. You can put the following policy text in the default node block (for all hosts), or you can put it inside a node block for a single host: file { '/tmp/hosts':ensure => file,owner => nobody,group => nobody,mode => 0444,force => false,source => 'puppet:///files/hosts',}file { '/tmp/hosts.linked':ensure => link,target => '/tmp/hosts',}file { '/tmp/puppet-files':ensure => directory,owner => root,group => root,mode => 0444,recurse => true,source => 'puppet:///files',} Now let's test out the revised policy on your node: $ sudo puppet agent --test You will get the following response: Info: Retrieving pluginInfo: Caching catalog for myhost.example.comInfo: Applying configuration version '1357520339'Notice: /Stage[main]//Node[myhost]/File[/tmp/hosts]/ensure: definedcontent as '{md5}41e6824ef17c17aa577cd6fd6f794351'Notice: /Stage[main]//Node[myhost]/File[/tmp/hosts.linked]/ensure:createdNotice: /Stage[main]//Node[myhost]/File[/tmp/puppet-files]/ensure:createdNotice: /File[/tmp/puppet-files/hosts]/ensure: defined content as '{md5}41e6824ef17c17aa577cd6fd6f794351'Notice: /File[/tmp/puppet-files/motd]/ensure: defined content as '{md5}d41d8cd98f00b204e9800998ecf8427e'Notice: Finished catalog run in 0.51 seconds With a simple ls –la /tmp you'll be able to see the file, link, and directory that this policy has created. At this point we've created a small but very effective Puppet policy. You have three different ways to copy files down to hosts. Packages are installed, and services are stopped or started based on your policy. And yet, the entire policy as expressed in the site.pp file, still fits on a single page. In this you can start to perceive the power of Puppet. Summary This article showed how to use the core resource types included within Puppet to reduce the amount of manual work and rework you do every day. Resources for Article : Further resources on this subject: Designing and Creating Database Tables in Ruby on Rails [Article] Facebook Application Development with Ruby on Rails [Article] Xen Virtualization: Work with MySQL Server, Ruby on Rails, and Subversion [Article]
Read more
  • 0
  • 0
  • 2123

article-image-quick-start
Packt
22 May 2013
8 min read
Save for later

Quick start

Packt
22 May 2013
8 min read
(For more resources related to this topic, see here.) Common issues in Google Map Maker Before we get started, it's worth taking into consideration some of the known issues with Google Map Maker: Map Maker interface does not usually come fully translated into all languages at the same time. UI translations are usually rolled out gradually and are a part of another community-driven effort. This project is accessible at http://www.google.com/ transconsole/giyl/chooseProject. Note that some of the languages—for example, Urdu despite being translated completely—still are not available in Map Maker UI. Map Maker has not been verified for compatibility with Internet Explorer 7 and earlier versions of IE. Google Map Maker is accessed by firing the URL http://www.google.com/mapmaker. To access and get started with Map Maker, you must have a Google Account in order to start making and submitting edits. A Google Account is a unified sign-in system that provides access to a variety of free Google consumer products such as Gmail, Google Groups, Google Maps, Google Wallet, AdWords, AdSense, and so on. Think of a Google Account as a single Google sign-in, made up of an e-mail address (any e-mail address, does not have to be a Gmail) and a password of your choice, that gives you access to all the Google products under your own profile. Create your Google Account by visiting https://accounts.google.com/SignUp if you would like to use another e-mail address. If you already have a Gmail account, please sign in from the left pane when you visit http://www.google.com/mapmaker, as shown here: The Map Maker interface during the first visit The Map Maker interface The Google Map Maker interface is simple, intuitive, and easy to use. It has standard graphical icons that help you navigate around the tools and functionalities. Let us take a closer look at it: A first-time login to Map Maker starts by displaying a tutorial to quickly take you through the key features of Google Map Maker. You can navigate your way through the quick tutorial by going back and forth using the respective forward and back arrows. You can close the quick tutorial and get started with making edits right away by clicking on the X icon on top. Don't worry, you can always access the tutorial later, as will be explained later in this book. The Map Maker UI Let us take a detailed look at the Map Maker interface, I have tried to subdivide it based on the main functionalities and purposes of the tools. Key tools/sections that you need to know are highlighted and clearly labeled as well. I have named them based strictly on the functionality and this is by no means the conventional way of doing so. Let us take a quick deep dive into the tools and see what each section serves: Search The search area allows you to search and fly to places you want to in Map Maker in an instant. It works just like Google Search, only that it returns a map zoomed to the area/business you queried. Try it. Type the name of your city and hit Enter. This comes in handy when, on visiting Google Map Maker, the default load is not defaulting to your current location much as it should or just when you want to make edits and/or reviews in some other area you are familiar with or just to view and visit places. Take a look at the following search query: Review area This is the area that displays your own recent edits as well as displaying edits happening within your neighborhood that you created or are based on your location. You can switch between the tabs based on the functionality that you want; the different tabs are explained as follows: Everything: This tab is like a channel stream or timeline. Shows the recent activities in terms of new edits, reviews, or comments by you and other mappers within the neighborhood view of the map, that is, the current location of the map that is in view. See the following example: An Everything view To Review: This area only highlights the edits whose reviews are pending. Recently Published: Streams all those recent edits, which have been approved and published. You can, however, still contest these edits or correct them if they are incorrect. Filter by Category: Just next to the Recently Published tab, you will find a three-dot tab that allows you to expand this section. This section is the filter section and gives you the power to filter by categories the actions, places, and edits you would like to perform. For instance, you may just be interested in (re)viewing road and line features or the chronological order of the edits being made in the locale. Filter by Category Map view area This is the area where the Google Maps loads in order to allow you to perform the operations and edits that you want. The map view usually defaults to your current location when you visit http://www.google.com/mapmaker. Map controls These tools allow you to control the view of the map. They allow you to pan, zoom, and view Street View for supported cities. Let's take a look at what and how each of the tools comes in handy: Map controls Edit control This is the area that allows you to make new edits to Map Maker and correct existing ones as well. You can create new point, line, and polygon features by exploring the Add New tab. Note that the tools will change according to the main tool selected. You can also edit existing point, line, polygon, and direction features by exploring the Edit tab. We will take a deep dive into this section a little later in this book. Personal/User area I call this the personal area, because it allows you to personalize your Map Maker through custom settings and adding labs (experimental features that are still under testing and development). Labs allow you to extend the normal functionality of Map maker. This section also allows you to share your edits, directions, and maps with your friends by generating a unique URL for it. Create and make changes to your Map Maker profile, access Help and discussion forums, report a bug, and as well as submit feedback to the Google Maker team by using these tools. Personal user area View The View section allows you to switch between the different layers of Google Map Maker—Satellite and Map. In a Map view, you only get to view the map details created by users, whereas in Satellite view, you can see the map elements overlaying the satellite imagery provided to Google by various satellite imagery providers and partners. This is the best layer to use when making edits as it allows you to draw/trace over the edits from the satellite imagery to creating the features in a process called digitization in Cartography terms. It is actually the backbone of this community-driven project. Users have to align everything from satellite imagery to points feature, line features, and polygon features for better accuracy; otherwise their edits may be denied or delayed in the reviewing process. You can add more layers such as photos, which will display edits /features alongside the photos uploaded among other features. To switch between and add layers, simply click on it and the Map view will be populated with the layer(s) of your selection. Different views in Map Maker Contributors The Contributors' segment displays all the contributors who have made a substantial number of edits on the area of the Map view. It displays the contributors' preferred nicknames (set during the signing-up stage). If you click on any nickname, it takes you to their respective Map Maker profiles showing their edits and badges earned. Scale This section will show us the display scale of the map as we zoom in and out. Summary This article explained in detail how we can use the different features of Map Maker to our benefit. It also explained the different interfaces used in Google Map Maker. Resources for Article : Further resources on this subject: Moodle 2.0 Multimedia: Working with 2D and 3D Maps [Article] Google Earth, Google Maps and Your Photos: a Tutorial [Article] Google Earth, Google Maps and Your Photos: a Tutorial Part II [Article]
Read more
  • 0
  • 0
  • 1580

article-image-getting-started-zombiejs
Packt
22 May 2013
9 min read
Save for later

Getting Started with Zombie.js

Packt
22 May 2013
9 min read
(For more resources related to this topic, see here.) A brief history of software and user interface testing Software testing is a necessary activity for gathering information about the quality of a certain product or a service. In the traditional software development cycle, this activity had been delegated to a team whose sole job was to find problems in the software. This type of testing would be required if a generic product was being sold to a domestic end user or if a company was buying a licensed operating system. In most custom-built pieces of software, the testing team has the responsibility of manually testing the software, but often the client has to do the acceptance testing in which he or she has to make sure that the software behaves as expected. Every time someone in these teams finds a new problem in the software, the development team has to fix the software and put it back in the testing loop one more time. This implies that the cost and time required to deliver a final version of the software increases every time a bug is found. Furthermore, the later in the development process the problem is found, the more it will impact the final cost of the product. Also, the way software is delivered has changed in the last few years; the Web has enabled us to make the delivery of software and its upgrade easy, shortening the time between when new functionality is developed and when it is put in use. But once you have delivered the first version of a product and have a few customers using it, you can face a dilemma; fewer updates can mean the product quickly becomes obsolete. On the other hand, introducing many changes in the software increases the chance of something going wrong and your software becoming faulty, which may drive customers away. There are many versions and iterations over how a development process can mitigate the risk of shipping a faulty product and increase the chances of new functionalities to be delivered on time, and for the overall product to meet a certain quality standard, but all people involved in building software must agree that the sooner you catch a bug, the better. This means that you should catch the problems early on, preferably in the development cycle. Unfortunately, completely testing the software by hand every time the software changes, would be costly. The solution here is to automate the tests in order to maximize the test coverage (the percentage of the application code that is tested and the possible input variations) and minimize the time it takes to run each test. If your tests take just a few seconds to run, you can afford to run them every time you make a single change in the code base. Enter the automation era Test automation has been around for some years, even before the Web was around. As soon as graphical user interfaces (GUIs) started to become mainstream, the tools that allowed you to record, build, and run automated tests against a GUI started appearing. Since there were many languages and GUI libraries for building applications, many tools that covered some of these started showing up. Generally they allowed you to record a testing session that you could later recreate automatically. In this session, you could automate the pointer to click on things (buttons, checkboxes, places on a window, and so on), select values (from a select box, for instance), and input keyboard actions and test the results. All of these tools were fairly complex to operate and, worst of all, most of them were technology-specific. But, if you're building a web-based application that uses HTML and JavaScript, you have better alternatives. The most well known of these is likely to be Selenium, which allows you to record, change, and run testing scripts against all the major browsers. You can run tests using Selenium, but you need at least one browser for Selenium to attach itself to, in order to load and run the tests. If you run the tests with as many browsers as you possibly can, you will be able to guarantee that your application behaves correctly across all of them. But since Selenium plugs into a browser and commands it, running all the tests for a considerably complex application in as many browsers as possible can take some time, and the last thing you want is to not run the tests as often as possible. Unit tests versus integration tests Generally you can divide automated tests into two categories, namely unit tests and integration tests. Unit tests: These tests are where you select a small subset of your application—such as a class or a specific object—and test the interface the class or object provides to the rest of the application. In this way, you can isolate a specific component and make sure it behaves as expected so that other components in the application can use it safely. Integration tests: These tests are where individual components are combined together and tested as a working group. During these tests, you interact and manipulate the user interface that in turn interacts with the underlying blocks of your application. The kind of testing you do with Zombie.js falls in this category. What Zombie.js is Zombie.js allows you to run these tests without a real web browser. Instead, it uses a simulated browser where it stores the HTML code and runs the JavaScript you may have in your HTML page. This means that an HTML page doesn't need to be displayed, saving precious time that would otherwise be occupied rendering it. You can then use Zombie.js to conduct this simulated browser into loading pages and, once a page is loaded, doing certain actions and observing the results. And you can do all this using JavaScript, never having to switch languages between your client code and your test scripts. Understanding the server-side DOM Zombie.js runs on top of Node.js (http://nodejs.org), a platform where you can easily build networking servers using JavaScript. It runs on top of Google's fast V8 JavaScript engine that also powers their Chrome browsers. At the time of writing, V8 implements the JavaScript ECMA 3 standard and part of the ECMA 5 standard. Not all browsers implement all the features of all the versions of the JavaScript standards equally. This means that even if your tests pass in Zombie.js, it doesn't mean they will pass for all the target browsers. On top of Node.js, there is a third-party module named JSDOM (https://npmjs.org/package/jsdom) that allows you to parse an HTML document and use an API on top of a representation of that document; this allows you to query and manipulate it. The API provided is the standard Document Object Model (DOM). All browsers implement a subset of the DOM standard, which has been dictated as a set of recommendations by a working group inside the World Wide Web Consortium (W3C). They have three levels of recommendations. JSDOM implements all three. Web applications, directly or indirectly (by using tools such as jQuery), use this browser-provided DOM API to query and manipulate the document, enabling you to create browser applications that have complex behavior. This means that by using JSDOM you automatically support any JavaScript libraries that most modern browsers support. Zombie.js is your headless browser On top of Node.js and JSDOM lies Zombie.js. Zombie.js provides browser-like functionality and an API you can use for testing. For instance, a typical use of Zombie.js would be to open a browser, ask for a certain URL to be loaded, fill some values on a form, and submit it, and then query the resulting document to see if a success message is present. To make it more concrete, here is a simple example of what the code for a simple Zombie.js test may look like: browser.visit('http://localhost:8080/form', function() {browser.fill('Name', 'Pedro Teixeira').select('Born', '1975').check('Agree with terms and conditions').pressButton('Submit', function() {assert.equal(browser.location.pathname, '/success');assert.equal(browser.text('#message'),'Thank you for submitting this form!');});}); Here you are making typical use of Zombie.js: to load an HTML page containing a form; filling that form and submitting it; and then verifying that the result is successful. Zombie.js may not only be used for testing your web app but also by applications that need to behave like browsers, such as HTML scrapers, crawlers, and all sorts of HTML bots. If you are going to use Zombie.js to do any of these activities, please be a good Web citizen and use it ethically. Summary Creating automated tests is a vital part of the development process of any software application. When creating web applications using HTML, JavaScript, and CSS, you can use Zombie.js to create a set of tests; these tests load, query, manipulate, and provide inputs to any given web page. Given that Zombie.js simulates a browser and does not depend on the actual rendering of the HTML page, the tests run much faster than they would if you instrumented a real browser. Thus it is possible for you to run these tests whenever you make any small changes to your application. Zombie.js runs on top of Node.js, uses JSDOM to provide a DOM API on top of any HTML document, and simulates browser-like functionalities with a simple API that you can use to create your tests using JavaScript Resources for Article : Further resources on this subject: Understanding and Developing Node Modules [Article] An Overview of the Node Package Manager [Article] Build iPhone, Android and iPad Applications using jQTouch [Article]
Read more
  • 0
  • 0
  • 21941
article-image-animating-capabilities-cinema-4d
Packt
22 May 2013
6 min read
Save for later

Animating capabilities of Cinema 4D

Packt
22 May 2013
6 min read
(For more resources related to this topic, see here.) Now it's finally time to start modeling. Ordinarily, we would create an Extrude generator, place it in the hierarchy, and parent the spline to it. Here, we'll use a special trick to extrude each spline in half the time it would normally take. With a path selected, hold the Alt/Option key when you create the Extrude object. This works whether you create the Extrude generator through the menu or through the top Command palette. You'll notice that the path is automatically parented to the Extrude generator, and that the Extrude generator's pivot is set up properly. For your logo, set up all of the extrusions that you'll need. In our case, we set up one extrude for the PACKT text, one for the PUBLISHING text, and one for the box brackets. Edit the properties of the different extrusions until you are happy with them. To add bevels to your extrusions, navigate to the Caps tab in the Attribute Editor and change the Start and End properties to Fillet Cap. You can then edit additional properties to get the type of bevels that you'd like. There is one very important thing to note about bevels. By default, bevels grow outward from your original path. In many cases this can have an undesired effect since the overall thickness of your logo will increase and it will look different from the original vector art. To fix this, turn on the Constrain option in the Caps section of the extrude generator's attributes. We now have our shapes the way we like them. The logo is extruded and our bevels are set up nicely. Also, most of the extrusion slides into a compound shape that fills our background. Now let's create and assign materials to different parts of the logo. Create a material in the Material Editor window, either by double-clicking on the empty space or through the Material Editor window's menu (Create | New Material). Assign the material to an object by dragging the material from the Material Editor onto the Extrude generator. Notice that the Extrude generator now has a Texture tag assigned to it. Edit the material as you want. You can select the material in the Material Editor, or double-click the Texture tag in the Object Manager palette. In the Basic tab of the material, you can turn different surface properties on or off, such as Specular, Reflection, and so on. Once a surface property is enabled, a tab appears for that property for further editing. Step 3 – shatter the logo Now it's time to shatter the logo using Nitro4Ds Thrausi plugin. Follow these steps to shatter the logo: Select the object you wish to shatter. Launch the Thrausi interface, through the main menu (Plugins | Thrausi 1.22 R12 | Thrausi). If you have the NitroBlast plugin, you can use that plugin instead. Set the value in the Pieces field to the number of actual pieces you'd like to generate. Select the type of shatter you'd like to perform. Here, we chose Voronoi. Click the Break Now button at the bottom of the Thrausi interface. It may take a few minutes to calculate the shatter. For the sake of this tutorial, delete the Rigid Body simulation tags on the resulting Fracture groups. Each letter has been shattered and put into a MoGraph Fracture group. This is a special group that will allow us to assign MoGraph effectors to the shards. If you'd like to regroup the shards into different Fracture objects to better organize your scene, it's perfectly safe to do so. Since we're not using dynamics for this tutorial, we deleted the Rigid Body tags from the Fracture groups. If you wanted to use dynamics to animate the shards, you could leave these tags for a start. One thing you may notice is that the bevels of the logo no longer have sharp edges. That's because the phong shading angle is too high. If the phong angle is 80 degrees, then any polygonal edge with 80 degrees or less between adjacent face normal will appear smoothed. These properties are controlled by the Phong tag. Now let's edit the phong tags on the shards: Select all of the Phong tags of the shards. You can do so by dragging a selection marquee in the Object Manager palette. You can also select the Phong tag of the first object in the list, then press the Shift key as you select the Phong tag of the last object. All of the Phong tags will be selected. Set the value of the Phong Angle field to something less than 45 degrees, such as 30. For the purposes of this tutorial, we'll be using MoGraph effectors to move the shards instead of dynamics. Now we'll create a Plain effector to spread out the shards. Just follow the subsequent steps to create a Plain effector: Select all of the MoGraph Fracture groups. Create a Plain effector through the main menu (MoGraph | Effectors | Plain). Since the Fracture groups are selected, the Plain effector is automatically assigned to them. In the Parameter tab of the Plain effector attributes, set the P.X, P.Y, and P.Z attributes to 0, 0, and -500 respectively. Also in the Parameter tab, set the Weight Transform attribute to 100%. This adds an invisible weight value per shard that can be inherited by other effectors later on. In the Falloff tab, set the Falloff property to Linear. Note that the falloff property's orientation is set to Z, and that falloff controls are now visible in the 3D view. Set the Falloff attribute to 100%. Move the Plain effector on the z axis, and adjust the falloff's Size Z until the Plain effector's falloff barely encompasses the logo. Turn on the Fracture groups. You can click on the little red cross next to the Fracture groups in the Object Manager palette, or turn on the Enabled checkbox in the Basic tab of the Fracture group's attributes. If everything is done correctly, you should see all your pieces floating forward. The Plain effector's linear falloff ensures that pieces closer to the front of the logo come out further as shown in the following screenshot: Summary We came across a few techniques in this article with which you can create brilliant animations out of simple images, there is a whole new world of features provided within Cinema 4D which have been described in the book. So buckle up and spread your wings of creativity. Resources for Article : Further resources on this subject: Creating and Warping 3D Text with Away3D 3.6 [Article] 3D Vector Drawing and Text with Papervision3D: Part 2 [Article] Tips and Tricks on Away3D 3.6 [Article]
Read more
  • 0
  • 0
  • 2305

article-image-preparing-your-website-use-gridster
Packt
22 May 2013
4 min read
Save for later

Preparing your website to use Gridster

Packt
22 May 2013
4 min read
(For more resources related to this topic, see here.) Getting ready There are only two things needed to get Gridster installed on your source code. You first need to download jQuery if you don't already have it, and then download the latest version of Gridster. After that, you will use plain HTML code to include both libraries in your webpage. For most casual users, adding the latest version of jQuery will suffice. There are also nightly builds available, but these won't be discussed here as they are not necessary, and the latest version should be able to do everything we need. How to do it... Start by visiting jQuery's website, http://jquery.com/download/, and download the library to a location you will remember. We won't be debugging our jQuery code in the examples given in this book, so downloading the production version will be fine. We should now head over to Gridster's website, http://gridster.net/#download/, and download the minified versions of both the gridster.js and gridster.css files. These are the files we will use throughout this entire book, so make sure they are kept safe and accessible. A suggestion would be to create a directory structure to make it easier to refer to the files. I will be using the following structure for the examples given here: Under the directory recipe1, create a new text file called index.html. This file should initially contain the following code: <!DOCTYPE html><html><head><script src = "../scripts/jquery-1.8.3.min.js"></script><script src = "../scripts/jquery.gridster.min.js"></script><link href = "../styles/jquery.gridster.min.css" rel="stylesheet" /><title>Recipe 1</title></head><body>Hello Gridster!</body></html> You can download the example code files for all Packt books that you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub. com/support and register to have the files e-mailed directly to you. By double-clicking on this file, you should be presented with a screen that looks like the following screenshot: You can check that everything has loaded up correctly by pressing the F12 key on your browser (Chrome or Firefox), and checking that all files have been correctly loaded without errors, as shown in the following screenshot: There's more... Instead of downloading the files into your project, you can simply load them up via CDN-hosted copies of the files, as follows: <script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> In that case, the files wouldn't be coming from your website, but from jQuery's website itself. This is a good practice when trying to improve performance, as big web servers tend to host files on multiple locations and use very aggressive caching techniques to make sure the files are served quickly. Gridster also offers files in the same way from their website as you will find in their download section. So, for example, you could link directly to their minified file as follows: <scriptsrc ="https://raw.github.com/ducksboard/gridster.js/master/dist/jquery.gridster.min.js"></script> Summary In this recipe we described all the necessary steps to get Gridster up and running on your website, and also demonstrated how to include any of the dependencies needed by the library. Resources for Article : Further resources on this subject: Getting Started with jQuery [Article] jQuery Animation: Tips and Tricks [Article] Tips and Tricks for Working with jQuery and WordPress [Article]
Read more
  • 0
  • 0
  • 2067
Modal Close icon
Modal Close icon