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-setting-biztalk-server-environment
Packt
09 Apr 2012
18 min read
Save for later

Setting up a BizTalk Server Environment

Packt
09 Apr 2012
18 min read
Gathering requirements by asking the right questions Although, this is not an exact recipe, asking questions to obtain requirements for your BizTalk environment is important. Having a clear view and understanding of the requirements enables you to deploy the desired BizTalk environment that meets expectations of the customer. What are the right questions you may ask yourself? Well, there is quite a large area in general you basically need to cover with questions. These questions will be around the following topics: A BizTalk work load(s) that is functional Non-functional (high availability, scalability, and so on) Licensing (software) Hardware Virtualization Development, Test, Acceptance, and Production (DTAP) environment Tracking/Tracing Hosting Security Getting ready Organize the sessions, and/or the workshop(s) to discuss the BizTalk architecture (environment), functionality, and non-functional requirements, where you do a series of interviews with appropriate stakeholders. This way you will be able to retrieve the necessary requirements and information for a BizTalk environment. You will need to focus on business first and IT later. You will notice that each business will have a different set of requirements on integration of data and processes. Some of these are listed as follows: Business is able to have the access of information from anywhere any time Have the proper information to present to the proper people Have the necessary information available when needed Manage knowledge efficiently and be able to share it with the business Change the information when needed Automate the business process that is error-prone Automate the business process to reduce the processing time of orders, invoices, and so on Regarding the business requirements, BizTalk will have certain workloads, and with the business you determine if you want BizTalk to aid in automating processes, exchange of information with partners, maintaining business rules, visibility of psychical events, and/or integration with different systems. One important factor to reckon with bringing BizTalk into an organization is risk-associated with transitioning to its platform. This risk can be of a technical, operational, political, and financial nature. BizTalk solutions have to operate correctly, meet the business requirements, and be accepted by stakeholders within the organization and should not be too expensive. With IT, you focus more on the technical side of the BizTalk Environment such as, "What messages in size, format, and encoding are sent to the BizTalk system or what does it need to output?" You should consider security around it, when information going to or coming from trading partners is confidential. Encryption and decryption of data such as, "What processes that are automated need to interact with internal and external systems?" or "How are you going to monitor messages that are going in and out?" can come into play. Support needs to be set up properly to keep BizTalk and its solutions healthy. Solutions need to be developed and tested, preferably using different environments such as test and acceptance. For that, you will need an agreed deployment process with IT. These are factors to reckon with and need to be addressed when interviewing or talking to IT stakeholders within the organization. How to do it… Categorize your stakeholders into two categories—business and IT. Create a communication plan and list of questions related to areas mentioned earlier. With the list of questions you can assign each question to a person you think can answer it. This way you ask the right questions to the right people. The following table shows a sample of roles belonging to business and/or IT. It could be that you identify more roles depending on your situation: Category Role Business CEO, CIO, Security Officer, Business Analyst, Enterprise Architect, and Solution Architect. IT IT Manager, Enterprise Architect, Solution Architect, System/Application Architect, System Analyst, Developer, System Engineer, and DBA. Having the roles clear belonging to either business, IT, or both, you will then need to have a list of questions and assign these to the appropriate role. You can find an example list of questions associated to a particular role in the following table: Question Role Will BizTalk integrate with systems in the enterprise? Which consumers and host systems will it integrate with? Enterprise Architect, Solution Architect What are the applicable workloads? Enterprise Architect Is BizTalk going to be strategic for integration with internal/external systems? CEO, CIO, Enterprise Architect, and Business Analyst Number of messages a day/hour Enterprise Architect What are the candidate processes to automate with BizTalk? Business Analyst, Solution Architect What communication protocols are required? Enterprise Architect, Solution Architect Choice of Microsoft platform-Operating System, SQL Server Database Enterprise Architect, Security Officer, Solution Architect, System Engineer, and DBA Encryption algorithm for data Enterprise Architect, Security Officer, Solution Architect, and System Engineer Is Secure Socket Layer required for communication? Enterprise Architect, Security Oficer, Solution Architect, and System Engineer What kind of certificate store is there? Enterprise Architect, Security Officer, Solution Architect, and System Engineer Is the Support for BizTalk going to be outsourced CEO, IT Manager There's more… The best approach to gather the requirements is to view it as a project or a part of the project. You can use a methodology such as PRINCE2. PRINCE2 Projects in Controlled Environments (PRINCE) is a project management method. It covers the management, control, and organization of a project. PRINCE2 is the second major release of it. More information is available at http://www.prince2.com/. Microsoft BizTalk Server website The Microsoft BizTalk Server website provides a lot of information. Especially, the Production Information section provides detailed information on system requirements, roadmap, and the FAQs. The latter sections provide details on pricing, licensing, and so on. Go to http://www.microsoft.com/biztalk/en/us/default.aspx. Analyzing requirements and creating a design Analyzing requirements and creating a design for the BizTalk landscape is the next step forward before planning and installing. With the gathered requirements, you can make decisions on how to design a BizTalk environment(s). If BizTalk is used for the first time in an enterprise environment capacity, planning and server allocation is something to focus on. Once you gather requirements and ask questions, you will have a clear picture of where the platform will be hosted and whether it needs to be scaled up or out. If everything gets placed on one big server, it will introduce a serious single point of failure. You should try to avoid this scenario. Therefore, separating BizTalk from the SQL Server is the first thing you will do in your design, each on a separate hardware preferably. Depending on availability requirements, you will probably cluster the SQL Server. Besides that, you can choose to scale out BizTalk into a multiserver group, because of availability requirements and if the expected load cannot be handled by one BizTalk instance. You can opt for installing BizTalk and SQL separately first and then scale-out after performing benchmark tests. You can scale vertically (scaleup) by increasing the number of processors and the amount of memory each server uses, or you can scale horizontally (scaleout) by adding more servers to your BizTalk Server configuration. Other options you can consider during your design are as follows: Having multiple MessageBox databases Separate BizTalk databases These options are best visualized by the scale-out poster from Microsoft (http://www.microsoft.com/download/en/details.aspx?id=13103). Based on the requirements, you can consider isolating the BizTalk hosts to be able to manage BizTalk applications better and divide the load. By separating send, receive, and processing functionality in different hosts, you will benefit from better memory and thread management. If you expect a high load of large messages or orchestrations that would consume large amounts of resources, you should isolate send and/or receive adapters. Another consideration is to separate a host to handle tracking and relieve processing hosts from it. So far we have discussed scalability and design decisions you could consider. There are some other design considerations for a BizTalk environment such as security, tracking, fault tolerance, load balancing, choice of license, and support for virtualization (http:// support.microsoft.com/kb/842301). BizTalk security can be enhanced by deploying Secure Socket Layer (SSL), IPSec Tunneling, the Inter Security and Acceleration (ISA) server, and certificate services included with the Windows Server 2008. With the BizTalk Server, you can apply access control, implement least rights to limit access, and provide integrated security through Enterprise Single Sign-On (http://msdn.microsoft.com/en-us/library/aa577802%28v=bts.70%29.aspx). Furthermore, you can protect and secure applications and data by authenticating the sender of a message and authorizing the receiver of a message. Tracking messages in BizTalk messages can be useful to see what messages come in and out of the system, or for auditing, troubleshooting, or archiving purposes. Tracking of messages within BizTalk is a process by which parts of a message such as the body, properties, and metadata are stored in a database. These parts can be viewed by running queries from the Group Hub page in the BizTalk Server Administration console. It is important that you decide, or take up into the design, what needs to be tracked based on the requirements. There are some considerations to make regarding tracking. Tracking everything is not the smart thing to do, as each time a message is touched in BizTalk; a copy is made and stored. Focus on scope by tracking only on a specific port, which is better for performance and keeps the database uncluttered. For the latter, it is important that the data purge and archive job is configured properly. As mentioned earlier, it is worth considering a dedicated host for tracking. Fault tolerance and load balancing for BizTalk can be achieved through clustering, separating hosts as described earlier, implement a Storage Area Network (SAN) to house the BizTalk Server databases, cluster Enterprise Single Sign-On (SSO) Master Secret Server, and configuring the Internet Information Services (IIS) web server for isolated host instances and the BAM Portal web page to be highly available using Network Load Balancing (NLB) or other load balancing devices. The best way to implement this is to follow the steps in the Checklist: Providing High Availability with Fault Tolerance or Load Balancing document found on MSDN (http://msdn.microsoft.com/en-us/library/gg634479%28v=bts.70%29.aspx). Another important topic regarding your BizTalk environment is costs and based on requirements you will choose the Branch, Standard, or Enterprise Edition. The editions differ not only in price, but also in functionality. As with the Standard Edition, it is not possible to support scenarios for high availability, fault tolerance, and is limited on CPU and applications. The Branch Edition is even more limited and is designed for hub and spoke deployment scenarios including Radio Frequency Identification (RFID). With any version, you probably want to consider whether or not to virtualize. With virtualization in mind, licensing can be difficult. With the Standard Edition, you need a license for each virtual processor used by the virtual OS environment, regardless of whether the number of virtual processors is less than, or greater than, the number of physical processors on the server. With the Enterprise Edition, if you license all physical CPUs on the server you can run any number of instances in the physical or virtual OS environment. With both of these, a virtual processor is assumed to have the same number of cores as the physical processor. Using less than the number of cores available in the physical processor still counts as a full virtual processor (http://www.microsoft. com/biztalk/en/us/editions.aspx). Last, but not least, you need to consider how to support your BizTalk environment. It is worth considering the System Center Operation Manager to monitor your BizTalk environment using management packs for the SQL Server, Windows Server, and BizTalk Server 2010. The management pack for the BizTalk Server 2010 provides two views, one for the enterprise IT administrator and one for the BizTalk Server administrator. The first will be monitoring the state and health of the various enterprise deployments, the machines hosting the SQL Server databases, machines hosting the Enterprise SSO service, host instance machines, IIS, network services, and is interested in the overall health of the "physical deployment" of a BizTalk Server setup. The BizTalk Server Administrator will be monitoring the state and health of various BizTalk Server application artifacts, such as orchestrations, send ports, receive locations, and is interested in monitoring and tracking the BizTalk Server's health. If necessary, he/she can carry out corrective measures to keep applications running as expected. What you have read so far are considerations, which are useful while analyzing requirements and preparing your design. You need to take a considerable amount of time for analyzing requirements to be able to create a solid design for your BizTalk environment. There is a wealth of information provided by Microsoft in this book. It will be worth investing time now as you will lose a lot time and money if your applications do not perform or the system cripples under load while receiving the process. How to do it... To analyze the requirements, you will need to categorize them to certain topics mentioned in the Gathering requirements by asking the right questions recipe. You will then go over each requirement and decide how it can be met best. For each requirement, you will consider what the best option is and capture that in your design for the BizTalk setup. The BizTalk design will be a Word document, where you capture your design, considerations, and decisions. How it works... During analysis of each requirement, you will capture your considerations and decisions in a word document. Besides that, you will also describe the situation at the enterprise where the BizTalk environment will be deployed. You will find an example structure of a design document for a Development, Test, Acceptance, and Production (DTAP) environment, as follows, where you can place all the information: Introduction Purpose Current situation IT landscape Design Decisions Considerations/Issues Overview DTAP landscape Scope MS BizTalk and SQL Server editions SQL Database Server ICT Policy Operating systems Windows Server Backup Antivirus Windows update Security Settings Backup and Restore Backup procedure Restore procedure Development Development environment Development server Developer machine Test Test server Acceptance SQL Server clustering BizTalk group Acceptance server Production SQL Server clustering BizTalk group (load balancing) Production server Management and security Groups and accounts SCOM Single Sign-On Hosts In process hosts Isolated hosts Trusted and untrusted hosts Hosts configuration DTAP Resources Appendix A Redistributable CAB Files Design decisions are the important parts of your document. Here, you summarize all your design decisions and reference them to each corresponding chapter/section in the document, where a decision is described; you also note issues around your design. There's more... Analyzing requirements is an important task, which should not be taken lightly. Knowing architectural patterns, for instance, can help you choose the right technology and create the appropriate design. It can be that the BizTalk Server is not the right fit for the purpose. The following resources can aid you in analyzing the requirements: Architectural Patterns: Packt has published a book called Applied Architecture Patterns on Microsoft Platform that can aid you in analyzing the requirements by selecting the right technology. Wiki TechNet article: Refer to the Recommendations for Installing, Sizing, Deploying, and Maintaining a BizTalk Server Solution article at http://social.technet. microsoft.com/wiki/contents/articles/666.aspx. Microsoft BizTalk Server 2010 Operations Guide: Microsoft has created a BizTalk Server 2010 Operations Guide for anyone involved in the implementation and administration of a BizTalk solution, particularly IT professionals. You can find it online (http://msdn.microsoft.com/en-us/library/ gg634499%28v=bts.70%29.aspx) or you can download it from http://www. microsoft.com/downloads/en/details.aspx?FamilyID=4ef9eebb-b3f4-4534-b733-3eb2cb83d867&displaylang=en. Microsoft volume licensing brief: Licensing Microsoft Server Products in Virtual Environments is an interesting white paper from Microsoft. It describes licensing models under virtual environments for the server operating systems and server applications. It can help you understand how to use Microsoft server products with virtualization technologies, such as Microsoft Hyper-V technology, Microsoft Virtual Server 2005 R2, or third-party virtualization solutions that are provided by VMWare and Parallels. You can download from the URL: http://www.microsoft.com/ downloads/en/details.aspx?FamilyID=9ef7fc47-c531-40f1-a4e9-9859e593a1f1&displaylang=en. Microsoft poster scale-out configurations: Microsoft has published a poster (normal or interactive) that can be downloaded describing typical scenarios and commonly used options for scaling out the BizTalk Server 2010's physical configurations. This post clearly illustrates how to scale for achieving high availability through load balancing and fault tolerance. It also shows how to configure for high-throughput scenarios. A normal poster can be obtained from the URL: http://www.microsoft.com/ downloads/en/details.aspx?FamilyID=2b70cbfc-d158-45a6-8bbd-99782d6747dc. An interactive poster created in Silverlight can be obtained from the URL:http:// www.microsoft.com/downloads/en/details.aspx?FamilyID=7ef9ae69-9cc8-442a-8193-831a414dfc30. Installing and using the BizTalk Best Practices Analyzer The Best Practices Analyzer (BPA) examines a BizTalk Server 2010 deployment and generates a list of issues pertaining to best practice standards for BizTalk Server deployments. This tool is designed to assess the configuration of a BizTalk installation. The BPA performs configuration-level verification by gathering data from different information sources, such as Windows Management Instrumentation (WMI) classes, SQL Server databases, and registry entries and presents a report to the user. Under the hood, it uses the data to evaluate the deployment configuration. It does not modify any system settings and is not a self-tuning tool. The tool is there to deliver support in achieving the best suitable configuration and report issues or possible issues, that could potentially harm the BizTalk environment. Getting ready The latest version of the BPA tool (V1.2) can be obtained from the Microsoft download center (http://www.microsoft.com/downloads/en/details.aspx?FamilyID=93d432fe-1370-4b6d-aaa8-a0c43c30f5ab&displaylang=en) and must be installed on the BizTalk machine. As a user, you need an account that has local administrative rights, that is a member of the BizTalk Server Administrators group, and a member of the SSO Administrators group to be able to run the BPA. You may need to explicitly set some WMI permissions before you can use the BPA in a distributed environment, where the SQL Server is not installed on the same computer as the BizTalk Server. This is because when the BPA tries to connect to a remote computer running the SQL Server, WMI may not have sufficient access to determine whether the SQL Server Agent is running. This may result in incorrect BPA evaluations. How to do it... To run the Best Practices Analyzer, perform one of the following: Start the BizTalk Server Best Practices Analyzer from the Start menu. Go to Start | Programs | Microsoft BizTalk Server Best Practices Analyzer. Open Windows Explorer and navigate to the Best Practices Analyzer installation directory (by default, c:Program FilesBizTalkBPA) and double-click on BizTalkBPA.exe. Open a command prompt, change to the installation directory, and then enter BizTalkBPACmd.exe. The following steps need to be performed to do the analysis: As soon as you start the BPA, it will check for updates. The user can decide whether or not to check for updates for newer versions of the configuration: (Move the mouse over the image to enlarge.) If a newer version is found, you are able to download the latest updates. The next step is to perform a scan by clicking on Start a scan: After starting the scan, starts data will be gathered from different information sources as described earlier. After the scan has been completed, the user can decide to view the report of the performed scan: You can click View a report of this Best Practices scan and the report will be generated. After generation of the report, several tabs will appear: Critical Issues All Issues Non-Default Settings Recent Changes Baseline Informational Items How it works... When the BPA is running, it gathers information and evaluates them to best practice rules from the Microsoft product group and support. A report is presented to the user providing information on issues, non-default settings, changes, and so on. The report enables you to take action and apply the necessary changes to resolve identified issues. The BPA can be run again to verify that it adheres to all the necessary best practices. This shows the value of the tool when assessing the deployed BizTalk environment before it is operational. When BizTalk becomes operational, the MessageBox Viewer (MBV) has more value. There's more... The BPA is very useful and gives you information that helps you to tune BizTalk and to keep it healthy. There are more tools that can help in sustaining a healthy environment overall. The Microsoft SQL Server 2008 R2 BPA is a diagnostic tool that provides information about a server and a Microsoft SQL Server 2008 or Microsoft SQL Server 2008 R2 instance installed on that server. The Microsoft SQL Server 2008 R2 Best Practices Analyzer can be downloaded from http://www.microsoft.com/download/en/details.aspx?id=15289. There are a couple of analyzers provided by Microsoft that do a good job helping you and the system engineer to put out a healthy, robust, and stable environment: Best Practices Analyzer: http://technet.microsoft.com/en-us/library/dd759260.aspx Microsoft Baseline Configuration Analyzer 2.0: http://www.microsoft.com/download/en/details.aspx?id=16475 Microsoft Baseline Security Analyzer 2.1.1: http://www.microsoft.com/download/en/details.aspx?id=19892
Read more
  • 0
  • 0
  • 5680

article-image-hours-1-12-your-quest-begins
Packt
03 Apr 2012
4 min read
Save for later

Hours 1-12: Your Quest Begins!

Packt
03 Apr 2012
4 min read
Dealing with the Game Jam "theme" Virtually every Jam requires that you try to make a game that fits a theme. This is either a surprise word that the moderators came up with or one that has been voted upon earlier. The theme for a Jam is typically announced immediately before it begins. The anticipation and surprise gives the start of the event extra excitement and serves as a means to inspire the participants in the same way that the "secret ingredient" is used in the TV show Iron Chef . Once the theme word or words have been announced, digest it for a while. Some suggestions for coming up with a great game concepts based on the theme are as follows: Take a walk Listen to music Mull over ideas away from the computer Come back home and sketch your idea Visualize the game being played before touching the keyboard Talk about the theme over dinner with a friend Sleep on it and start in the morning Use this theme word as the genesis for your creative spark. Let it inspire you to think outside your normal comfort zone. Don't get discouraged if you think the theme isn't something you like: any game concept can be easily manipulated to fit a theme. Add one subtle reference and whatever game you'd hoped to make is still a possibility. Haiku Time: Many ideas. They all seem to fit the theme! Must I choose just one? Games that tend to win Game Jam competitions often make use of the theme word to find endless material for humor. One very strange statistical anomaly is that in most Game Jams, these three themes always score well in the voting stages: evolution, kittens, and fishing. Time and time again they are "always a bridesmaid, never a bride" and tend to be in the top ten, rather than the chosen theme. In Ludum Dare, for example, the "evolution" theme has been in the top ten almost a dozen times over the last six or seven years. When will "the evolution of kitten fishing" finally be the theme of a Game Jam? What the experts say: Chevy Ray Johnston A great way to come up with an idea to fit the theme is to write down the first five things that come to mind, then toss 'em. Those are the ideas everybody else is already thinking of and/or making. If I could give one piece of advice to newcomers, it would be to make a really simple game, and spend all your time polishing it like crazy! Really polished games are addictive, impressive, and always popular. Visual polish of some sort always seems to give games a boost-up in votes in compos, and makes them more likely to be clicked on by judges (especially in short Jams, where 90% of the games have little to no graphics). But unless you just care about winning, don't sacrifice a fun or engaging and interesting game just to make it look pretty. The best thing about Game Jams is the ridiculous shortcuts and solutions developers come up with to solve design problems in such a short time span. I hope that in the future, Game Jams will see more people developing not just video games, but other types of games as well; and creative things in general. I'm talking about writing Jams, board Game Jams, card Game Jams, and tech Jams where people get together and try to solve technological problems with the same mindset and ambition. Jams are great. Chevy Ray Johnston is author of many games including Fat Wizard and Skullpogo, the creator of the FlashPunk game engine (which is frequently used in Game Jams), and two time winner of Ludum Dare with the games FleeBuster and Beacon. Twitter: http://twitter.com/chevyray Flashpunk : http://flashpunk.net/ Google+ : https://plus.google.com/103872388664329802170   An example of a winning entry Let's take an example theme and see what it might inspire you to create. Take "ESCAPE," the theme of Ludum Dare 21. The winner of Ludum Dare 21 (theme: ESCAPE) created a game where you had to run away from an alien death beam in various platform-style obstacle courses. Try it out: Flee Buster by Chevy Ray Johnston. Other notable entrants created puzzle games where you had to escape from a mansion, jail, dungeon, or reverse pinball where you were the ball trying to get past the bottom. The possibilities are endless. The key qualities that the top ten entries all had were: Humor Simple gameplay Simple graphics Easy to pick up and play (simple controls)
Read more
  • 0
  • 0
  • 25530

Packt
02 Apr 2012
7 min read
Save for later

Using Location in your iOS Apps – Core Location

Packt
02 Apr 2012
7 min read
Core Location framework – an overview Core Location implements all the three methods of location detection: GPS, Wi-Fi, and Cell Tower Triangulation. The developer can control location detection by only specifying the accuracy needed. Core Location then decides internally on which approach to use for actual location detection. When creating an application that uses the Core Location framework, you need to first add it to your project in Xcode and include the <CoreLocation/Corelocation.h> header files in your .m or .h file. The new iOS SDK 5 and Xcode 4.2 includes a nifty location simulation and debugging capability. Now we will understand how the location debugging feature helps you test your app by using different location values when your app is actually running in the simulator or a connected device. Time for action – location debugging Open the Hello Location application and run the application. If you are running your app on the iOS Simulator, then go to the Debug | Location Menu option where you can simulate multiple location inputs for your app, as shown in the following screenshot: If you are running your app on a connected device, you need to go to the Product | Debug | Simulate Location menu option in the Xcode 4 menu bar. Try changing to different locations and testing the app by clicking the Detect Location button in the app. Location data is reported in your application via the Core Location's Delegate object, CLLocationManagerDelegate. Based on the location service type used in your app, the corresponding Core Location Delegate function has to be implemented by your application to catch the appropriate location change event. We will look at it as we inspect the different Core Location Services. What just happened? We simulated location information on our iPhone, using the new feature of "Location Simulation" in iOS 5 SDK and Xcode 4.2. This new feature helps us analyze our app's behavior in different locations. In the preceding example, we changed the location values one-by-one and clicked on the Detect Location button to echo the geo co-ordinates of our labels. iOS 5 Location simulation includes significant location updates, region monitoring, and continuous location updates via the GPX file support (a GPX file is an XML file format that contains a sequence of Geo Coordinates, typically for Tours or Navigational purposes). Core location services The Core Location framework provides the following services: Standard location Significant change Region monitoring Geocoding and reverse Geocoding – CLGeocoder (Added in iOS 5 SDK) Direction using heading information Standard location Standard Location is the latitude and longitude information retrieved from Core Location. The Core Location Manager (the CLLocationManager object in the iOS SDK) returns this information in the CLLocation object. NSString *latitudeTextData = [[NSString alloc]initWithFormat: @"%g",locMgr.location.coordinate.latitude]; Here the location object is an instance of the CLLocation object that contains the latitude and longitude variables. Standard location service with the Core Location Manager is started with the startUpdatingLocation function. You can tell the Location Manager to stop updating the location with the stopUpdatingLocation function. distanceFilter and desiredAccuracy are two properties that define how often you will receive the location updates and how much accuracy (in meters) is required by your app. With distanceFilter, you will receive location information if the device has moved distance equal to or more than the value specified in the distanceFilter property. Accuracy of the location detections can be chosen from the following desiredAccuracy values: Table 1 Use/Try to use the lowest accuracy possible (the lowest accuracy your application can work with) to avoid more battery power consumption. Significant change With the Core Location framework, you can also request for location updates having significant location value changes only. This method provides excellent power saving options, as well as the ability of the device to send location updates even when your application is not running. This method uses Cellular Radio to detect the device location. To use the significant change location service in your app, you need to use the startMonitoringSignificantLocationChanges and stopMonitoringSignificantLocationChanges functions. Core Location framework caches the location data, it is a good idea to get the timestamp on the measurement objects to make sure your application receives the correct and updated location information. Region monitoring With the Region monitoring services, you can define geographical boundary-based tracking for your apps. Consider a simple example of a Weather app that can use Region Monitoring to detect the user's location based on physical boundaries and alert them if they cross a particular boundary, for example, if a user crosses a San Francisco city boundary towards San Jose, the app can trigger a boundary alert for the user and show him the new San Jose weather information. The startMonitoringForRegion and stopMonitoringForRegion methods of the location framework are used to start and stop region monitoring in your application. Boundary entering and exiting are monitored by locationManager:didEnterRegion and locationManager:didExitRegion. Boundary crossing deteci on also requires an accuracy factor to determine the crossing factor needed to trigger the alert. This is done by the startMonitoringForRegion:desiredAccuracy method. As with the Significant Change service, Region monitoring also works even if your application is not running. The most important part is that you need to register the Regions to be monitored with the device using the monitoredRegions property. Use smart programming techniques to shut down location services when not required in order to conserve battery power. Another good idea is to turn off location if accuracy does not improve over a course of time. Geocoding and reverse Geocoding – CLGeocoder The CLGeocoder along with the CLPlacemark object provide the Geocoding and Reverse Geocoding functions in the Core Location framework. Note that these are new APIs added in the iOS 5.0 SDK. The MKReverseGeocoder from the MapKit Framework has been deprecated. The CLGeocode object now handles the same. CLGeocode features as follows: Requests are asynchronous and support only one operation per request Supports multiple languages Supports Forward and Reverse Geocoding Does not require results to be displayed on a map Worldwide coverage Geocoding is done by any of the following three methods: geocodeAddressString:completionHandler: Geocodes a simple string, for example, Mountain View, San Francisco. geocodeAddressString:inRegion:completionHandler: Geocodes a specified string using regional information. Think of this as searching for the String Market Street in region San Francisco. geocodeAddressDictionary:completionHandler: Geocodes is a speci? ed address dictionary. This is a more structured geocoding request, usually providing the Address Street, Address City, and Address State fields in the AddressBook format. The following is an example code snippet for this function: CLGeocoder *geocoder =[[CLGeocoder alloc]init]; NSDictionary *address=[NSDictionary dictionaryWithObjectsAndKeys: @"32 Lincoln RoadRoad",kABPersonAddressStreetKey, @"Birmingham",kABPersonAddressCityKey,nil ]; [geocoder geocodeAddressDictionary:address completionHandler:^(NSArray *placemarks, NSError *error) { for(CLPlacemark *placemark in placemarks) { NSLog(@"Placemark %@",placemark); } }]; Don't forget to add the AddressBook framework in build phases in Xcode and import the header files required in your Hello_LocationViewController.m file from the Hello World example. #import <AddressBook/AddressBook.h> #import <AddressBook/ABPerson.h> You can find the code at the book's page at http://www.packtpub.com/iphone-location-aware-apps-beginners-guide/book – in a project called Hello Location – Geocode. Run the application and click on the Detect Location button and observe the Debug Console in Xcode; you should see an output as follows: Placemark 32 Lincoln Road, Solihull, England, B27 6, United Kingdom @ <+52.44378245,-1.81094734> +/- 100.00m This is the result of the geocoding, along with the accuracy of 100 meters. Reverse Geocoding is handled by the reverseGeocodeLocation:completionHandler method in the CLGeocoder class. The CLPlaceMark object is returned for both Forward and Reverse Geocoding. Direction using heading Heading information in the Core Location service signifies the direction in which the device is oriented. This information is very critical for augmented reality, navigation, and gaming applications. The direction in which a device is poini ng, reported by iOS devices with a magnetometer is known as heading, while direci on in which the iOS device is moving, reported by the GPS hardware, is known as course. The CLHeading object holds the heading data reported by the Location Manager. The startUpdatingHeading method in the Location Manager is used to start the heading update process, while stopUpdatingHeading is used to stop it. The CLHeading object contains the following properties: Table 2
Read more
  • 0
  • 0
  • 5208

article-image-cisco-unified-communications-manager-8-call-routing-dial-plan-and-e164
Packt
30 Mar 2012
13 min read
Save for later

Cisco Unified Communications Manager 8: Call Routing, Dial Plan, and E.164

Packt
30 Mar 2012
13 min read
Further resources related to this subject: Introduction Even if you're not interested in E.164, the recipes in this article can be applied to building any style of dial plan while utilizing some of the feature benefits to make dial plan management easier than before. Implementing local route groups with device pools for E.164 call routing To simplify call routing and dial plan management, local route groups provide a logical way to process calls according to settings specific to the device pool of the originating device. Getting ready This recipe assumes you have a gateway or trunk device configured. How to do it... To implement a local route group for use with a device pool, perform the following: Add a new route list that will serve as the link to the local route groups (Call Routing Route/Hunt | Route List|). Click on Add New to add a new route list. Type in a name and select a Call Manager Group in the drop-down with which the route list will be associated: Click on Save. Once the page reloads, click on Add Route Group and a new page will open. Select Standard Local Route Group from the Route Group drop-down menu then click on Save. You will be returned to the Route List page: Finally, click on Save to save the Route List. Add a new route group containing the gateway or trunk (Call Routing Route/Hunt | Route Group|). Find and select your gateway or trunk under the Find Devices to Add to Route Group section. Then click on Add to Route Group. You should now see the device in the Selected Devices list: Click on Save. The device will show up under Route Group Members. Assign the route group you created in the previous step to the device pool by navigating to the device pool (From the menu, System Device Pool|) configuration page and selecting the route group from the Local Route Group drop-down under the Device Pool Settings section: Click on Save. These changes will not take effect until you reset the devices in the device pool. How it works... Prior to the introduction of local route groups in CUCM, dial plans relied on route patterns pointing to specific gateways and route lists in site-specific partitions. By utilizing local route groups with device pools we can simplify call routing and reduce the number of route patterns needed throughout the system, thereby making the overall system simpler and maintenance easier. There's more... When a call is placed on the system it matches a route pattern that informs the system where to send the call, typically a route list containing trunks and gateways. When the system is told to send the call to a route list containing the Standard Local Route Group, the egress gateway is determined by information pulled from the device pool settings of the device that initiated the call, and routes it accordingly. Implementing E.164 route patterns and partitions An advantage of an E.164 dial plan is that it requires only a single route pattern to make it all work, though additional route patterns are still needed to allow users to dial using traditional dialing and TEHO. Here we will create the route partition to be used by the E.164 route pattern. How to do it... To create the route pattern to support an E.164 dial plan, we will do the following: Add a new partition, which will be globally accessible, by clicking Add New on the Partitions page located in the Class of Control submenu under the Call Routing menu. Enter in a partition name and a description in the text box and then click on Save. Add the E.164 Route Pattern and assign the Route List to it (Call Routing Route/ Hunt | Route Pattern|). Click on Add New. Enter +.! for the Route Pattern and select the route partition previously created in the Route Partition drop-down: From the Gateway/Route List* drop-down, select the route list containing the Standard Local Route Group. Ensure that the Call Classification is OffNet and the Route Option is set to Route this pattern. Click on Save.   Add the calling party transformation pattern (Call Routing | Transformation | Transformation Pattern | Calling Party Transformation Pattern|). Add the transformation pattern appropriate to your environment and location: Prefix any necessary digits and select the appropriate digit discard field. In the case of the previous example, Discard Digits is set to PreDot with no digits being prefixed. Add the called party transformation pattern (Call Routing Transformation | Transformation Pattern | Called Party Transformation Pattern|). Add the appropriate transformation pattern and any prefix digits necessary. In this case, we again choose PreDot for Discard Digits and set Prefix Digits to 9. Refer to the There's more... section for further explanation if required. Navigate to the configuration page for the port or device. On a MGCP controlled gateway, transformations are configured on a per port basis. The configuration page for the port is found by navigating to the configuration page for the gateway, then selecting the appropriate T1 port under the Configured Slots, VICs and Endpoints section as indicated in the following screenshot: This is configured at the device level for trunks and gateways. Next we apply the transformations to our trunks or gateways. Calling party transformations are configured under the section titled Incoming Calling Party Settings. The type of device we are configuring will determine the fields available to us. On gateway devices we see National, International, Unknown, and Subscriber. On trunk devices we see Incoming Number. Select the Calling Search Space that contains the partitions you assigned to the called and calling party transformation patterns and apply it to all applicable fields: The previous screenshot is for an SIP trunk. Here we uncheck Use Device Pool CSS as we are not using the device pool for number transformation. Finally, called party transformations are configured under different sections depending on the type of device. On the gateways configuration page, this section is called Call Routing Information - Outbound Calls, and Outbound Calls for trunks. Again, we are not using the device pool for number transformation, so we uncheck boxes for both calling and called device pool transformations. The calling search space selected for the Called and Calling Party Transformation CSS must contain the partitions used when creating the transformation patterns. How many locations? Multinational? Will short dials (or hot numbers) be used? What about multinational dialing considerations? PT-Line PT-System PT-Global-E164 PT-US-DialPlan PT-UK-DialPlan PT-US-SFO-DialPlan Calling party transformation patterns: In the example from the recipe you see a calling party transformation pattern using +1.!. As we explain in the example, we discard digits PreDot. We do this to normalize the number users see when their phone is ringing and connected, as users in the United States may not be accustomed to seeing +1 before the number. Alternatively, say we have an office in San Francisco where users are accustomed to seeing only seven digits for local calls and ten for everything else. We still use the +1.! PreDot pattern to remove the +1 for calls but we add another pattern to strip the area code off. In this case that pattern would be +1415.!, stripping PreDot with a partition of PT-SFO-Inbound-ANI, or something similar. By doing this, calls from 415 numbers will show as seven digits on the display when ringing and connected. Called party transformation patterns: Prior to local route groups and called party transformations, you would prepare the dialed number to be sent to the gateway or route list on the route pattern itself. Called party transformation patterns would then be used to prepare the dialed digits to be accepted by the gateway, trunk, or PSTN. In many cases this involves stripping the plus sign and prefixing an access code before sending it out to the gateway or trunk to route the call to the PSTN. How we modify the number depends on the type of gateways or trunks we are using. With MGCP gateways, we format the number so that it can be sent across to the PSTN. In some cases this means removing the plus, and appending or removing digits depending on what the carrier expects. For instance, if the carrier expects seven digits for local calls and 1 + 10 digits for long distance calls, we might strip the +1 and area code for local calls and strip only the plus for all other calls. For gateways and trunks, access codes are typically configured to inform the gateway or trunk to send the call to the PSTN. Typically these are 9, or 91. In this situation we would strip the necessary digits and prefix the access code appropriate to the call. For example, say our carrier requires seven digits for local and eleven digits for long distance calls; assuming we require an access code of 9 for local and 91 for long distance calls, we might implement the following called party transformations: +1.! Partition: PT-SFO-Outbound-DNIS Prefix digits: 91 +1415.! Partition: PT-SFO-Outbound-DNIS Prefix digits: 9 Now, when a call is made to +1 415 555 1234, for example, the transformation pattern will remove +1415 and append a 9, sending the call to the gateway or trunk as 95551234 where it would match a dial peer before being sent out to the PSTN. While it is possible to do these transformations on the gateway themselves, managing them in UCM provides a central point for configuration and can help reduce dial plan maintenance. CSS-SFO-Outbound-ANI PT-SFO-Outbound-ANI PT-US-Outbound-ANI CSS-SFO-Outbound-DNIS PT-SFO-Outbound-DNIS PT-US-Outbound-DNIS CSS-SFO-Inbound-ANI PT-SFO-Inbound-ANI PT-US-Inbound-ANI CSS-US-Inbound-ANI PT-US-Inbound-ANI DID ranges of locations for which we are implementing LCR Site codes of locations for which we are implementing LCR Local numbers per location for Tail End Hop Off DID Range for this location: +1 415 555 1000 to 1099 Site code for this location: 11 Local numbers for this location: 415 XXX XXXX Add a new route list that will contain the route group with the gateway or trunk device local to the location for which we are implementing LCR, as well as the Standard Local Route Group: The order here is important. Ensure the local route group is above the Standard Local Route Group in the list. Add a new route pattern to send local calls to our new route list. Key fields to note here are Route Pattern, Route Partition, and Gateway/Route List*: Here we have unchecked Provide Outside Dial Tone as it is unused, but feel free to leave it checked. Next add a translation pattern (Call Routing Translation Pattern|, then click on Add New) that is responsible for converting E.164 numbers to their internal extensions. Here the Translation Pattern must match only the DID range for the location. For our recipe the pattern is +1415555.10XX. For the partition use something that is globally accessible, for example PT-Global-E164: First, create the partitions with the necessary descriptions (Call Routing Class of Control | Partition|): Next, create the calling search spaces (Call Routing Class of Control | Calling Search Space|): Finally, add the translation pattern for the blocking patterns (Call Routing Translation Pattern|): It is important to note here that we have used the Partition PT-US-Block-National with a Route Option set to Block this pattern. National/long distance International Premium CSS-US-Line-National PT-US-Block-National PT-US-Block-International PT-US-Block-Premium CSS-US-Line-International PT-US-Block-International PT-US-Block-Premium CSS-US-Line-Premium PT-US-Block-Premium CSS-US-Line-Unrestricted No partitions selected For seven digit dial plans: 91.[2-9]XXXXXXXXX +1[2-9]XXXXXXXXX 9.011! 9.011!# +[^1] The pattern +[^1] will match any E.164 number that does not start with a one. For instance, the pattern will match +44 but not +1. 9.1900XXXXXXX +1900XXXXXXX 124[26][2-9]XXXXXX 126[48][2-9]XXXXXX 1284[2-9]XXXXXX 134[05][2-9]XXXXXX 1441[2-9]XXXXXX 1473[2-9]XXXXXX 1649[2-9]XXXXXX 1664[2-9]XXXXXX 1758[2-9]XXXXXX 1767[2-9]XXXXXX 178[47][2-9]XXXXXX 1809[2-9]XXXXXX 186[89][2-9]XXXXXX 1876[2-9]XXXXXX 1976[2-9]XXXXXX How it works... When an E.164 number is dialed, the system will match it against the route pattern. The purpose of this pattern is to get the call to route to the local gateway or trunk where number normalization occurs, before sending the call out to the local gateway. Call Classification is set to OffNet for this pattern because we expect any calls that match this pattern to be routed out to the PSTN. There's more... Implementing a successful dial plan requires a few considerations from a technical perspective as well as a user experience standpoint. Dial plan considerations and partitions Partitions are a crucial part of both the dial plan and the implementation of calling restrictions. Having a well designed partition scheme can make management easier and it isn't difficult to implement. Some things to consider when planning your partition scheme are as follows: Common system partitions In most systems there are a few basic requirements from a partitioning perspective and at the very least we want to separate user directory numbers from system numbers. To accomplish this we might have the following partitions: If this is an E.164 dial plan, we want to separate the partitions from the rest of the system. That is why we also include: Partitioning at a national level In order to support a basic multinational dial plan we need partitions for dialing rules specific to each nation, for example: We would typically use these partitions for any patterns that reach the PSTN, including emergency and information services, as well as regular outbound calls. Partitioning at a local level If location specific dial rules are required, we might have partitions for each location. For example: By doing this at the location level, we can allow for location specific short dials or dialing rules. For example, if we wanted to implement extension 4357 as a short dial to reach the local help desk, we would use a location specific partition such as that shown previously. Dial plan considerations and route patterns It's important to define how users will access the outside world based on what they are familiar with. In many corporations, dial plan rules exist to allow local calls to be dialed first with a 9 or 91, followed by seven or ten digits; other companies may require nine or ten digits for all calls. We call this seven digit and ten digit dialing, respectively. Regardless of which dialing method is used, the setup is the same and thanks to E.164 you only need one route pattern to support all locations. Seven digit dialing To implement seven digit dialing we will add another route pattern as explained earlier, which is the 9.[2-9]XXXXXX pattern: Unlike the earlier example, we want to strip the 9 off and append a plus sign. This is necessary so the call will match the +.! pattern before it can be routed to the local gateway or trunk: In situations where you are not using an E.164 dial plan but want to implement seven digit dialing, you need to only put the pattern in a location specific partition and point the Gateway/Route List* to the appropriate route list or gateway. In this situation, you would not prefix the plus sign. Don't forget to include a pattern for non-local calls! Ten digit dialing To configure ten digit dialing, follow the previous steps and instead use a pattern of 9.[2-9]XXXXXXXXX.
Read more
  • 0
  • 0
  • 8704

article-image-collaboration-features-alfresco-share
Packt
27 Mar 2012
19 min read
Save for later

Collaboration Features in Alfresco Share

Packt
27 Mar 2012
19 min read
(For more resources on Alfresco, see here.) The wiki page The wiki page list displays a summary of all pages created for the current site's wiki. A browsing pane on the left side of the page enables you to populate the wiki list with a subset of the wiki content. Selecting a page in the wiki list displays the entire wiki page in the page view.   When you enter the wiki page, the page view displays the wiki main page. Click Wiki Page List to display the wiki list.   You can create, delete, view details for, and edit a wiki page in both views. To perform some of the operations on a wiki page like renaming a page, you must be on the wiki page.   How to access the wiki page Accessing the wiki page gives you access to all wiki content. Within the wiki you can create, delete, rename, and edit the wiki pages. You can perform most actions from both the wiki list and the page view.   To access the wiki page, perform the following steps: Enter the Marketing Site . On the banner, click Wiki. The wiki page appears, displaying the main wiki page for this site in the page view. In this view, the actions you can perform on the current wiki page appear as buttons beneath the banner (New Page, Delete , Rename) and as links at the top right of the content area ( View Page, Edit Page, Details): (Click on the image to enlarge.) Click Wiki Page List to display the wiki list. The wiki list displays a summary of all pages in the wiki for the current site. In this view, the actions you can perform on a wiki page appear as buttons beneath the banner (only New Page is available in this view) and as links to the right of each page summary. Browsing the wiki pages Assuming that you are on the wiki page of the Marketing Site , the browsing pane to the left of the wiki page list enables you to filter the wiki content to make locating specific wiki pages more manageable. The wiki page list displays all wiki pages in the current site, organized chronologically. The most recent page appears at the top of the list. The browsing pane on the left side of the page enables you to display a subset of the wiki content by selecting a specific view or a tag. Whether browsing by view or tag, the wiki list displays a summary of all pages matching the selected option. The summary includes the wiki page name, author, creation and modification dates, a sample of the content, and the tags associated with the page. The browsing pane provides the following views: Recently Modified: In this view, the user can see the pages modified recently, for instance pages modified in the past seven days. All: This displays all pages created in the wiki for the current site. Recently Added: This displays the pages created recently, like in the past seven days. My Pages: In this view, the user can see the pages created by himself/herself. Tags: This displays all tags currently associated with one or more wiki pages. By clicking on an individual tag, the user can see all the wiki pages tagged with that particular tag. To browse the wiki pages perform the following steps: Click Wiki Page List on the page view to navigate to the wiki list, if it is not already displayed. Select the desired option in the browsing pane. In the Pages list, click the view representing the wiki pages you want to display. The wiki list displays all pages in the current site that correspond to the selection. In the Tags list, click the tag of interest. The wiki list displays all pages in the current site associated with the selected tag. n the wiki list, click a wiki page title to display that full page. The selected wiki page appears in the page view. Creating the wiki main page When any new site is created with a wiki page, it contains a main wiki page, which will be, by default, empty. And this can be considered as an introductory page for the site wiki. To add content to the wiki main page perform the following steps: Click Main Page beneath the banner if the main page is not already displayed. Click Edit Page. Type the content for the main page in the Text box. Use the formatting features provided to markup the content, insert bulleted and numbered lists, and include hyperlinks: Optionally, add tags for the main page. Type tags in the box provided and click Add. To add multiple tags, separate each tag with a space. Click Choose from popular tags in this site to display the existing tags used in this site. Click a tag to associate it with the main page. The newly associated tags appear beneath the Text box. Click a tag to remove it. Click Save. The page view displays the main page. Creating a new wiki page You can create a new wiki page from both the wiki list and the page view. To create a new wiki page perform the following steps: Click New Page to create the wiki page. Enter a Title for the page. When your title contains a disallowed character, like some special characters, such as quotation marks, periods, colons, and asterisks (*), the Save button is disabled. Type the wiki page content in the Text box. Use the formatting features provided to markup the content, insert bulleted and numbered lists, and include hyperlinks. To create a link to another wiki page, type Page Name. If the page indicated does not exist, Share creates it; however, this is an empty wiki page and it will not appear in the wiki list until you select Edit Page and provide content for it. Optionally, add tags for the wiki page. Type a tag or multiple tags, separated by a space, in the box provided and click Add. Click Choose from popular tags in this site> to display the existing tags used in this site. Click a tag to associate it with the new wiki page. The newly associated tags appear beneath the Text> box. Click a tag to remove it. Click Save. The new wiki page appears as users will see it. Click Wiki Page List to return to the wiki list: Editing a wiki page Adding and editing wiki content happens in a simple browser. You can perform this task from both the wiki list and the page view. To edit a wiki page perform the following steps: Click Edit for the page you want to modify. If the wiki page you want to edit is already open in the page view, simply click Edit Page. The content of the selected wiki page displays in an editing box. Make the required changes to the content. To create a link to another wiki page, type Page Name. If the page indicated does not exist, Share creates it; however, this is an empty wiki page and it will not appear in the wiki list until you select Edit Page and provide content for it. To edit the tags for this wiki page perform the following steps: To add a new tag, type a tag in the box provided and click Add. To add multiple tags, separate each tag with a space. To add an existing tag, click Choose from popular tags in this site to display the tags used in this site. Click a tag to associate it with the wiki page. To remove an existing tag from the set beneath the Text box, click the tag you want to remove. Click Save. The page view displays the updated wiki page. Renaming a wiki page You can rename a wiki page in the page view. When you rename a wiki page, the updated page retains the page history. Share creates a new page with the original page name; this page links to the updated page. To rename a wiki page perform the following steps: Click the title of the page that you want to rename. Click Rename. The Rename page opens. Type the new name for the wiki page. Click Save. The page view reflects the name change and this wiki page retains the page history of the original page. Share creates a new page with the original page name, which links to the updated page. Deleting a wiki page Delete a wiki page you no longer want to appear in the wiki for the current site. You can perform this task from both the wiki list and the page view. To delete a wiki page perform the following steps: In the wiki list, locate the wiki page you want to delete. Click Delete for that page. If the wiki page you want to delete is already open in the page view, simply click Delete on that page. A message prompts you to confirm the deletion. Click Yes to delete the current wiki page View the details for a wiki page to see the version history, view the tags associated with the page, and list the wiki pages that link to the selected page. You can view the page details from both the wiki list and the page view. To view the wiki page details perform the following steps: Click Details for the page whose details you want to view. If the wiki page you want to view is already open in the page view, simply click Details on that page. The page view displays the wiki page content in an expanded form to include the Version History, Tags, and Linked Pages. From this page, you can click Edit Page to make any necessary changes. Click View Page to hide the details. The wiki page displays in the page view: For more details on the Alfresco Share wiki feature, refer to the link: http://docs.alfresco.com/4.0/ index.jsp?topic=%2Fcom.alfresco.enterprise. doc%2Fconcepts%2Fwiki-intro.html. The Blog page Site members can create, edit, and add comments to blog postings. The Blog page enables you to add commentary, descriptions of events, and other material related to your site. The postings can be saved as drafts and then, when ready can be published. The blogs can be published as an internal blog and also to an external blogging site, including WordPress and TypePad. We will discuss more about how you can configure your blog to get published on external blog sites from Alfresco Share in a later section of this article. How to access a Blog page Accessing the Blog page enables you to view all published blog posts for the Marketing Site . Within the blog, you can create new posts, as well as edit, publish, and delete posts you created. You can also add comments to existing blog posts. To access the Blog page perform the following steps: Enter the Marketing Site. On the banner, click Blog. The Blog page appears. The default view, Latest, is selected and the post list displays a summary of the posts created or edited in the past seven days. The summary includes the post title, date and time the post was published (if applicable), the author who created the post, a sample of the content, the number of replies to the post, and the tags associated with the post. The Previous and Next navigation buttons help move through multiple pages of posts. Click Simple List> to display only the title of the posts. Click Detailed List to display the summary view. Browsing the blog The browsing feature in the Blog page enables you to filter the blog posts. This allows you to more easily navigate the blog content. A subset of the blog posts by selecting a specific view, a period of time (month), or a tag is displayed on the left hand browsing pane. The Posts list in the browsing pane provides the following views/filters: All: In this view, the user can see all posts in the blogs. Latest: This view displays only the posts created, or modified, recently like in the past seven days. My Drafts: Here, the user can see the posts created by himself/herself that are saved as drafts (not yet published) My Published: This view displays the posts created and published, either externally or internally, by the current user. Published Externally: In this view, all posts that have been published to an external blog are displayed. Archives: This view organizes posts by month and year. This will have further sub lists of month and year. Tags: Here, the list displays all tags currently associated with one or more blog posts. By clicking on an individual tag, the user can see all the posts tagged with that particular tag. To browse the blog posts perform the following steps: Select the desired option in the browsing pane. In the Posts list, click the view representing the posts you want to view. The post list displays all blog posts in the current site that correspond to the selection. In the Archives list, click the month of interest. The post list displays all blog posts in the current site published during that month. In the Tags list, click the tag of interest. The post list displays all posts in the current site associated with the selected tag. Click Simple List to display only the title of the posts. Click Detailed List to display the summary view Creating a blog post Create a new blog post to add information or a commentary related to the current site. When you create a new post, you can save it as a draft without publishing it, or you can immediately publish it to the blog on the Marketing Site . You also have the option of publishing the post to both the internal blog and a configured external blog To create a new post perform the following steps: Click New Post. The Create Blog Post page appears. Type a Title for the post. Type the post content in the Text box. Use the formatting features provided to markup the content, insert bulleted and numbered lists, and include hyperlinks.Optionally, add tags for the blog post: Type a tag in the box provided and click Add. To add multiple tags, separate each tag with a space. Click Choose from popular tags in this site to display the existing tags used in this site. Click a tag to associate it with the new post: The newly associated tags appear beneath the Text box. Click a tag to remove it. To save or publish the new blog post perform the following steps: Click Save as Draft to save the post without publishing it. The post will not appear in the post list. Click Publish Internally to publish the post to the internal blog, making it available for other users of this site. Click Publish Internally and Externally to publish the post to both the internal and external blogs. The new post appears as users will see it. The text (Draft) appears after the title if the post remains unpublished. Click Go to Post List to return to the main view. Editing a blog post Only the Marketing Site Manager, and the user who created the blog post, can edit it to modify or add to its content. To edit an existing post perform the following steps: In the post list, locate the blog post you want to edit. Click Edit. The Edit Blog Post page appears displaying the selected post. Make the desired changes to the post title and content. To edit the tags for this post perform the following steps: To add a new tag or multiple tags, each separated with a space, type a tag in the box provided and click Add. To add an existing tag, click Choose from popular tags in this site to display the tags used in this site. Click a tag to associate it with the new blog post. To remove an existing tag from the set beneath the Text box, click the tag you want to remove: To save or publish the updated blog post perform the following steps: Click Update to save the changes. Click Publish Internally to save the changes and publish the post to the internal blog, making it available for other site members. This option appears only for draft posts. Click Update Internally and Publish Externally to publish the post to both the internal and external blogs. The updated post appears as users will see it. The text (updated) appears after the title. Click Go to Post List to return to the main view. Viewing a blog post Browsing the blog displays either a summary view or a simple list of the existing posts in the main window of the Blog page. Viewing a post allows you to see the full contents of the post. You can perform actions on a post from the main page, but viewing a post enables you to confirm that you have selected the correct post before performing irreversible actions, such as deleting and publishing the post. While the same actions are available in both views (Edit, Publish Externally, and Delete ), you must view a post to add a comment to it. To view a blog post perform the following steps: Browse the blog posts to locate the post you want to view. Click the title of the post or click Read beneath the post. If the main page displays posts in a simple list, you must click the title of the post. The post view displays the selected blog post, along with any related comments. Click Go to Post List to return to the main view. Deleting a blog post Delete a blog post to permanently remove it from the blog of the Marketing Site. Deleting a post also deletes all of its comments. Only a Site Manager and the user who created the blog post can delete it. To delete a post perform the following steps: In the post list, locate the blog post you want to delete. Click Delete. A message prompts you to confirm the deletion f the selected post. Click Delete. A message indicates the selected blog post has been deleted. Configuring the external blog In addition to creating blog posts and publishing them internally within the site, you can publish the blog posts to an existing WordPress or TypePad blog. To publish the site blogs externally, you must configure the external blog details. To configure an external blog perform the following steps: Click Configure External Blog. The Configure External Blog page appears. In the Type list, select the appropriate option: Select WordPress to configure the external blog to run on the WordPress blog publishing system. Select TypePad to configure the external blog to run on a TypePad blogging service. Complete the remaining fields with the details of the external blog. The User Name and Password provided must be the user details of the author, or administrator, responsible for posting the external blog. Click OK: Publishing a post to an external blog In addition to publishing a blog post to the internal blog of the Marketing Site , you can publish a post to a configured external blog. To publish a draft post externally, you must also publish it internally. To publish a post externally perform the following steps: In the post list, locate the blog post you want to publish externally. Click Publish Externally. Optionally, open the post to perform this action. A message indicates the selected blog post is published. Working with comments Adding comments to a blog post can help make a site blog interactive. People can comment on the post and provide their views or comments for any blogs written by other users. While all users with access to the Marketing Site can view the blog conversations, only site members can add comments. The number of replies added to a post is displayed in the post list beneath the post summary. You must view a post to add, view, and manage the related comments. Adding a comment to a post In the Blog page, you can add a comment to reply to any published blog post. To add a comment perform the following steps: In the post list, locate the blog post to which you want to add a comment. Click the post title to view the post. The post view displays the selected blog post, along with any related comments. Type the post comment in the Add comment box. Use the formatting features provided to markup the content, insert bulleted and numbered lists, and include hyperlinks. Click Create comment. The comment displays beneath the post. Click Go to post list to return to the main view: Editing a comment You can edit a blog comment to modify or add to its content. Only a Site Manager, and the user who created the comment, can edit it. To edit a comment perform the following steps: In the post list, locate the blog post containing the comment you want to edit. Click the post title to view the post. The post view displays the selected blog post and the related comments. Click Edit to the right of the comment you want to change. The Edit Comment box appears, displaying the selected comment. Make the desired changes to the comment. Click Update. The updated comment displays beneath the post. Click Go to Post List to return to the main view. Deleting a comment Delete a comment to permanently remove it from a blog post. Only a Site Manager, and the user who created the comment, can delete it. To delete a comment perform the following steps: In the post list, locate the blog post containing the comment you want to delete. Click the post title to view the post. The post view displays the selected blog post and the related comments. Click Delete. A message prompts you to confirm the deletion of the selected comment. Click Delete. A message indicates the selected comment has been deleted. Click Go to Post List to return to the main view.
Read more
  • 0
  • 0
  • 3426

article-image-combining-silverlight-and-windows-azure-projects
Packt
22 Mar 2012
6 min read
Save for later

Combining Silverlight and Windows Azure projects

Packt
22 Mar 2012
6 min read
Combining Silverlight and Windows Azure projects Standard Silverlight applications require that they be hosted on HTML pages, so that they can be loaded in a browser. Developers who work with the .Net framework will usually host this page within an ASP.Net website. The easiest way to host a Silverlight application on Azure is to create a single web role that contains an ASP.Net application to host the Silverlight application. Hosting the Silverlight application in this way enables you, as a developer, to take advantage of the full .Net framework to support your Silverlight application. Supporting functionalities can be provided such as hosting WCF services, RIA services, Entity Framework, and so on. In the upcoming chapters, we will explore ways by which RIA services, OData, Entity Framework, and a few other technologies can be used together. For the rest of this chapter, we will focus on the basics of hosting a Silverlight application within Azure and integrating a hosted WCF service. Creating a Silverlight or Azure solution Your system should already be fully configured with all Silverlight and Azure tools. In this section, we are going to create a simple Silverlight application that is hosted inside an Azure web role. This will be the basic template that is used throughout the book as we explore different ways in which we can integrate the technologies together: Start Visual Studio as an administrator. You can do this by opening the Start Menu and finding Visual Studio, then right-clicking on it, and selecting Run as Administrator. This is required for the Azure compute emulator to run successfully. Create a new Windows Azure Cloud Service. The solution name used in the following example screenshot is Chapter3Exercise1: (Move the mouse over the image to enlarge.) Add a single ASP.Net Web Role as shown in the following screenshot. For this exercise, the default name of WebRole1 will be used. The name of the role can be changed by clicking on the pencil icon next to the WebRole1 name: Visual Studio should now be loaded with a single Azure project and an ASP. Net project. In the following screenshot, you can see that Visual Studio is opened with a solution named Chapter3Exercise1. The solution contains a Windows Azure Cloud project, also called Chapter3Exercise1. Finally, the ASP.Net project can be seen named as WebRole1: Right-click on the ASP.Net project named WebRole1 and select Properties. In the WebRole1 properties screen, click on the Silverlight Applications tab. Click on Add to add a new Silverlight project into the solution. The Add button has been highlighted in the following screenshot: For this exercise, rename the project to HelloWorldSilverlightProject. Click on Add to create the Silverlight project. The rest of the options can be left to their default settings, as shown in the following screenshot. Visual Studio will now create the Silverlight project and add it to the solution. The resulting solution should now have three projects as shown in the following screenshot. These include the original Azure project, Chapter3Exercise1; the ASP.Net web role, WebRole1; and the third new project HelloWorldSilverlightProject: Open MainPage.xaml in design view, if not already open. Change the grid to a StackPanel. Inside the StackPanel, add a button named button1 with a height of 40 and a content that displays Click me!. Inside the StackPanel, underneath button1, add a text block named textBlock1 with a height of 20 The final XAML should look similar to this code snippet: <UserControl> <StackPanel x_Name="LayoutRoot" Background="White"> <Button x_Name="button1" Height="40" Content="Click me!" /> <TextBlock x_Name="textBlock1" Height="20" /> </StackPanel> </UserControl> Double-click on button1 in the designer to have Visual Studio automatically create a click event. The final XAML in the designer should look similar to the following screenshot: Open the MainPage.xaml.cs code behind the file and find the button1_Click method. Add a code that will update textBlock1 to display Hello World and the current time as follows: private void button1_Click(object sender, RoutedEventArgs e) { textBlock1.Text = "Hello World at " + DateTime.Now.ToLongTimeString(); } Build the project to ensure that everything compiles correctly.Now that the solution has been built, it is ready to be run and debugged within the Windows Azure compute emulator. The next section will explore what happens while running an Azure application on the compute emulator. Running an Azure application on the Azure compute emulator With the solution built, it is ready to run on the Azure simulation: the compute emulator. The compute emulator is the local simulation of the Windows Azure compute emulator which Microsoft runs on the Azure servers it hosts. When you start debugging by pressing F5 (or by selecting Debug | Start Debugging from the menu), Visual Studio will automatically package the Azure project, then start the Azure compute emulator simulation. The package will be copied to a local folder used by the compute emulator. The compute emulator will then start a Windows process to host or execute the roles, one of which will be started as per the instance request for each role. Once the compute emulator has been successfully initialized, Visual Studio will then launch the browser and attach the debugger to the correct places. This is similar to the way Visual Studio handles debugging of an ASP.Net application with the ASP. Net Development Server. The following steps will take you through the process of running and debugging applications on top of the compute emulator: In Solution Explorer, inside the HelloWorldSilverlightProject, right-click on HelloWorldSilverlightProjectTestPage.aspx, and select Set as startup page. Ensure that the Azure project (Chapter3Exercise1) is still set as the start-up project. In Visual Studio, press F5 to start debugging (or from the menu select Debug | Start Debugging). Visual Studio will compile the project, and if successful, begins to launch the Azure compute emulator as shown in the following screenshot: Once the compute emulator has been started and the Azure package deployed to it, Visual Studio will launch Internet Explorer. Internet Explorer will display the page set as the start-up page (which was set to in an earlier step HelloWorldSilverlightProjectTestPage.aspx). Once the Silverlight application has been loaded, click on the Click me! button. The TextBlock should be updated with the current time, as shown in the following screenshot: Upon this completion, you should now have successfully deployed a Silverlight application on top of the Windows Azure compute emulator. You can now use this base project to build more advanced features and integration with other services. Consuming an Azure-hosted WCF service within a Silverlight application A standalone Silverlight application will not be able to do much by itself. Most applications will require that they consume data from a data source, such as to get a list of products or customer orders. A common way to send data between .Net applications is through WCF services.
Read more
  • 0
  • 0
  • 2948
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-introduction-logging-tomcat-7
Packt
21 Mar 2012
9 min read
Save for later

Introduction to Logging in Tomcat 7

Packt
21 Mar 2012
9 min read
(For more resources on Apache, see here.) JULI Previous versions of Tomcat (till 5.x) use Apache common logging services for generating logs. A major disadvantage with this logging mechanism is that it can handle only single JVM configuration and makes it difficult to configure separate logging for each class loader for independent application. In order to resolve this issue, Tomcat developers have introduced a separate API for Tomcat 6 version, that comes with the capability of capturing each class loader activity in the Tomcat logs. It is based on java.util.logging framework. By default, Tomcat 7 uses its own Java logging API to implement logging services. This is also called as JULI. This API can be found in TOMCAT_HOME/bin of the Tomcat 7 directory structures (tomcat-juli.jar). The following screenshot shows the directory structure of the bin directory where tomcat-juli.jar is placed. JULI also provides the feature for custom logging for each web application, and it also supports private per-application logging configurations. With the enhanced feature of separate class loader logging, it also helps in detecting memory issues while unloading the classes at runtime. For more information on JULI and the class loading issue, please refer to http://tomcat.apache.org/tomcat-7.0-doc/logging.html and http://tomcat.apache.org/tomcat-7.0-doc/class-loader-howto.html respectively. Loggers, appenders, and layouts There are some important components of logging which we use at the time of implementing the logging mechanism for applications. Each term has its individual importance in tracking the events of the application. Let's discuss each term individually to find out their usage: Loggers:It can be defined as the logical name for the log file. This logical name is written in the application code. We can configure an independent logger for each application. Appenders: The process of generation of logs are handled by appenders. There are many types of appenders, such as FileAppender, ConsoleAppender, SocketAppender, and so on, which are available in log4j. The following are some examples of appenders for log4j: log4j.appender.CATALINA=org.apache.log4j.DailyRollingFileAppender log4j.appender.CATALINA.File=${catalina.base}/logs/catalina.out log4j.appender.CATALINA.Append=true log4j.appender.CATALINA.Encoding=UTF-8 The previous four lines of appenders define the DailyRollingFileAppender in log4j, where the filename is catalina.out . These logs will have UTF-8 encoding enabled. If log4j.appender.CATALINA.append=false, then logs will not get updated in the log files. # Roll-over the log once per day log4j.appender.CATALINA.DatePattern='.'dd-MM-yyyy'.log' log4j.appender.CATALINA.layout = org.apache.log4j.PatternLayout log4j.appender.CATALINA.layout.ConversionPattern = %d [%t] %-5p %c- %m%n The previous three lines of code show the roll-over of log once per day. Layout: It is defined as the format of logs displayed in the log file. The appender uses layout to format the log files (also called as patterns). The highlighted code shows the pattern for access logs: <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log." suffix=".txt" pattern="%h %l %u %t &quot;%r&quot; %s %b" resolveHosts="false"/> Loggers, appenders, and layouts together help the developer to capture the log message for the application event. Types of logging in Tomcat 7 We can enable logging in Tomcat 7 in different ways based on the requirement. There are a total of five types of logging that we can configure in Tomcat, such as application, server, console, and so on. The following figure shows the different types of logging for Tomcat 7. These methods are used in combination with each other based on environment needs. For example, if you have issues where Tomcat services are not displayed, then console logs are very helpful to identify the issue, as we can verify the real-time boot sequence. Let's discuss each logging method briefly. Application log These logs are used to capture the application event while running the application transaction. These logs are very useful in order to identify the application level issues. For example, suppose your application performance is slow on a particular transition, then the details of that transition can only be traced in application log. The biggest advantage of application logs is we can configure separate log levels and log files for each application, making it very easy for the administrators to troubleshoot the application. Log4j is used in 90 percent of the cases for application log generation. Server log Server logs are identical to console logs. The only advantage of server logs is that they can be retrieved anytime but console logs are not available after we log out from the console. Console log This log gives you the complete information of Tomcat 7 startup and loader sequence. The log file is named as catalina.out and is found in TOMCAT_HOME/logs. This log file is very useful in checking the application deployment and server startup testing for any environment. This log is configured in the Tomcat file catalina.sh, which can be found in TOMCAT_HOME/bin. The previous screenshot shows the definition for Tomcat logging. By default, the console logs are configured as INFO mode. There are different levels of logging in Tomcat such as WARNING, INFORMATION, CONFIG, and FINE. The previous screenshot shows the Tomcat log file location, after the start of Tomcat services. The previous screenshot shows the output of the catalina.out file, where Tomcat services are started in 1903 ms. Access log Access logs are customized logs, which give information about the following: Who has accessed the application What components of the application are accessed Source IP and so on These logs play a vital role in traffic analysis of many applications to analyze the bandwidth requirement and also helps in troubleshooting the application under heavy load. These logs are configured in server.xml in TOMCAT_HOME/conf. The following screenshot shows the definition of access logs. You can customize them according to the environment and your auditing requirement. Let's discuss the pattern format of the access logs and understand how we can customize the logging format: <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log." suffix=".txt" pattern="%h %l %u %t &quot;%r&quot; %s %b" resolveHosts="false"/> Class Name: This parameter defines the class name used for generation of logs. By default, Apache Tomcat 7 uses the org.apache.catalina.valves.AccessLogValve class for access logs. Directory: This parameter defines the directory location for the log file. All the log files are generated in the log directory—TOMCAT_HOME/logs—but we can customize the log location based on our environment setup and then update the directory path in the definition of access logs. Prefix: This parameter defines the prefix of the access log filename, that is, by default, access log files are generated by the name localhost_access_log.yy-mm-dd.txt. Suffix: This parameter defines the file extension of the log file. Currently it is in .txt format. Pattern: This parameter defines the format of the log file. The pattern is a combination of values defined by the administrator, for example, %h = remote host address. The following screenshot shows the default log format for Tomcat 7. Access logs show the remote host address, date/time of request, method used for response, URI mapping, and HTTP status code. In case you have installed the web traffic analysis tool for application, then you have to change the access logs to a different format. Host manager These logs define the activity performed using Tomcat Manager, such as various tasks performed, status of application, deployment of application, and lifecycle of Tomcat. These configurations are done on the logging.properties, which can be found in TOMCAT_HOME/conf. The previous screenshot shows the definition of host, manager, and host-manager details. If you see the definitions, it defines the log location, log level, and prefix of the filename. In logging.properties, we are defining file handlers and appenders using JULI. The log file for manager looks similar to the following: I28 Jun, 2011 3:36:23 AM org.apache.catalina.core.ApplicationContext log INFO: HTMLManager: list: Listing contexts for virtual host 'localhost' 28 Jun, 2011 3:37:13 AM org.apache.catalina.core.ApplicationContext log INFO: HTMLManager: list: Listing contexts for virtual host 'localhost' 28 Jun, 2011 3:37:42 AM org.apache.catalina.core.ApplicationContext log INFO: HTMLManager: undeploy: Undeploying web application at '/sample' 28 Jun, 2011 3:37:43 AM org.apache.catalina.core.ApplicationContext log INFO: HTMLManager: list: Listing contexts for virtual host 'localhost' 28 Jun, 2011 3:42:59 AM org.apache.catalina.core.ApplicationContext log INFO: HTMLManager: list: Listing contexts for virtual host 'localhost' 28 Jun, 2011 3:43:01 AM org.apache.catalina.core.ApplicationContext log INFO: HTMLManager: list: Listing contexts for virtual host 'localhost' 28 Jun, 2011 3:53:44 AM org.apache.catalina.core.ApplicationContext log INFO: HTMLManager: list: Listing contexts for virtual host 'localhost' Types of log levels in Tomcat 7 There are seven levels defined for Tomcat logging services (JULI). They can be set based on the application requirement. The following figure shows the sequence of log levels for JULI: Every log level in JULI had its own functionality. The following table shows the functionality of each log level in JULI: Log level Description SEVERE(highest) Captures exception and Error WARNING Warning messages INFO Informational message, related to server activity CONFIG Configuration message FINE Detailed activity of server transaction (similar to debug) FINER More detailed logs than FINE FINEST(least) Entire flow of events (similar to trace) For example, let's take an appender from logging.properties and find out the log level used; the first log appender for localhost is using FINE as the log level, as shown in the following code snippet: localhost.org.apache.juli.FileHandler.level = FINE localhost.org.apache.juli.FileHandler.directory = ${catalina.base}/logs localhost.org.apache.juli.FileHandler.prefix = localhost. The following code shows the default file handler configuration for logging in Tomcat 7 using JULI. The properties are mentioned and log levels are highlighted: ############################################################ # Facility specific properties. # Provides extra control for each logger. ############################################################ org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level = INFO org.apache.catalina.core.ContainerBase.[Catalina].[localhost].handlers = 2localhost.org.apache.juli.FileHandler org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager] .level = INFO org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager] .handlers = 3manager.org.apache.juli.FileHandler org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/host- manager].level = INFO org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/host- manager].handlers = 4host-manager.org.apache.juli.FileHandler
Read more
  • 0
  • 0
  • 8999

article-image-creating-views-3-programmatically
Packt
21 Mar 2012
18 min read
Save for later

Creating Views 3 Programmatically

Packt
21 Mar 2012
18 min read
(For more resources on Drupal, see here.) Programming a view Creating a view with a module is a convenient way to have a predefined view available with Drupal. As long as the module is installed and enabled, the view will be there to be used. If you have never created a module in Drupal, or even never written a line of Drupal code, you will still be able to create a simple view using this recipe. Getting ready Creating a module involves the creation of the following two files at a minimum: An .info file that gives Drupal the information needed to add the module A .module file that contains the PHP script More complex modules will consist of more files, but those two are all we will need for now. How to do it... Carry out the following steps: Create a new directory named _custom inside your contributed modules directory (so, probably sites/all/modules/_custom). Create a subdirectory inside that directory; we will name it d7vr (Drupal 7 Views Recipes). Open a new file with your editor and add the following lines: ; $Id: name = Programmatic Views description = Provides supplementary resources such as programmatic views package = D7 Views Recipes version = "7.x-1.0" core = "7.x" php = 5.2 Save the file as d7vrpv.info. Open a new file with your editor and add the following lines: Feel free to download this code from the author's web site rather than typing it, at http://theaccidentalcoder.com/ content/drupal-7-views-cookbook <?php /** * Implements hook_views_api(). */ function d7vrpv_views_api() { return array( 'api' => 2, 'path' => drupal_get_path('module', 'd7vrpv'), ); } /** * Implements hook_views_default_views(). */ function d7vrpv_views_default_views() { return d7vrpv_list_all_nodes(); } /** * Begin view */ function d7vrpv_list_all_nodes() { /* * View 'list_all_nodes' */ $view = views_new_view(); $view->name = 'list_all_nodes'; $view->description = 'Provide a list of node titles, creation dates, owner and status'; $view->tag = ''; $view->view_php = ''; $view->base_table = 'node'; $view->is_cacheable = FALSE; $view->api_version = '3.0-alpha1'; $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ /* Display: Defaults */ $handler = $view->new_display('default', 'Defaults', 'default'); $handler->display->display_options['title'] = 'List All Nodes'; $handler->display->display_options['access']['type'] = 'role'; $handler->display->display_options['access']['role'] = array( '3' => '3', ); $handler->display->display_options['cache']['type'] = 'none'; $handler->display->display_options['exposed_form']['type'] = 'basic'; $handler->display->display_options['pager']['type'] = 'full'; $handler->display-> display_options['pager']['options']['items_per_page'] = '15'; $handler->display->display_options['pager']['options'] ['offset'] = '0'; $handler->display->display_options['pager']['options'] ['id'] = '0'; $handler->display->display_options['style_plugin'] = 'table'; $handler->display->display_options['style_options'] ['columns'] = array( 'title' => 'title', 'type' => 'type', 'created' => 'created', 'name' => 'name', 'status' => 'status', ); $handler->display->display_options['style_options'] ['default'] = 'created'; $handler->display->display_options['style_options'] ['info'] = array( 'title' => array( 'sortable' => 1, 'align' => 'views-align-left', 'separator' => '', ), 'type' => array( 'sortable' => 1, 'align' => 'views-align-left', 'separator' => '', ), 'created' => array( 'sortable' => 1, 'align' => 'views-align-left', 'separator' => '', ), 'name' => array( 'sortable' => 1, 'align' => 'views-align-left', 'separator' => '', ), 'status' => array( 'sortable' => 1, 'align' => 'views-align-left', 145 'separator' => '', ), ); $handler->display->display_options['style_options'] ['override'] = 1; $handler->display->display_options['style_options'] ['sticky'] = 0; $handler->display->display_options['style_options'] ['order'] = 'desc'; /* Header: Global: Text area */ $handler->display->display_options['header']['area'] ['id'] = 'area'; $handler->display->display_options['header']['area'] ['table'] = 'views'; $handler->display->display_options['header']['area'] ['field'] = 'area'; $handler->display->display_options['header']['area'] ['empty'] = TRUE; $handler->display->display_options['header']['area'] ['content'] = '<h2>Following is a list of all non-page nodes.</h2>'; $handler->display->display_options['header']['area'] ['format'] = '3'; /* Footer: Global: Text area */ $handler->display->display_options['footer']['area'] ['id'] = 'area'; $handler->display->display_options['footer']['area'] ['table'] = 'views'; $handler->display->display_options['footer']['area'] ['field'] = 'area'; $handler->display->display_options['footer']['area'] ['empty'] = TRUE; $handler->display->display_options['footer']['area'] ['content'] = '<small>This view is brought to you courtesy of the D7 Views Recipes module</small>'; $handler->display->display_options['footer']['area'] ['format'] = '3'; /* Field: Node: Title */ $handler->display->display_options['fields']['title'] ['id'] = 'title'; $handler->display->display_options['fields']['title'] ['table'] = 'node'; $handler->display->display_options['fields']['title'] ['field'] = 'title'; $handler->display-> display_options['fields']['title']['alter']['alter_text'] = 0; $handler->display-> display_options['fields']['title']['alter']['make_link'] = 0; $handler->display-> display_options['fields']['title']['alter']['trim'] = 0; $handler->display-> display_options['fields']['title']['alter'] ['word_boundary'] = 1; $handler->display-> display_options['fields']['title']['alter']['ellipsis'] = 1; $handler->display-> display_options['fields']['title']['alter']['strip_tags'] = 0; $handler->display-> display_options['fields']['title']['alter']['html'] = 0; $handler->display-> display_options['fields']['title']['hide_empty'] = 0; $handler->display-> display_options['fields']['title']['empty_zero'] = 0; $handler->display-> display_options['fields']['title']['link_to_node'] = 0; /* Field: Node: Type */ $handler->display->display_options['fields']['type'] ['id'] = 'type'; $handler->display->display_options['fields']['type'] ['table'] = 'node'; $handler->display->display_options['fields']['type'] ['field'] = 'type'; $handler->display-> display_options['fields']['type']['alter']['alter_text'] = 0; $handler->display-> display_options['fields']['type']['alter']['make_link'] = 0; $handler->display-> display_options['fields']['type']['alter']['trim'] = 0; $handler->display-> display_options['fields']['type']['alter'] ['word_boundary'] = 1; $handler->display-> display_options['fields']['type']['alter']['ellipsis'] = 1; $handler->display-> display_options['fields']['type']['alter']['strip_tags'] = 0; $handler->display-> display_options['fields']['type']['alter']['html'] = 0; $handler->display-> display_options['fields']['type']['hide_empty'] = 0; $handler->display-> display_options['fields']['type']['empty_zero'] = 0; $handler->display-> display_options['fields']['type']['link_to_node'] = 0; $handler->display-> display_options['fields']['type']['machine_name'] = 0; /* Field: Node: Post date */ $handler->display->display_options['fields']['created'] ['id'] = 'created'; $handler->display->display_options['fields']['created'] ['table'] = 'node'; $handler->display->display_options['fields']['created'] ['field'] = 'created'; $handler->display-> display_options['fields']['created']['alter'] ['alter_text'] = 0; $handler->display-> display_options['fields']['created']['alter'] ['make_link'] = 0; $handler->display-> display_options['fields']['created']['alter']['trim'] = 0; $handler->display-> display_options['fields']['created']['alter'] ['word_boundary'] = 1; $handler->display-> display_options['fields']['created']['alter']['ellipsis'] = 1; $handler->display-> display_options['fields']['created']['alter'] ['strip_tags'] = 0; $handler->display-> display_options['fields']['created']['alter']['html'] = 0; $handler->display-> display_options['fields']['created']['hide_empty'] = 0; $handler->display-> display_options['fields']['created']['empty_zero'] = 0; $handler->display-> display_options['fields']['created']['date_format'] = 'custom'; $handler->display-> display_options['fields']['created']['custom_date_format'] = 'Y-m-d'; /* Field: User: Name */ $handler->display->display_options['fields']['name'] ['id'] = 'name'; $handler->display->display_options['fields']['name'] ['table'] = 'users'; $handler->display->display_options['fields']['name'] ['field'] = 'name'; $handler->display->display_options['fields']['name'] ['label'] = 'Author'; $handler->display-> display_options['fields']['name']['alter']['alter_text'] = 0; $handler->display-> display_options['fields']['name']['alter']['make_link'] = 0; $handler->display-> display_options['fields']['name']['alter']['trim'] = 0; $handler->display-> display_options['fields']['name']['alter'] ['word_boundary'] = 1; $handler->display-> display_options['fields']['name']['alter']['ellipsis'] = 1; $handler->display-> display_options['fields']['name']['alter']['strip_tags'] = 0; $handler->display-> display_options['fields']['name']['alter']['html'] = 0; $handler->display-> display_options['fields']['name']['hide_empty'] = 0; $handler->display-> display_options['fields']['name']['empty_zero'] = 0; $handler->display-> display_options['fields']['name']['link_to_user'] = 0; $handler->display-> display_options['fields']['name']['overwrite_anonymous'] = 0; /* Field: Node: Published */ $handler->display->display_options['fields']['status'] ['id'] = 'status'; $handler->display->display_options['fields']['status'] ['table'] = 'node'; $handler->display->display_options['fields']['status'] ['field'] = 'status'; $handler->display-> display_options['fields']['status']['alter'] ['alter_text'] = 0; $handler->display-> display_options['fields']['status']['alter']['make_link'] = 0; $handler->display-> display_options['fields']['status']['alter']['trim'] = 0; $handler->display-> display_options['fields']['status']['alter'] ['word_boundary'] = 1; $handler->display-> display_options['fields']['status']['alter']['ellipsis'] = 1; $handler->display-> display_options['fields']['status']['alter'] ['strip_tags'] = 0; $handler->display-> display_options['fields']['status']['alter']['html'] = 0; $handler->display-> display_options['fields']['status']['hide_empty'] = 0; $handler->display-> display_options['fields']['status']['empty_zero'] = 0; $handler->display->display_options['fields']['status'] ['type'] = 'true-false'; $handler->display->display_options['fields']['status'] ['not'] = 0; /* Sort criterion: Node: Post date */ $handler->display->display_options['sorts']['created'] ['id'] = 'created'; $handler->display->display_options['sorts']['created'] ['table'] = 'node'; $handler->display->display_options['sorts']['created'] ['field'] = 'created'; $handler->display->display_options['sorts']['created'] ['order'] = 'DESC'; /* Filter: Node: Type */ $handler->display->display_options['filters']['type'] ['id'] = 'type'; $handler->display->display_options['filters']['type'] ['table'] = 'node'; $handler->display->display_options['filters']['type'] ['field'] = 'type'; $handler->display-> display_options['filters']['type']['operator'] = 'not in'; $handler->display->display_options['filters']['type'] ['value'] = array( 'page' => 'page', ); /* Display: Page */ $handler = $view->new_display('page', 'Page', 'page_1'); $handler->display->display_options['path'] = 'list-all-nodes'; $views[$view->name] = $view; return $views; } ?>   Save the file as d7vrpv.module. Navigate to the modules admin page at admin/modules. Scroll down to the new module and activate it, as shown in the following screenshot: Navigate to the Views Admin page (admin/structure/views) to verify that the view appears in the list: Finally, navigate to list-all-nodes to see the view, as shown in the following screenshot: How it works... The module we have just created could have many other features associated with it, beyond simply a view, and enabling the module will make those features and the view available, while disabling it will hide those same features and view. When compiling the list of installed modules, Drupal looks first in its own modules directory for .info files, and then in the site's modules directories. As can be deduced from the fact that we put our .info file in a second-level directory of sites/all/modules and it was found there, Drupal will traverse the modules directory tree looking for .info files. We created a .info file that provided Drupal with the name and description of our module, its version, the version of Drupal it is meant to work with, and a list of files used by the module, in our case just one. We saved the .info file as d7vrpv.info (Drupal 7 Views Recipes programmatic view); the name of the directory in which the module files appear (d7vr) has no bearing on the module itself. The module file contains the code that will be executed, at least initially. Drupal does not "call" the module code in an active way. Instead, there are events that occur during Drupal's creation of a page, and modules can elect to register with Drupal to be notifi ed of such events when they occur, so that the module can provide the code to be executed at that time; for example, you registering with a business to receive an e-mail in the event of a sale. Just like you are free to act or not, but the sales go on regardless, so too Drupal continues whether or not the module decides to do something when given the chance. Our module 'hooks' the views_api and views_default_views events in order to establish the fact that we do have a view to offer. The latter hook instructs the Views module which function in our code executes our view: d7vrpv_list_all_nodes(). The first thing it does is create a view object by calling a function provided by the Views module. Having instantiated the new object, we then proceed to provide the information it needs, such as the name of the view, its description, and all the information that we would have selected through the Views UI had we used it. As we are specifying the view options in the code, we need to provide the information that is needed by each handler of the view functionality. The net effect of the code is that when we have cleared cache and enabled our module, Drupal then includes it in its list of modules to poll during events. When we navigate to the Views Admin page, an event occurs in which any module wishing to include a view in the list on the admin screen does so, including ours. One of the things our module does is defi ne a path for the page display of our view, which is then used to establish a callback. When that path, list-all-nodes, is requested, it results in the function in our module being invoked, which in turn provides all the information necessary for our view to be rendered and presented. There's more The details of the code provided to each handler are outside the scope of this book, but you don't really need to understand it all in order to use it. You can enable the Views Bulk Export module (it comes with Views), create a view using the Views UI in admin, and choose to Bulk Export it. Give the exporter the name of your new module and it will create a file and populate it with nearly all the code necessary for you. Handling a view field As you may have noticed in the preceding code that you typed or pasted, Views makes tremendous use of handlers. What is a handler? It is simply a script that performs a special task on one or more elements. Think of a house being built. The person who comes in to tape, mud, and sand the wallboard is a handler. In Views, one type of handler is the field handler, which handles any number of things, from providing settings options in the field configuration dialog, to facilitating the field being retrieved from the database if it is not part of the primary record, to rendering the data. We will create a field handler in this recipe that will add to the display of a zip code a string showing how many other nodes have the same zip code, and we will add some formatting options to it in the next recipe. Getting ready A handler lives inside a module, so we will create one: Create a directory in your contributed modules path for this module. Open a new text file in your editor and paste the following code into it: ; $Id: name = Zip Code Handler description = Provides a view handler to format a field as a zip code package = D7 Views Recipes ; Handler files[] = d7vrzch_handler_field_zip_code.inc files[] = d7vrzch_views.inc version = "7.x-1.0" core = "7.x" php = 5.2 Save the file as d7vrzch.info. Create another text file and paste the following code into it: <?php /** * Implements hook_views_data_alter() */ function d7vrzch_field_views_data_alter(&$data, $field) { if (array_key_exists('field_data_field_zip_code', $data)) { $data['field_data_field_zip_code']['field_zip_code'] ['field']['handler'] = 'd7vrzch_handler_field_zip_code'; } } Save the file as d7vrzch.views.inc. Create another text file and paste the following into it: <?php /** * Implements hook_views_api(). */ function d7vrzch_views_api() { return array( 'api' => 3, 'path' => drupal_get_path('module', 'd7vrzch'), ); } Save the file as d7vrzch.module. How to do it... Carry out the folowing steps: Create another text file and paste the following into it: <?php // $Id: $ /** * Field handler to format a zip code. * * @ingroup views_field_handlers */ class d7vrzch_handler_field_zip_code extends views_handler_field_field { function option_definition() { $options = parent::option_definition(); $options['display_zip_totals'] = array( 'contains' => array( 'display_zip_totals' => array('default' => FALSE), ) ); return $options; } /** * Provide a link to the page being visited. */ function options_form(&$form, &$form_state) { parent::options_form($form, $form_state); $form['display_zip_totals'] = array( '#title' => t('Display Zip total'), '#description' => t('Appends in parentheses the number of nodes containing the same zip code'), '#type' => 'checkbox', '#default_value' => !empty($this-> options['display_zip_totals']), ); } function pre_render(&$values) { if (isset($this->view->build_info['summary']) || empty($values)) { return parent::pre_render($values); } static $entity_type_map; if (!empty($values)) { // Cache the entity type map for repeat usage. if (empty($entity_type_map)) { $entity_type_map = db_query('SELECT etid, type FROM {field_config_entity_type}')->fetchAllKeyed(); } // Create an array mapping the Views values to their object types. $objects_by_type = array(); foreach ($values as $key => $object) { // Derive the entity type. For some field types, etid might be empty. if (isset($object->{$this->aliases['etid']}) && isset($entity_type_map[$object->{$this-> aliases['etid']}])) { $entity_type = $entity_type_map[$object->{$this-> aliases['etid']}]; $entity_id = $object->{$this->field_alias}; $objects_by_type[$entity_type][$key] = $entity_id; } } // Load the objects. foreach ($objects_by_type as $entity_type => $oids) { $objects = entity_load($entity_type, $oids); foreach ($oids as $key => $entity_id) { $values[$key]->_field_cache[$this->field_alias] = array( 'entity_type' => $entity_type, 'object' => $objects[$entity_id], ); } } } } function render($values) { $value = $values->_field_cache[$this->field_alias] ['object']->{$this->definition['field_name']} ['und'][0]['safe_value']; $newvalue = $value; if (!empty($this->options['display_zip_totals'])) { $result = db_query("SELECT count(*) AS recs FROM {field_data_field_zip_code} WHERE field_zip_code_value = :zip",array(':zip' => $value)); foreach ($result as $item) { $newvalue .= ' (' . $item->recs . ')'; } } return $newvalue; } Save the file as d7vrzch_handler_field_zip_code.inc. Navigate to admin/build/modules and enable the new module, which shows as the Zip Code Handler. We will test the handler in a quick view. Navigate to admin/build/views. Click on the +Add new view link , enter test as the View name, check the box for description and enter Zip code handler test; clear the Create a page checkbox , and click on the Continue & edit button . On the Views edit page, click on the add link in the Filter Criteria pane, check the box next to Content: Type, and click on the Add and configure filter criteria button . In the Content: Type configuration box , select Home and click on the Apply button . Click on the add link next to Fields, check the box next to Content: Zip code, and click on the Add and configure fields button. Check the box at the bottom of the Content: Zip code configuration box titled Display Zip total and click on the Apply button. Click on the Save button and see the result of our custom handler in the Live preview: How it works... The Views field handler is simply a set of functions that provide support for populating and formatting a field for Views, much in the way a printer driver does for the operating system. We created a module in which our handler resides, and whenever that field is requested within a view, our handler will be invoked. We also added a display option to the configuration options for our field, which when selected, takes each zip code value to be displayed, determines how many nodes have the same zip code, and appends the parenthesized total to the output. The three functions, two in the views.inc file and one in the module file, are very important. Their result is that our custom handler file will be used for field_zip_code instead of the default handler used for entity text fields. In the next recipe, we will add zip code formatting options to our custom handler.
Read more
  • 0
  • 0
  • 15228

article-image-getting-started-gamesalad
Packt
20 Mar 2012
10 min read
Save for later

Getting Started with GameSalad

Packt
20 Mar 2012
10 min read
Let's get to it shall we?   System requirements In order for you to run GameSalad and create amazingly awesome games, you must meet the minimum system requirements, which are as follows:   Intel Mac (Any Mac from 2006 and above) Mac OS X 10.6 or higher At least 1GB RAM A device running iOS (iPad, iPhone 3G and up, or iPod Touch) If your computer exceeds these requirements, perfect! If not, you will need to upgrade your computer. Keep in mind, these are the minimum requirements, having a computer with better specs is recommended.   Let's get into GameSalad Let's start by downloading GameSalad and registering for an account. Let's go to GameSalad's website, www.gamesalad.com. Click the "Download Free App – GameSalad Creator" button.   While you are waiting for GameSalad to download, you should sign up for a free account. At the top of the page click Sign Up, enter your email address and create a username and password. You have two options for GameSalad membership, you can keep the Basic Pricing, which is completely free or select Professional Pricing. The difference is when you publish your App, you will have a Created with GameSalad splash screen, not a big deal right? Especially, not when you can get this awesome program for free! The Professional Pricing, which is $499 (USD) per year gives you all the features of the free version of GameSalad, plus it allows you to use iAds, Game Center, Promotional Links, your own Custom Splash Screen, and Priority Technical Support.   This does not include your Apple developer cost, which is $99 a year Other tools that are recommended for game development:   Adobe Photoshop (http://www.adobe.com/products/photoshop.html) or a free equivalent, Inkscape, Gimp, and Pixelmator Drawing Tablet (Makes creating sprites much easier but not required) Getting familiar with GameSalad's interface Once you open GameSalad, you are presented with several options on the screen.   Following are the options:   Home: It shows you the latest GameSalad links (Success stories, their latest game release, and so on...). News: It is self-explanatory, this shows you the latest update notes, and what is new in the GS community. Start: The getting started screen, here you have video tutorials, Wiki Docs, Blog, and more. Profile: This shows you, your GameSalad's profile page, messages, followers, and likes. New: These are all your new projects, Blank templates, and various bare bone templates to get you started. Recent: This shows you all of your recently saved projects. Portfolio: This shows all your published Apps through GameSalad.   Back/Forward buttons: Used when navigating back and forth between windows Web Preview: Allows you to see what your game will look like within the browser (HTML5) Home: This takes you right back to the project's main window Publish: Brings up the Publish window, here you can chose to deploy your game to the web, iPhone, iPad, Mac, or Android Scenes: Gives you a drop-down menu of all your scenes Feedback: Have some thoughts about GameSalad? Click this to send them to the Creators! Preview: At the main menu, or while editing an actor this starts your game from the beginning. If you are in a level, it will preview the level Help: Brings up the GameSalad documentation, which lists many help topics. Target Platform and Orientation: This drop-down menu gives you, your device options, iPhone Landscape, iPhone Portrait, GameSalad.com, iPad Landscape, iPad Portrait, and 720p HD Enable Resolution Independence (only when iPhone and iPad device is set): Check this option if you are creating a game specifically for the iPhone 4, 4S, iPad, or Kindles and Nooks. This takes your high resolution images and converts them for iPhone 3GS, 3G, and iPhone (1st Gen) Scenes Tab: Switch to this to see all your wonderful levels! Actors Tab: Select this tab to see all your actors in the game project. From this tab, you can group different types of actors, such as platforms and enemies. This comes in handy when an actor has to collide with numerous other actors (enemies or platforms) + button: Adds a Level - button (when a level is selected): Deletes a level Inspector (with Game selected) Actors: Here, you will see all your in-game items (Players, platforms, collectables, and so on) Attributes: Here, you can edit all the attributes of the game such as the display size. Devices: Here, you can edit all the settings for the mouse, touch screen, accelerometer, screen, and audio. Inspector (with Scene selected) o Attributes: Here, you can edit all the attributes of the current level, such as the size of the level, screen wrap (X,Y), Gravity, background color, camera settings, and autorotate. o Layers: Here, you can create numerous layers with scrollable on or off. For example, a layer called UI with scrollable deselected will have all your user interface items, and they will stay on the screen. Library (with Behaviors selected) o Standard: These are all the standard GameSalad behaviors (Movements, change actor attributes, and more) o Custom: These are your own custom behaviors. Let's say, you needed the same behavior throughout numerous actors but you didn't want to keep re-adding and changing the behavior for each actor. Once, you create the Behavior, drag it into this box and you can use it as much as you want. o Pro: These are all the professional behaviors (only available when you have paid for the professional membership). These include Game Center Connect, iAd, and Open URL Library (with Images selected) Project: This shows all your imported images into this project. Purchased: This is a new feature that shows the images you have purchased through GameSalad's Marketplace. (When you click Purchase Images..., this will take you to the GameSalad Marketplace where you will have a plethora of Content packs and more to purchase and import into your game) When you click the "+" button, you can import images from your hard drive, alternately, you can drag them directly into the Library from the Finder Library (with Sounds selected): This shows you all of your sound effects and music that you have imported into your project. As with images, when you click the "+" button you can import sound effects or music from your hard drive, or drag them directly in from the Finder. Actor Mode: This involves normal mouse functions; it allows you to select actors within the level. Following is the screenshot of the icon: Camera Mode: It allows you to edit the camera, position, and scrolling hot spots for characters that control the camera. Following is the screenshot of the icon: Reset Scene: While previewing your level and if this button is pressed, everything will go back to its initial state. Following is the screenshot of the icon: Play: This will start a preview of the current level. This is different from the green Project Preview button, as this will only preview the current level, and not the whole project. When you complete the level, an alert will appear telling you the scene has ended, and you can either select to preview the next level, or reset the current scene. Following is the screebshot of the icon: Show Initial State: If you have run a preview, and want to see the initial state without ending the preview, then pause the preview, click on the following icon and the initial state is seen. Following is the screenshot of the icon: For now, let's click New | My Great Project This is a fresh project; everything is empty. You can see that you have one level so far, but you can add more at a later time. See the Scenes and Actors Tabs? Currently, Scenes is selected, this shows you all of your levels, but if you click the Actors tab, you will be able to see all your actors (or game objects, characters, collectables, and so on.) in the game. You can also rearrange all of the actors in Actor Tags, to give you an idea of what these are useful for. Take for example, if you have 30 different enemies, when you are setting up your collisions within behaviors, you won't have to set up 30 different collisions. Rather, when you set up all the enemies within a tag named Enemies you can do a single collision behavior for all actors of the tag! This reduces a lot of time when coding. We will get into more detail about actor tags, when we get into creating some games later in the book. If you double-click on the Initial Scene, you will be taken to the level editor. Before we do that, let's go through the buttons shown in the following screenshot: The descriptions of the buttons in the previous screenshot are as as follows: Seems pretty easy, right? It is! GameSalad's user interface is simple. Even if you don't know what a certain button does, just hover your mouse over the button and a tooltip appears and tells you what the button does. Even though it's a very simple user interface, it is very powerful. Take for example, something as simple as the Enable Resolution Independence option. Simply selecting this takes out a lot of time from having to create two sets of images, a high resolution retina-friendly image, and a lower quality set for non-retina display images. With this option, all you have to do is create a high resolution set. Choose this option and GameSalad automatically creates a lower quality set of images for non-retina devices. How great is that? Such a simple option and yet it saves so much time and effort, and isn't simplicity what everyone wants? Now let's get into the scene editor Double-click our initial scene and you will see the Scene Editor, yes it may be a little daunting, but once you get used to the user interface, it is really quite simple. Let's break down all the buttons and see what they do: What do all these buttons mean? Following is a description of all the buttons and boxes: There we go! The GameSalad interface really is that easy to navigate! In this article, you set up an account with GameSalad, you downloaded and installed it and now you know how to use the interface. GameSalad has such a simple interface, but it is really powerful. As we looked at earlier, an option as simple as Resolution Independence is so easy to select and yet one click takes off so much time from creating different sets of images that can be used for developing. This is what makes GameSalad so great; it's such a simple user interface and yet it is so powerful. What is so amazing about all of it, is that there's no programming involved whatsoever! For those who don't have the smartness to program a full game, this is what everyone else wants, simple, quick, and super powerful.
Read more
  • 0
  • 0
  • 14885

article-image-tabula-rasa-nurturing-your-site-tablets
Packt
09 Mar 2012
16 min read
Save for later

Tabula Rasa: Nurturing your Site for Tablets

Packt
09 Mar 2012
16 min read
The human touch There's a reason touchscreen interfaces were rarely used before Apple re-invented them in the iPhone. It's because programming them is very difficult. With a mouse-driven interface you have a single point of contact: the mouse's pointer. With a touchscreen, you potentially have ten points of contact, each one with a separate motion. And you also have to deal with limiting spurious input when the user accidentally touches the tablet when they didn't mean to. Does the user's swipe downward mean they want to scroll the page or to drag a single page element? The questions go on to infinity. With this article, we stand on the shoulders of those giants who have done the heavy lifting and given us a JavaScript interface that registers touch and gestures for use in our web pages. Many Bothans died to bring us this information. To understand the tablet is to understand the touch interface, and in order to understand the touch interface, we need to learn how touch events differ from mouse events. But that begs the question: what is an event? The event-driven model Many developers use JavaScript-based events and have not even the slightest clue as to what they can do or their power. In addition, many developers get into situations where they don't know why their events are misfiring or, worse yet, bubbling to other event handlers and causing a cascade of event activity. As you may or may not know, an HTML document is made up of a series of tags organized in a hierarchical structure called the HTML document. In JavaScript, this document is referred to through the reserved word document. Simple enough, right? Well, what if I want to interact with the tag inside of a document, and not the document as a whole? Well, for that we need a way of addressing nested items inside the main <html> tag. For that, we use the Document Object Model (DOM). DOM is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML, and XML documents. Aspects of the DOM (such as its elements) may be addressed and manipulated within the syntax of the programming language in use. The public interface of a DOM is specified in its Application Programming Interface (API). For more details on DOM, refer to the Wikipedia document at: http://en.wikipedia.org/wiki/Document_Object_Model. The body of that document then becomes document.body. The head of the document, likewise, becomes document.head. Now, what happens when your mouse interacts with this web page? This is said to be a DOM event. When you click, the elements that are the receivers of that action are said to propagate the event through the DOM. In the early days, Microsoft and Netscape/Firefox had competing ways of handling those events. But they finally gave way to the modern W3C's standard, which unifies the two ways and, even more importantly, jQuery has done a lot to standardize the way we think about events and event handling. In most browsers today, mouse events are pretty standardized, as we are now more than 20 years into the mouse-enabled computing era: For tablets and touchscreen phones, obviously, there is no mouse. There are only your fingers to serve the purpose of the mouse. And here's where things get simultaneously complicated as well as simple. Touch and go Much of what we talk about as touch interaction is made up of two distinct types of touches—single touches and gestures. A single touch is exactly that. One finger placed on the screen from the start till the end. A gesture is defined as one or more fingers touching the surface of the area and accompanied by a specific motion: Touch + Motion. To open most tablets, you swipe your finger across a specific area. To scroll inside a div element, you use two fingers pushing up and down. In fact, scrolling itself is a gesture and tablets only respond to the scroll event once it's over. We will cover more on that later. Gestures have redefined user interaction. I wonder how long it took for someone to figure out that the zoom in and zoom out is best accomplished with a pinch of the fingers? It seems so obvious once you do it and it immediately becomes second nature. My mom was pinching to zoom on her iPhone within the first 5 minutes of owning it. Touch events are very similar to multiple mouse events without a hover state. There is no response from the device when a finger is over the device but has not pressed down. There is an effort on the part of many mobile OS makers to simulate the hover event by allowing the hover event to trigger with the first click, and the click event to trigger with the second click on the same object. I would advise against using it for any meaningful user interaction as it is inconsistently implemented, and many times the single click triggers the link as well as the hover-reveal in drop-down menus. Not using the hover event to guide users through navigation changes the way we interact with a web page. Much of the work we've done to guide users through our pages is based on the hover-response event model to clue users in on where links are. We have to get beyond that. Drop-down menus quickly become frustrating at the second and third levels, especially if the click and hover events were incorrectly implemented in the desktop browser. Forward and back buttons are rendered obsolete by a forward and backwards swipe gesture. The main event There are basically three touch events—touchstart, touchmove, and touchend. Gesture events are, likewise: gesturestart, gesturemove, and gestureend. All gestures register a touch event but not all touch events register gestures. Gestures are registered when multiple fingers make contact with the touch surface and register significant location change in a concerted effort, such as two or more fingers swiping, a pinch action, and so on. In general, I've found it a good practice to use touch events to register finger actions; but it is required to return null on a touch event when there are multiple fingers involved and to handle such events with gestures. jQuery mobile has a nice suite of touch events built into its core that we can hook into. But jQuery and jQuery mobile sometimes fall short of the interaction we want to have for our users, so we'll outline best practices for adding customized user touch events to both the full and mobile version of the demo site. Let's get started… Time for action – adding a swipe advance to the home page The JavaScript to handle touch events is a little tricky; so, pay attention: Add the following lines to both sites/all/themes/dpk/js/global.js and sites/all/themes/dpk_mobile/js/global.js: Drupal.settings.isTouchDevice = function() { return "ontouchstart" in window; } if (Drupal.settings.isTouchDevice() ) { Drupal.behaviors.jQueryMobileSlideShowTouchAdvance = { attach: function(context, settings) { self = Drupal.behaviors.jQueryMobileSlideShowTouchAdvance; jQuery.each(jQuery(".views_slideshow_cycle_main. viewsSlideshowCycle-processed"), function(idx, value) { value.addEventListener("touchstart", self. handleTouchStart); jQuery(value).addClass("views-slideshow-mobileprocessed"); }) jQuery(self).bind("swipe", self.handleSwipe); }, detach: function() { }, original: { x: 0, y: 0}, changed: { x: 0, y: 0}, direction: { x: "", y: "" }, fired: false,handleTouchStart: function(evt) { self = Drupal.behaviors.jQueryMobileSlideShowTouchAdvance; if (evt.touches) { if (evt.targetTouches.length != 1) { return false; } if (evt.touches.length) { evt.preventDefault(); evt. stopPropagation() } self.original = { x: evt.touches[0].clientX, y: evt. touches[0].clientY } self.target = jQuery(this).attr("id").replace("views_ slideshow_cycle_main_", ""); Drupal.viewsSlideshow.action({ "action": "pause", "slideshowID": self.target }); evt.target.addEventListener("touchmove", self. handleTouchMove); evt.target.addEventListener("touchend", self. handleTouchEnd); } }, handleTouchMove: function(evt) { self = Drupal.behaviors.jQueryMobileSlideShowTouchAdvance; self.changed = { x: (evt.touches.length) ? evt.touches[0].clientX: evt.changedTouches[0].clientX, y: (evt.touches.length) ? evt.touches[0].clientY: evt.changedTouches[0].clientY }; h = parseInt(self.original.x - self.changed.x), v = parseInt(self.original.y - self.changed.y); if (h !== 0) { self.direction.x = (h < 0) ? "right":"left"; } if (v !== 0) { self.direction.y = (v < 0) ? "up": "down"; } jQuery(self).trigger("swipe"); }, handleTouchEnd: function(evt) { self = Drupal.behaviors.jQueryMobileSlideShowTouchAdvance; evt.target.removeEventListener("touchmove", self. handleTouchMove); evt.target.removeEventListener("touchend", self. handleTouchEnd); self.fired = false; }, handleSwipe: function(evt) { self = Drupal.behaviors.jQueryMobileSlideShowTouchAdvance; if (evt != undefined && self.fired == false) { Drupal.viewsSlideshow.action({ "action": (self.direction.x == "left")?"nextSlide":"previousSlide", "slideshowID": self.target}); self.fired = true; //only fire advance once per touch } } } } Clear Drupal's cache by either navigating to Configuration | Performance and clicking on the Clear cache button or entering these lines in a terminal: cd ~/sites/dpk/drush cc all Navigate to either home page with a touch-enabled device and you should be able to advance the home page slideshow with your fingers. What just happened? Let's take a look at how this code works. First, we have a function, isTouchDevice. This function returns true/false values if touch events are enabled on the browser. We use an if statement to wall off the touchscreen code, so browsers that aren't capable don't register an error. The Drupal behavior jQueryMobileSlideShowTouchAdvance has the attach and detach functions to satisfy the Drupal behavior API. In each function, we locally assign the self variable with the value of the entire object. We'll use this in place of the this keyword. In the Drupal behavior object, this can sometimes ambiguously refer to the entire object, or to the current sub-object. In this case, we want the reference to be to just the sub-object so we assign it to self. The attach function grabs all slideshow_cycle div elements in a jQuery each loop. The iteration of the loop adds an event listener to the div tag. It's important to note that the event listener is not bound with jQuery event binding. jQuery event binding does not yet support touch events. There's an effort to add them, but they are not in the general release that is used with Drupal 7. We must then add them with the browser native function, AddEventListener. We use the handleTouchStart method to respond to the touchstart event. We will add touchend and touchmove events after the touchstart is triggered.The other event that we're adding listens to this object for the swipe event. This is a custom event we will create that will be triggered when a swipe action happens. We will cover more on that shortly.The detach function is used to add cleanup to items when they are removed from the DOM. Currently, we have no interaction that removes items from the DOM and therefore no cleanup that's necessary for that removal to take place.Next, we add some defaults—original, changed, direction, and fired. We'll use those properties in our event response methods.HandleTouchStart event is fired when the finger first touches the surface. We make sure the evt.touches object has value and is only one touch. We want to disregard touches that are gestures. Also, we use preventDefault and stopPropagation on the event to keep it from bubbling up to other items in the DOM. self.original is the variable that will hold the touch's original coordinates. We store the values for touch[0]. We also name the target by getting the DOM ID of the cycle containing the div element. We can use string transforms on that ID to obtain the ID of the jQuery cycle being touched and will use that value when we send messages to the slideshow, based on the touch actions, like we do in the next line. We tell the slideshow to pause normal activity while we figure out what the user wants. To figure that out, we add touchmove and touchend events listening to the div element. handleTouchMove figures out the changed touch value. It does so by looking at the ClientX and ClientY values in the touch event.Some browsers support the changedTouches value which will do some calculations on how much the touch has changed since the last event was triggered. If it's available, we use it, or we use the value of the X and Y coordinates in the touch event's touches array. We do some subtraction against the original touch to find out how much the touch has changed and in what direction. We use self.direction to store the direction of the change. We store the direction in and tell the world that a swipe has begun on our div element by triggering a custom event on our self object.If you remember correctly, we used the handleSwipe method to respond to the swipe event. In handleSwipe we make sure the event has not already fired. If it hasn't, we use that swipe event to trigger a next or previous action on our jQuery cycle slideshow. Once we've fired the event, we change the self.fired to true so it will only fire once per touch. In the touchend responder, HandleTouchEnd, we remove both the touchmove and touchend responders and reset the fired state.But adding the touch events to both the desktop and the mobile themes begs the question, "Into which category does the table fall?" Have a go hero – adding a swipe gesture Add a swipe gesture event to the Menu Item page that allows you to scroll through menu items. The changing landscape (or portrait) Responsive web design is a design discipline that believes that the same markup should be used for both desktop and mobile screens, with the browser managing the display of items, rather than the user choosing an experience. If the screen is smaller, the layout adjusts and content emphasis remains.Conversely, the popularity of Internet-connected game consoles and DVI ports on large screen televisions gives us yet another paradigm for web pages—the large screen. I sit in front of a 72" TV screen and connect it to either my laptop or iPad and I have a browsing experience that is more passive, but completely immersive.Right now, I bet you're thinking, "So which is it Mr Author, two sites or one?" Well, both, actually. In some cases, with some interactions it will be necessary to do two site themes and maintain them both. In some cases, when you can start from scratch, you can do a design that can work on every browser screen size. Let's start over and put responsive design principals to work with what we already know about media queries and touch interfaces. "Starting over" or "Everything you know about designing websites is wrong" Responsive web design forces the designer to start over—to forget the artificial limitations of the size that print imposes and to start with a blank canvas. Once that blank canvas is in place, though, how do you fill it? How do you create "The One True Design" (cue the theme music)?This book is not a treatise on how to create the perfect design. For that, I can recommend A Book Apart and anything published by smashingmagazine.com. Currently, they are at the forefront of this movement and regularly publish ideas and information that is helpful without too much technical jargon.No, this book is more about giving you strategies to implement the designs you're given or that you create using Drupal. In point of fact, responsive design, at the time of writing, is in its infancy and will change significantly over the next 10 years, as new technology forces us to rethink our assumptions about what books, television, and movies are and what the Web is.So suffice to say, it begins with content. Prioritizing content is the job of the designer. Items you want the user to perceive first, second, and third are the organizing structure of your responsive design makeover. In most instances, it's helpful to present the web developer with four views of the website. Wire framing made easy Start with wireframes. A great wire framing tool is called Balsamiq. It has a purposefully "rough" look to all of the elements you use. That way, it makes you focus on the elements and leave the design for a later stage. It's also helpful for focusing clients on the elements. Many times the stake holders see a mockup and immediately begin the discussion of "I like blue but I don't like green/I like this font, but don't like that one." It can be difficult to move the stake holders out of this mindset, but presenting them with black-and-white chalk-style drawings of website elements can, in many cases, be helpful. Balsamiq is a great tool for doing just that: These were created with Balsamiq but could have been created in almost any primitive drawing program. There are many free ones as well as the more specialized pay ones. A simple layout like this is very easy to plan and implement. But very few of the websites you develop will ever be this simple. Let's take for instance that the menu item we have not, as yet, implemented, is for online ordering. How does that work? What do those screens look like? At this point we have a Menu page but, as per this mockup, that menu page will become the online ordering section. How do we move these menu items we created to a place where they can be put in an order and paid for? And more importantly, how does each location know what was ordered from their location?These are questions that come up in the mockup and requirements phase and whether you are building the site yourself or being given requirements from a superior, or a client, you now have a better idea of the challenges you will face implementing the single design for this site. With that, we've been given these mockups for the new online ordering system. The following mockup diagram is for adding an order: The following mockup diagram is for placing an order: We'll implement these mockups using the Drupal 7 Commerce module. The Commerce module is just a series of customized data entities and views that we can use as the building blocks of our commerce portion. We'll theme the views in the standard Drupal way but with an eye to multi-width screens, lack of hover state, and keeping in mind "hit zones" with fingers on small mobile devices. We'll also add some location awareness to assist with the delivery process. Once an order is placed, an e-mail will need to be sent to the correct franchise notifying them of the pizza order and initiating the process of getting it out the door.
Read more
  • 0
  • 0
  • 3736
article-image-silverlight-5-lob-development-validation-advanced-topics-and-mvvm
Packt
09 Mar 2012
8 min read
Save for later

Silverlight 5 LOB Development : Validation, Advanced Topics, and MVVM

Packt
09 Mar 2012
8 min read
(For more resources on Silverlight, see here.) Validation One of the most important parts of the Silverlight application is the correct implementation of validations in our business logic. These can be simple details, such as the fact that the client must provide their name and e-mail address to sign up, or that before selling a book, it must be in stock. In RIA Services, validations can be defined on two levels: In entities, via DataAnnotations. In our Domain Service, server or asynchronous validations via Invoke. DataAnnotations The space named System.ComponentModel.DataAnnotations implements a series of attributes allowing us to add validation rules to the properties of our entities. The following table shows the most outstanding ones: Validation Attribute Description DataTypeAttribute Specifies a particular type of data such as date or an e-mail EnumDataTypeAttribute Ensures that the value exists in an enumeration RangeAttribute Designates minimum and maximum constraints RegularExpressionAttribute Uses a regular expression to determine valid values RequiredAttribute Specifies that a value must be provided StringLengthAttribute Designates a maximum and minimum number of characters CustomValidationAttribute Uses a custom method for validation The following code shows us how to add a field as "required": [Required()]public string Name{ get { return this._name; } set { (...) }} In the UI layer, the control linked to this field (a TextBox, in this case), automatically detects and displays the error. It can be customized as follows: These validations are based on the launch of exceptions. They are captured by user controls and bound to data elements. If there are errors, these are shown in a friendly way. When executing the application in debug mode with Visual Studio, it is possible to find that IDE captures exceptions. To avoid this, refer to the following link, where the IDE configuration is explained: http://bit.ly/riNdmp. Where can validations be added? The answer is in the metadata definition, entities, in our Domain Service, within the server project. Going back to our example, the server project is SimpleDB.Web and the Domain Service is MyDomainService. medatada.cs. These validations are automatically copied to the entities definition file and the context found on the client side. In the Simple.DB.Web.g.cs file, when the hidden folder Generated Code is opened, you will be surprised to find that some validations are already implemented. For example, the required field, field length, and so on. These are inferred from the Entity Framework model. Simple validations For validations that are already generated, let's see a simple example on how to implement those of the "required" field and "maximum length": [Required()][StringLength(60)]public string Name{ get { return this._name; } set { (...) }} Now, we will implement the syntactic validation for credit cards (format dddddddd- dddd-dddd). To do so, use the regular expression validator and add the server file MyDomainService.metadata.cs, as shown in the following code: [RegularExpression(@"d{4}-d{4}-d{4}-d{4}",ErrorMessage="Credit card not valid format should be: 9999-9999-9999-9999")]public string CreditCard { get; set; } To know how regular expressions work, refer to the following link: http://bit.ly/115Td0 and refer to this free tool to try them in a quick way: http://bit.ly/1ZcGFC. Custom and shared validations Basic validations are acceptable for 70 percent of validation scenarios, but there are still 30 percent of validations which do not fit in these patterns. What do you do then? RIA Services offers CustomValidatorAttribute. It permits the creation of a method which makes a validation defined by the developer. The benefits are listed below: Its code: The necessary logic can be implemented to make validations. It can be oriented for validations to be viable in other modules (for instance, the validation of an IBAN [International Bank Account]). It can be chosen if a validation is executed on only the server side (for example, a validation requiring data base readings) or if it is also copied to the client. To validate the checksum of the CreditCard field, follow these steps: Add to the SimpleDB.Web project, the class named ClientCustomValidation. Within this class, define a static model, ValidationResult, which accepts the value of the field to evaluate as a parameter and returns the validation result. public class ClientCustomValidation{ public static ValidationResult ValidMasterCard(string strcardNumber)} Implement the summarized validation method (the part related to the result call back is returned). public static ValidationResult ValidMasterCard(string strcardNumber){ // Let us remove the "-" separator string cardNumber = strcardNumber.Replace("-", ""); // We need to keep track of the entity fields that are // affected, so the UI controls that have this property / bound can display the error message when applies List<string> AffectedMembers = new List<string>(); AffectedMembers.Add("CreditCard"); (...) // Validation succeeded returns success // Validation failed provides error message and indicates // the entity fields that are affected return (sum % 10 == 0) ? ValidationResult.Success : new ValidationResult("Failed to validate", AffectedMembers);} To make validation simpler, only the MasterCard has been covered. To know more and cover more card types, refer to the page http://bit.ly/aYx39u. In order to find examples of valid numbers, go to http://bit.ly/gZpBj. Go to the file MyDomainService.metadata.cs and, in the Client entity, add the following to the CreditCard field: [CustomValidation(typeof(ClientCustomValidation),"ValidMasterCard")]public string CreditCard { get; set; } If it is executed now and you try to enter an invalid field in the CreditCard field, it won't be marked as an error. What happens? Validation is only executed on the server side. If it is intended to be executed on the client side as well, rename the file called ClientCustomValidation.cs to ClientCustomValidation.shared. cs. In this way, the validation will be copied to the Generated_code folder and the validation will be launched. In the code generated on the client side, the entity validation is associated. /// <summary>/// Gets or sets the 'CreditCard' value./// </summary>[CustomValidation(typeof(ClientCustomValidation), "ValidMasterCard")][DataMember()][RegularExpression("d{4}-d{4}-d{4}-d{4}", ErrorMessage="Creditcard not valid format should be: 9999-9999-9999-9999")][StringLength(30)]public string CreditCard{ This is quite interesting. However, what happens if more than one field has to be checked in the validation? In this case, one more parameter is added to the validation method. It is ValidationContext, and through this parameter, the instance of the entity we are dealing with can be accessed. public static ValidationResult ValidMasterCard( string strcardNumber, ValidationContext validationContext){ client currentClient = (client)validationContext.ObjectInstance; Entity-level validations Fields validation is quite interesting, but sometimes, rules have to be applied in a higher level, that is, entity level. RIA Services implements some machinery to perform this kind of validation. Only a custom validation has to be defined in the appropriate entity class declaration. Following the sample we're working upon, let us implement one validation which checks that at least one of the two payment methods (PayPal or credit card) is informed. To do so, go to the ClientCustomValidation.shared.cs (SimpleDB web project) and add the following static function to the ClientCustomValidation class: public static ValidationResult ValidatePaymentInformed(clientCurrentClient){ bool atLeastOnePaymentInformed = ((CurrentClient.PayPalAccount != null && CurrentClient.PayPalAccount != string.Empty) || (CurrentClient.CreditCard != null && CurrentClient.CreditCard != string.Empty)); return (atLeastOnePaymentInformed) ? ValidationResult.Success : new ValidationResult("One payment method must be informed at least");} Next, open the MyDomainService.metadata file and add, in the class level, the following annotation to enable that validation: [CustomValidation(typeof(ClientCustomValidation), ValidatePaymentInformed")][MetadataTypeAttribute(typeof(client.clientMetadata))]public partial class client When executing and trying the application, it will be realized that the validation is not performed. This is due to the fact that, unlike validations in the field level, the entity validations are only launched client-side when calling EndEdit or TryValidateObject. The logic is to first check if the fields are well informed and then make the appropriate validations. In this case, a button will be added, making the validation and forcing it to entity level. To know more about validation on entities, go to http://bit.ly/qTr9hz. Define the command launching the validation on the current entity in the ViewModel as the following code: private RelayCommand _validateCommand;public RelayCommand ValidateCommand{ get { if (_validateCommand == null) { _validateCommand = new RelayCommand(() => { // Let us clear the current validation list CurrentSelectedClient.ValidationErrors.Clear(); var validationResults = new List<ValidationResult>(); ValidationContext vcontext = new ValidationContext(CurrentSelectedClient, null, null); // Let us run the validation Validator.TryValidateObject(CurrentSelectedClient, vcontext, validationResults); // Add the errors to the entities validation error // list foreach (var res in validationResults) { CurrentSelectedClient.ValidationErrors.Add(res); } },(() => (CurrentSelectedClient != null)) ); } return _validateCommand; }} Define the button in the window and bind it to the command: <Button Content="Validate" Command="{Binding Path=ValidateCommand}"/> While executing, it will be appreciated that the fields be blank, even if we click the button. Nonetheless, when adding a breaking point, the validation is shown. What happens is, there is a missing element showing the result of that validation. In this case, the choice will be to add a header whose DataContext points to the current entity. If entity validations fail, they will be shown in this element. For more information on how to show errors, check the link http://bit.ly/ad0JyD. The TextBox added will show the entity validation errors. The final result will look as shown in the following screenshot:
Read more
  • 0
  • 0
  • 2347

article-image-visualizations-made-easy-gnuplot
Packt
01 Mar 2012
12 min read
Save for later

Visualizations made easy with gnuplot

Packt
01 Mar 2012
12 min read
  This article, written by Lee Philips the author of gnuplot Cookbook contains the following :   Making a surface plot Using coordinate mappings Coloring the surface Making a contour plot Making a vector plot Making an image plot or heat map Combining contours and images Combining surfaces with images Plotting a path in 3D Drawing parametric surfaces Making a surface plot A surface plot represents the dependent quantity z, which depends on the two independent variables x and y, as a surface whose height indicates the value of z.   The previous figure is a perspective drawing of a surface representing the Bessel function J0(r), where r is the distance from (x=0, y=0). The height of the surface shows the value of J0, given on the vertical axis (unlabeled in this figure, but usually called z). The other two (unlabeled) axes defning the plane above which the surface is drawn are the x and y axes.     How to do it… The following code listing is the script that coaxed gnuplot into making the previous figure:   set isosamples 40unset keyset title "J_0(r^2)"set xrange [-4:4]set yrange [-4:4]set ztics 1splot besj0(x**2+y**2)set view 29,53 #Done implicitly by mousing.set term pngcairo mono enhancedset out 'bessel.png'replot   How it works… There are several new commands in this recipe. The set isosamples command sets the isoline density. This is analogous to the set samples command when making 2D plots, but it sets the number of lines used in forming the surface. The number of isosamples can be set independently in each direction; if one number is specifed, it is used for both directions. The default of 10 usually creates surfaces that are far too coarse to be useful.   Turning to the second of the highlighted commands, the splot command is the 3D version of our old friend the plot command (it probably initially stood for "surface plot", but now can do several things besides plot surfaces, as we shall see in the rest of this article). It expects a function of x and y rather than x alone. Although we are interested in plotting something that has the type of symmetry that would be most conveniently expressed in polar (spherical or cylindrical) coordinates, these geometries are not available for function plots in 3D in gnuplot. (They are available through the set mapping command for data plots, as we shall see later in this article.) Therefore in such cases, we are required to convert our expressions to the rectangular coordinate system. Instead of what we would call r in a cylindrical coordinate system, here we use the equivalent x**2 + y**2.   In this recipe, we would like to illustrate, as far as possible, the interactive approach to creating a fnal 3D plot. The next highlighted line, beginning with set view, can be entered on the command line or included in a script. The view is the orientation in degrees of the perspective drawing of the 3D plot. Naturally, it does arise in 2D. It is diffcult to determine what is the most useful view for a particular plot without looking at it and experimenting with it; therefore, even if our fnal product is intended to be a fle, a common workfow is to frst create the plot using an interactive terminal (x11 or wxt). Then we rotate the plot with the mouse, and possibly scale and zoom it using the middle mouse button, until we arrive at the desired appearance. This is what we mean by the comment in the set view command. Now we can reset the terminal to the fnal output device that we need, specify the output fle, and simply say replot. The view and scaling at which we left the interactive plot is retained as a set of global settings and will be refected in our fnal output fle. These settings are also displayed at the bottom of the interactive plot window, so we can record them if we are going to make similar plots in the future, or want a set of plots to be drawn with the same settings. Note that we also redefned the ztics value. This is because when the plot is tilted to the fnal view angle that we chose, the perspective causes the tic labels on the vertical axis to be crowded together; this is a common problem with 3D plots, and taking manual control of the tics on the z-axis is the solution.   There's more… Following is the same plot with one setting changed (aside from a slight adjustment in the view angle):   While the frst plot was essentially a wireframe that we could see through, this version has the appearance of a solid, opaque surface. All we need to do is to say set hidden3d. This, which only works when lines or linespoints are being used, makes the surface appear opaque by removing from the plot any part of the surface, other surfaces, and other plot elements such as the axes and tic labels, that are behind the surface from our point of view. The underside of the surface is shown in a contrasting color with a color output device, but the two sides of the surface are not distinguished in monochrome. The name of the setting refers to the technique of hidden line removal; gnuplot is justly famed for the quality of its hidden line removal algorithm, and is one reason this program is so well regarded for its 3D plotting ability.   Using coordinate mappings It is possible, when making 3D plots from data fles, for the data to be interpreted in spherical or cylindrical coordinates rather than the default Cartesian system. For details, type help set mapping. We will give an example of using the cylindrical mapping to conveniently draw a shape with cylindrical symmetry.   The previous figure is a perspective view of a surface that somewhat resembles a Christmas tree ornament. The relevant feature of this surface is that it has rotational symmetry around the z (vertical) axis, which means that it is most naturally expressed in cylindrical coordinates.   How to do it… Try the following script:   set mapping cylindricalunset ticsunset borderset hiddenset xrange [-pi : pi]set yrange [-pi : pi]set zrange [0 : pi]set iso 60unset keysplot '++' using 1:2:(sin($2)) with lines   How it works… There are several new ideas used in this recipe. Breaking it down, these are:   The set mapping command The frst, highlighted line contains the new command that is the subject of this recipe. When the default Cartesian (x-y-z) coordinate system is changed to cylindrical then the columns of data read in during a data plot are interpreted as θ-z-r, where θ is the angular coordinate, z is the vertical coordinate, and r is the radius. A spherical mapping is also available and explained in the gnuplot online help (help set mapping). If the data fle only has two columns, then the plot is drawn with r = 1.   In our example we don't want to plot from a data fle, however. We want to plot a function given directly in the script. This presents us with a problem, as gnuplot does not support cylindrical or spherical plots of functions in 3D. The solution is to use one of gnuplot's pseudofles.   The ++ pseudofle The "++" pseudofle creates rows of imaginary data with three columns x-y-z unless we change the coordinate mapping, which of course in this example we have. Setting the mapping to cylindrical means that the fctitious data columns will be interpreted as θ-z-r.   Now to plot a function, we use the using notation applied to the imaginary columns of data. We've done this in the fnal line of the script, where we plot the sine of the second column (z).   To clarify the use of "++" when plotting surfaces, note that, in Cartesian coordinates, the two commands "splot sin(x)+cos(y)" and "splot '++' using 1:2:(sin($1)+cos($2)) with lines" produce exactly the same plot.   Coordinate ranges We have also established ranges for all variables in the set xrange and two other commands following it. The ranges for the polar coordinates are taken from the corresponding Cartesian coordinates, that is, when we set the xrange, we are setting both the range of the x-axis displayed on the plot and the range of the variable θ in the cylindrical coordinate system. It is mandatory to set xrange and yrange when using the "++" flename.   This mixing of the coordinate system in which the function is calculated and the Cartesian system in which it is displayed can be confusing, but the example shows a strategy, which should make it possible to get predictable results. Setting the xrange and yrange as we've done puts the r = 0 point in the middle of the graph and prevents part of the plot from being cut off. It also sets up a full rotation of the angular coordinate over a range of 2 p.   If we wanted to plot, say, our shape with half of it sliced off by a vertical plane, the easiest way to do this is not to fddle with the coordinate ranges, but to apply a transformation to one of the fctitious data columns: splot '++' using ($1/2):2:(sin($2)) with lines, will do the trick without any surprising side effects. In this example the underlying angular coordinate (column 1) still passes through a full rotation, but we've divided it in half without changing the way the figure is projected onto the Cartesian display. Note that the 60 isolines will still be used in our reduced angular range, so we might want to set iso to a smaller value.   Completing the picture We've eliminated all of the graph adornments (unset tics, unset border, unset key) so we will be left with only the surface. The isosamples are set to give a suffciently smooth surface drawing that is nevertheless not too crowded with isosurface lines (see the previous recipe). set hidden ensures that we shall see only the outer surface of the shape.   Coloring the surface The wireframe splot with hidden line removal that we covered in the frst recipe of this article, Making a surface plot, gives the visual impression of a solid surface. The numerical value encoded into the surface's height can be visually estimated, roughly, by the perspective provided by the isolines in conjunction with the tics on the vertical axis. But gnuplot also has a way to draw real solid surfaces whose height is indicated by color or shade.   The previous figure shows the same mathematical function plotted in the frst recipe in this article (Making a surface plot). Now the numerical value of the function at any point is indicated by both the height of the surface and its shade; the surface is now drawn as an opaque membrane rather than as a network of curves.   How to do it…   To produce the previous figure, run the following in gnuplot:   set isosamples 100set samples 100unset keyset title "J_0(r^2)"set xrange [-4:4]set yrange [-4:4]set ztics 1unset surfaceset pm3dsplot besj0(x**2+y**2) The surface will be drawn with a palette of colors when a color output device is being used and with a grayscale palette when using a monochrome terminal.     How it works… If you compare the previous script with the one in the Making a surface plot recipe at the beginning of this article, you will see that the only signifcant difference is the highlighted line. The pm3d mode colors the imaginary surface being plotted according to its height or z-value at every point, with the mapping between the height and the color or shade determined by the palette, which we shall discuss in some more detail shortly.   The other modifcations are to increase the number of isolines, in order to get a smoother surface, and to turn off the drawing of the individual isolines themselves with the command unset surface. We also need to set the sample frequency; generally we want this to be equal to the isosample frequency. In pm3d mode, the two orthogonal sets of isolines are drawn with two different spacings given by the two parameters. Although the gnuplot manual claims that the global hidden3d setting does not affect pm3d surface plots, it in fact seems to, and should not be turned on, as it appears to slightly degrade the drawing quality.   There's more… Sometimes we want both a colored surface and a set of isolines; in fact, this can often be the clearest type of quantitative 3D plot. The way to achieve the highest quality in this type of graph is to use the hidden3d linestyle option to pm3d, as we do in the following script:   set iso 30set samp 30unset keyset title "J_0(r^2)"set xrange [-4:4]set yrange [-4:4]set ztics 1unset surfset style line 1 lt 4 lw .5set pm3d at s hidden3d 1splot besj0(x**2+y**2) This requires us to defne a user linestyle. Then the linestyle is referred to in an option to the set pm3d command. This will cause the isolines to be drawn using lines in this style, which allows us to have them in any color, thickness, or pattern supported by our terminal. Further, the isolines will be drawn with hidden line removal, so they will appear to be embedded in the opaque surface. As before, the global hidden3d option should not be turned on.   Note that we've also reduced the sample and isoline frequency, to keep our plot from being too crowded with isolines. (The at s component of the set pm3d command means at surface.)  
Read more
  • 0
  • 0
  • 13522

article-image-ibm-db2-97-advanced-database-administration-cookbook
Packt
01 Mar 2012
10 min read
Save for later

IBM DB2 9.7 Advanced Database Administration Cookbook

Packt
01 Mar 2012
10 min read
Introduction IBM DB2 comes and integrates a multitude of high-availability solutions, that can employ and increase the availability of databases. There are software high availability solutions, such as SQL Replication, Q Replication, HADR, DB2 ACS, and IBM TSA, and hardware-based solutions, such as IBM PPRC, HACMP, FlashCopy, or hybrid such as the new clustering solution provided by DB2 pureScale technology, covered in Chapter 14, IBM pureScale Technology and DB2. Obviously, we can choose to implement one solution or use a virtually unlimited number of combinations to ensure that we are highly protected from any type of disaster. In the following recipes, we will cover how to set up and DB2 fault monitor as high availability solutions as a high availability solution. HADR is a high availability software solution provided by IBM for DB2 database protection in the case of disaster or critical database failure. HADR is an abbreviation for High Availability Disaster Recovery. The technology itself can be classified as a replication solution. Basically, this technology replicates data by sending and replaying logs from a source database to a destination database. The source database, by convention, is called the primary database; the destination database is called the standby database Some important benefits of HADR: Transparent takeover (switchover) or takeover by force (failover) for clients connected Automatic client reroute capabilities It is a very fast method in terms of recoverability It has a negligible impact on transaction performance The cost is low compared with a hardware replication solution Some restrictions with using HADR: Backup operations are not supported on standby databases/li> HADR cannot be implemented with multipartitioned databases The primary and standby database must be run on the same operating system (same bit size) and the same version of the DB2 database system The system clock must be synchronized on both primary and standby servers Operations replicated using HADR: Data definition language (DDL) Data manipulation language (DML) Buffer pool operations Table space operations Online reorganization Offline reorganization Metadata for stored procedures and user-defined functions Operations that do not replicate using HADR: Tables created with the NOT LOGGED INITIALLY option Non-logged LOB columns are not replicated Updates to database configuration Database configuration and database manager configuration parameters Objects external to the database-related objects and library files The recovery history file (db2rhist.asc) and changes made to it Setting up HADR by using the command line Setting up HADR is straightforward. You can use a variety of methods to set up HADR, using the command line or Control Center, and IBM Optim Database Administrator HADR setup wizards. In the following recipe, we will set up HADR using the command line. Getting ready In this recipe, nodedb21 will be used for the initial primary database, and nodedb22 for the initial standby database. We use the term initially, because in the following recipes, we will initiate takeover and takeover by force operations, and the databases will exchange and change their roles. All operations will be conducted on the non-partitioned NAV database, under instance db2inst1 on nodedb21, and db2inst1 on nodedb22. How to do it... To set up a HADR configuration, we will use the following steps: Install IBM DB2 9.7 ESE in location /opt/ibm/db2/ V9.7_01, on nodedb22 Creating additional directories for log archiving, backup, and mirror log locations, on both nodes Setting proper permissions on new directories Configuring log archiving and log mirroring Configuring the LOGINDEXBUILD and INDEXREC parameters Backing up the primary database Copying primary database backup to nodedb22 Setting up HADR communication ports Configuring HADR parameters on both databases Initiating HADR on the standby database Initiating HADR on the primary database Install IBM DB2 ESE on nodedb22 Install IBM DB2 9.7 Enterprise Server Edition in location /opt/ibm/db2/V9.7_01, on nodedb22; create users db2inst1 and db2fenc1, and instance db2inst1, during installation. Creating additional directories for table space containers, archive logs, backup, and mirror logs Create one directory for table space containers of the NAV application on nodedb22: [root@nodedb22 ~]# mkdir -p /data/db2/db2inst1/nav [root@nodedb22 ~]# Create directories for the archive logs location on both servers: [root@nodedb22 ~]# mkdir -p /data/db2/db2inst1/logarchives [root@nodedb22 ~]# [root@nodedb21 ~]# mkdir -p /data/db2/db2inst1/logarchives [root@nodedb22 ~]# Create directories for the database backup location on both servers: [root@nodedb21 ~]# mkdir -p /data/db2/db2inst1/backup [root@nodedb21 ~]# [root@nodedb21 ~]# mkdir -p /data/db2/db2inst1/backup [root@nodedb21 ~]# Create directories for the mirror log location on both servers: [root@nodedb21 ~]# mkdir -p /data/db2/db2inst1/mirrorlogs [root@nodedb21 ~]# [root@nodedb22 ~]# mkdir -p /data/db2/db2inst1/mirrorlogs [root@nodedb22~]# This is just an example; usually, the mirror logs should be stored in a safe location. If it is possible use an NFS mount exported from another server. Setting permissions on the new directories Set db2inst1 as owner for the directories where we will configure archive log and log mirrors, and restore the NAV application table space containers on both servers: [root@nodedb21 ~]# chown –R db2inst1:db2iadm1 /data/db2/db2inst1 [root@nodedb21 ~]# [root@nodedb22 ~]# chown –R db2inst1:db2iadm1 /data/db2/db2inst1 [root@nodedb22 ~]# Configuring archive log and mirror log locations Connect to the NAV database: [db2inst1@nodedb21 ~]$ db2 "CONNECT TO NAV"     Database Connection Information   Database server        = DB2/LINUXX8664 9.7.4  SQL authorization ID   = DB2INST1  Local database alias   = NAV Quiesce the NAV database: [db2inst1@nodedb21 ~]$ db2 "QUIESCE DATABASE IMMEDIATE" DB20000I  The QUIESCE DATABASE command completed successfully. [db2inst1@nodedb21 ~]$ Set the log archive location: [db2inst1@nodedb21 ~]$ db2 "UPDATE DB CFG FOR NAV USING    logarchmeth1 'DISK:/data/db2/db2inst1/logarchives'" DB20000I  The UPDATE DATABASE CONFIGURATION command completed    successfully. [db2inst1@nodedb21 ~]$ Set the number of primary logs; usually, in a HADR configuration, it should be set to a greater value than in a normal database: [db2inst1@nodedb21 ~]$ db2 "UPDATE DB CFG FOR NAV USING    LOGPRIMARY 20" DB20000I  The UPDATE DATABASE CONFIGURATION command completed    successfully. [db2inst1@nodedb21 ~]$ Set the number of secondary logs: [db2inst1@nodedb21 ~]$ db2 "UPDATE DB CFG FOR NAV USING    LOGSECOND 5" DB20000I  The UPDATE DATABASE CONFIGURATION command completed    successfully. [db2inst1@nodedb21 ~]$ Set log file size; it is also recommended to be bigger than in a normal database: [db2inst1@nodedb21 ~]$  db2 "UPDATE DB CFG FOR NAV USING    LOGFILSIZ 2048 " DB20000I  The UPDATE DATABASE CONFIGURATION command completed    successfully. [db2inst1@nodedb21 Set a mirror log location in the case where the primary log's host fails (these logs will be needed for replaying on the standby database): [db2inst1@nodedb21 ~]$ db2 "UPDATE DATABASE CONFIGURATION USING    MIRRORLOGPATH /data/db2/db2inst1/mirrorlogfiles" DB20000I  The UPDATE DATABASE CONFIGURATION command completed    successfully. [db2inst1@nodedb21 ~]$ Set log buffer size. Use a log buffer size on both the primary and standby databases, bigger than in a normal database, to overcome log buffer full events: [db2inst1@nodedb21 ~]$ db2 "UPDATE DB CFG FOR NAV USING    LOGBUFSZ 1024 " DB20000I  The UPDATE DATABASE CONFIGURATION command completed    successfully. db2inst1@nodedb21 ~]$ Set log buffer size. Use a log buffer size on both the primary and standby databases, bigger than in a normal database, to overcome log buffer full events: [db2inst1@nodedb21 ~]$  db2 "UNQUIESCE DATABASE" DB20000I  The UNQUIESCE DATABASE command completed successfully. [db2inst1@nodedb21 ~]$  Unquiesce the NAV database: [db2inst1@nodedb21 ~]$ db2 "UPDATE DATABASE CONFIGURATION FOR NAV    USING LOGINDEXBUILD ON " DB20000I  The UPDATE DATABASE CONFIGURATION command completed    successfully. [db2inst1@nodedb21 ~]$ LOGBUFSZ should be correlated with network tuning; try to set TCP tunables (receive and send buffer) to appropriate values. Configuring LOGINDEXBUILD and INDEXREC parameters The LOGINDEXBUILD parameter specifies if operations as create index, rebuild index, and reorganize table generates log when it has a value of ON or not if it is OFF, rebuild or table reorganization; usually, this parameter in a HADR configuration should be configured to ON. If you plan to use the standby database for reporting, then it is mandatory to set the parameter to ON. If it is set to OFF, then there is not enough log information for building the indexes on the standby database. Therefore, the new indexes created or rebuilt in a HADR configuration are marked as invalid on the standby database. In case you have slow network bandwidth, you can set it to OFF, but the amount of time needed to activate the standby database will increase considerably, because the invalid indexes have to be rebuilt. You can also control index logging at table level by setting the table option LOG INDEX BUILD to ON or OFF. [db2inst1@nodedb21 ~]$ db2 "UPDATE DATABASE CONFIGURATION FOR NAV    USING INDEXREC RESTART" DB20000I  The UPDATE DATABASE CONFIGURATION command completed    successfully. [db2inst1@nodedb21 ~]$ In case you have slow network bandwidth, you can set it to OFF, but the amount of time needed to activate the standby database will increase considerably, because the invalid indexes have to be rebuilt. You can also control index logging at table level by setting the table option LOG INDEX BUILD to ON or OFF. [db2inst1@nodedb21 ~]$ db2 terminate DB20000I  The TERMINATE command completed successfully. [db2inst1@nodedb21 ~]$ db2 "BACKUP DATABASE NAV TO "/data/backup"    COMPRESS" Backup successful. The timestamp for this backup image is :    20110707150659 [db2inst1@nodedb21 ~]$ The parameter INDEXREC control s the rebuild of invalid indexes on database startup. In HADR configurations, it should be set to RESTART, on both databases. [db2inst1@nodedb21 ~]$ scp /data/db2/db2inst1/backup/ NAV.0.db2inst1.NODE0000.CATN0000.   20110707150659.001 nodedb22:/data/db2/db2inst1/backup db2inst1@nodedb22's password: NAV.0.db2inst1.NODE0000.CATN0000.20110707150659.001 [db2inst1@nodedb21 ~]$ Backing up the primary database Back up the database with the compress option, to save space; it is useful to compress the backup piece, especially when you have a very large database: [db2inst1@nodedb22 ~]$ db2 "RESTORE DATABASE NAV FROM /data/db2/ db2inst1/backup TAKEN AT 20110707150659 REPLACE    HISTORY FILE" DB20000I  The RESTORE DATABASE command completed successfully. [db2inst1@nodedb22 ~]$ Copying the database backup to nodedb22 Copy the database backup to location /data/db2/db2inst1/backup on nodedb22: DB2_HADR_NAV1      55006/tcp DB2_HADR_NAV2      55007/tcp Restoring the database NAV on nodedb22 Restore the database on the standby location: [db2inst1@nodedb21 ~]$ db2 "UPDATE DATABASE CONFIGURATION FOR NAV USING HADR_LOCAL_HOST nodedb21"DB20000I  The UPDATE DATABASE CONFIGURATION command completed successfully.[db2inst1@nodedb21 ~]$ Setting up HADR communication ports Add the following two entries to /etc/services, on both locations: DB2_HADR_NAV1      55006/tcp DB2_HADR_NAV2      55007/tcp
Read more
  • 0
  • 0
  • 2818
article-image-configuration-and-handy-tweaks-udk
Packt
01 Mar 2012
18 min read
Save for later

Configuration and Handy Tweaks for UDK

Packt
01 Mar 2012
18 min read
(For more resources on UDK, see here.) Groundwork for adjusting configuration defaults In this article we'll build up from simply changing some trivial configuration settings to orchestrating unique gaming experiences. To start out, we need to make clear how UDK configures content under the hood by introducing the layout and formatting for this kind of file. The experience in this recipe can be likened to savoring morsels of cake samples in a shop before committing to a purchase; while you're not actually changing major settings yet, the aim is to make some tasty observations so later the changes you make will come from informed decisions. Getting ready In your UDK installation, you have a folder called C:UDK~UDKGameConfig and it is worthwhile to browse the files here and get to know them. Treat them like the faces of colleagues in a new company. It may take a while, but you'll eventually know all their names! You may want to make an alternative install of UDK before starting this article, to protect any content you've been working on. In these examples we're going to assume you are using ConTEXT, or a notepad alternative that highlights UnrealScript syntax, like those listed at http://wiki.beyondunreal.com/Legacy:Text_Editor. The advantage with ConTEXT is that you have a history of recently opened files, and several concurrently open files can be arranged in tabs; also, you can view specific lines in the file in response to line error warnings from the UDK log, should they arise. In ConTEXT, to display line numbers go to the Options | Environment Options menu then click on the Editor tab in the options dialog, tick on Line Numbers and press Apply. How to do it... Open the file C:UDK~UDKGameConfigDefaultCharInfo.INI using ConTEXT. Alongside it, open C:UDK~UDKGameConfigUDKCharInfo.INI, which is a rather similar file. Values we set from an existing class are presented after a reference to the class in square brackets which surround the folder and class name, such as [UTGame.UTCharInfo]. Commented out lines or notes are distinguished using ; and the entire line isn't parsed. This differs from the // used to comment out lines in UnrealScript. In some configuration files you will see BasedOn=... followed by the path to another configuration file. This helps you track where the info is coming from. Values for variables are set in the configuration file as in the example: LOD1DisplayFactor=0.4. In ConTEXT , click on File | Open... and scroll down the list of files. Notice that it previews the contents of the highlighted .INI files before you open them. Choose DefaultWeapon.INI and edit line 3 (strictly speaking line 1 is empty). Press Ctrl + G (or View | Go to Line) and enter the line number 3. This line specifies CrosshairColor for the weapon. If you change the value A=255 to A=0 you will effectively have hidden the weapon target. Supposing you wanted to do so, you'd just have to save this file then reload UDK. No compiling is needed for adjusting configuration files, unlike classes, unless the configuration is defining custom scripts to be used in some way. Let's assume for now that you don't want to hide the weapon cursor, so close the file without saving by pressing Ctrl + W and choose No for the file save option. Open the file UDKEditor.INI and go to line 12: Bindings=(Key="S",SeqObjClassName="Engine.SeqAct_PlaySound") then look at line 28: Bindings=(Key="S",bControl=true,SeqObjClassName="Engine.SeqEvent_LevelLoaded"). What's important here is the added bControl=true for the S key. S will create a Play Sound node in Kismet. Ctrl + S will create a Level Loaded event. We really don't need to change anything but you can, for instance, change Ctrl + S to Ctrl + L in line 28, for adding a new Level Loaded event node in Kismet: Bindings=(Key="L",bControl=true,SeqObjClassName="Engine.SeqEvent_LevelLoaded") . Make sure that UDK is closed before you save the change or the file will not be effected at all. Reloading UDK after saving the change will see it take effect. Unless you have very long hands you will probably want to test this using the right Ctrl button on the right-hand side of the keyboard so your fingers can hold L and Ctrl and left mouse click all at once. You should get the Level Loaded event in Kismet from this key combination now. On that note, when you are specifying hotkeys for your game, bear in mind the idea of user friendly interface as you decide what keys to use. Often used keys should be easy to remember, fast to reach, and possibly semantically clustered together. How it works... What we looked at in this recipe were some formatting features that occur in every configuration file. In particular it is important to know that edits should be made while UDK is closed or they get scrubbed back out immediately. Also you will have noticed that the values we change reference UnrealScript classes from the C:UDK~DevelopmentSrc folder, and reading through their layout can help you learn how the default content in UDK is made to work during gameplay. There's more... Consider a version control software for editing UDK content There is a free version control system called Bazaar ( http://bazaar.canonical.com) that integrates with Windows folders. What version control software does is keep track of changes you have made to files, protecting them through a history based backup that lets you review and revert changes to a previous state if needed. You can init a folder, then browse it, add content and commit changes to changed files with comments that help you track what's going on. Where needed you can review the change history and revert files to any previously committed state. Alternatives to Bazaar are the commercial tool Alienbrain Essentials for Artists, or the free repository TortoiseSVN. The utility of version control in the case of UDK development is to prevent unrecoverable problems when doing a script compile when changes haven't been tracked and therefore can't be restored without re-installing from scratch, and to allow assets to be overwritten with a history. Enabling the remote control for game inspection This is a method for turning on an extra feature of UDK called the Remote Control that can be used to manipulate render nodes, inspect Actors, and evaluate performance. How to do it... In Windows, go to the Start menu or your desktop and find the shortcut for the UDK Editor and right-click on it to expose its properties. In the Target field edit it to read: C:UDK~BinariesUDKLift.exe editor -wxwindows -remotecontrol -log. The main point of this entry is so that we can launch a tool called RemoteControl. The usefulness of running the -log window increases over time. It is used for tracking what is happening while you run the editor and PIE. When trouble shooting problems in Kismet or with missing assets for example, it is a good first port of call for seeing where and when errors occur. In the following screenshot, the log shows the creation of a Trigger Touch event in the main Kismet sequence based on the actor Trigger_0 in the scene: Having edited the UDK launch properties to allow RemoteControl to launch, now load the Midday Lighting map template and PIE (F8). If you press Tab and type remotecontrol you should get a pop-up window like this: If you hit the Actors tab you get access to properties of certain actors, and you can change properties live while playing. For example, expand Actors | DominantDirectionalLight and double-click on DominantDirectionalLight_0 . Then in the light's property Movement | Rotation | Yaw or Pitch, try out different angle values. However, the changed values will revert to the editor state after PIE is closed. See also: http://udn.epicgames.com/Three/RemoteControl.html. An additional note: if you happen to minimize the RemoteControl window in some cases it may stay like that until you press Alt + Space . And to swap between the game and the Remote Control window press Alt + Tab . Pressing Show Flags lets you display various elements of the scene such as Collision, Bones, and Bounds. Go to the Stats tab and tick on Memory in the listing, then expand it and tick on the item within it called Lightmap Memory . This shows the cost of displaying lighting backed into lightmaps. Further down in the Stats tab list, tick on the item D3D9RHI and look at the DrawPrimitive calls. In the game, look straight up at the empty sky and note the value. Now look at the box on the ground. Notice the value increases. This is because the view has to draw the added objects (ground and box). In a large scene, especially on iOS, there is a functional limit to the number of drawcalls. How it works... The RemoteControl tool is external to the game window and is created using wxWindows. It is meant for use during PIE, for evaluation of performance. The Actors tab shows us a tree list of what is in the level, along with filters. You can access Actor Properties for an actor under the crosshairs using the icon [] or access them from a list. What you see in this screenshot is the result of turning the memory statistics on within a scene and the frame rate indicator (FPS = frames per second) through the Rendering tab in the Stats section, as well as the display of bones used in the scene. In Remote Control , you can set the Game Resolution (or game window size) under Rendering | View Settings. In the next recipe, we'll look at how to do this in UDK's configuration. Changing the Play in Editor view resolution This is a very short method for setting the view size for PIE sessions. How to do it... In C:UDK~UDKGameConfigDefaultEngineUDK.INI press Ctrl + F and search for [SystemSettings]. This should expose the lines: [SystemSettings] ; NOTE THAT ANY ITEMS IN THIS SECTION AFFECT ALL PLATFORMS! bEnableForegroundShadowsOnWorld=False bEnableForegroundSelfShadowing=False ResX=1024 ResY=768 Change the ResX and ResY values to suit yourself, using screen resolutions that make sense, such as 1920x1080. This will update UDKEngine.INI in the same folder so you will see the change reflected in these lines: PlayInEditorWidth=1920 PlayInEditorHeight=1080 Load a level and PIE to see the difference. Note that if you update UDKEngine.INI directly it will just revert to whatever is set in DefaultEngineUDK.INI. There is a lot of redundancy built into UDK's configuration that takes some time and practice to get used to. Removing the loading hints and similar articles Quickly getting rid of all the peripheral text and imagery that wraps around a given level, especially in console mode, is not easy. A few options exist for removing the more distracting elements such as splash screens and menus. You may want to do this if you wish to show your work without any artwork made by someone else getting in the way of your own. One method is called destructive editing, where your delete or blank out assets at the source, and this isn't as safe as it is quick. Instead you can provide your own menus, splash, and UI by extending on the classes that call up the default ones. How to do it... Removing the console mode videos during map loading Open C:UDK~UDKGameConfigDefaultEngine.INI. Press Ctrl + F and search for [FullScreenMovie] , which should expose the startup and loadmap references. Comment out the entries as follows: [FullScreenMovie] //+StartupMovies=UDKFrontEnd.UDK_loading //+LoadMapMovies=UDKFrontEnd.UDK_loading Load a level and play in console mode []. You won't get the movies that precede gameplay. If you take out all the pre-loading content there may occur the problem of getting a look at the level too early and "pre-caching" showing up. To learn how to instead swap out the .BIK files that constitute the loading movies between levels you can follow the video by Michael J Collins: http://www.youtube.com/watch?v=SX1VQK1w4NU. Removing the level loading hints To totally prevent .BIK movies during development, you can open C:UDK~EngineConfigBaseEngine.INI and search for NoMovies, then adjust the FALSE in the exposed lines: // Game Type name //class'Engine'.static.AddOverlay( LoadingScreenGameTypeNameFont, Desc, 0.1822, 0.435, 1.0, 1.0, false); // becomes class'Engine'.static.AddOverlay( LoadingScreenGameTypeNameFont, Desc, 0.1822, 0.435, 1.0, 0, false); // and Map name // class'Engine'.static.AddOverlay( LoadingScreenMapNameFont, MapName, 0.1822, 0.46, 2.0, 2.0, false); // becomes class'Engine'.static.AddOverlay( LoadingScreenMapNameFont, MapName, 0.1822, 0.46, 2.0, 0, false); What's happening here is that the last digit of four in an entry 1,1,1,1 is the Alpha value, controlling transparency, so 1,1,1,0 will be invisible. The first three numbers are RGB values, but they can be anything if the Alpha is 0. Removing the default exit menu Open C:UDK~UDKGameConfigDefaultInput.INI and press Ctrl + F to search for Escape. The first time will expose a removed key binding, so search from the cursor again to find in line 205: .Bindings=(Name="Escape",Command="GBA_ShowMenu" and comment it out with ; then add this line underneath instead: .Bindings=(Name="Escape",Command="quit" if UDK should close directly. If you want to provide a custom menu type: .Bindings=(Name="Escape",Command="open Menu" , where players pressing Esc will be sent to Menu.UDK (a scene of your own design) instead of the default menu. This won't do anything if you don't provision a Menu.UDK map first and cook it with your game levels. The map Menu.UDK would typically include some kind of clickable exit, resume, and reload buttons. If you want Esc to automatically restart the level you're playing, put in "open YOURMAPNAME" but bear in mind the only way to exit then will be Alt + F4. Possibly a strong way to approach the Escape option is to have a Pause command that permits a choice about leaving the game through a floating button: Resume or Exit. In addition you might have a similar floating button when the player dies: Replay or Exit, rather than the default Fire to Respawn. Editing DefaultEngineUDK to allow 4096x4096 texture compression This is a method for enabling UDK to use textures larger than its default limit. Conventional wisdom says that game textures should be highly optimized, but large resolution artwork is always enticing for many designers, and computers are getting better all the time. Performance issues aside, it's a good goal to push the graphic envelope and larger textures allow detail to hold up better on close inspection. Getting ready We've provided one really large texture that is 4096x4096 that you may find convenient, intended for use as a Skydome. If you are going to use a large texture it would most likely be on a very important model like a key character always close to the camera or else of a very large model which is always visible, such as a Skydome, or Skybox. A simple tutorial for making a Skybox is at http://www.worldofleveldesign.com/categories/UDK/UDK-how-add-skybox.php but this recipe assumes the use of a provided one. How to do it... With UDK closed, open C:UDK~UDKGameConfigDefaultEngineUDK.INI. Press Ctrl + F in ConTEXT and search for Skybox . You should be directed to line 127: TEXTUREGROUP_Skybox=(MinLODSize=512,MaxLODSize=2048,LODBias=0,MinMagFilter=aniso,MipFilter=point). Change the value for MaxLODSize=2048 to 4096. To really force it, you can also set the MinLODSize=4096 too. Doing this for a Skybox is okay, since there's normally only one used in a map, but you'd risk slowing the game down to do this with regular textures. Note, the TEXTUREGROUP_Skybox will allow a texture for a Skybox to be large, but not other things like character textures. For that, you can edit the relevant values in the other TEXTUREGROUP lines. Further down, in the SystemSettingsMobile section, the texture sizes are much smaller, which is due to the relatively limited processing power of mobile devices. Now save, and next we'll verify this in fact worked by adding a large sky to a scene in UDK. Look in the Content Browser and search the Packt folder for Packt_SkyDome , which is a typical mesh for a sky. You can see there is a completed version, and a copy called Packt_SkyDomeStart which has no material. Go to the Packt texture group. You will see there is already a provisioned 4096x4096 texture for Packt_SkyDome , but let's import a fresh one. Right-click in the Content Browser panel and choose Import , and browse to find Packt_SkydomeStart.PNG which is just a copy of the already existing texture. The reason to import it, is to verify you understand the compression setting. In the options you will see a panel that lets you specify the name info, which you should enter as Packt.Texture.SkyDomeTest or something unique. Further down you will see the compression settings. Choose LODGroup and from the expanding list choose TEXTUREGROUP_Skybox, as shown in the next screenshot, since this is what we have set to have 4096x4096 compression enabled in the configuration: The file may take some time to process, given its size. Once it is complete you can create a new Material Packt.Material.SkyDomeTest_mat. Open it and in the Material Editor hold T and click to add the highlighted SkyDomeTest texture to the Emissive channel. Skies are self lighting, so in the PreviewMaterial node's properties, set the Lighting Model to MLM_Unlit . The mesh Packt_SkyDomeStart is already UV mapped to match the texture, and if you double-click on it you can assign the new Material Packt.Material.SkyDomeTest_mat in the LODGroupInfo by expanding until you access the empty Material channel. Select the Material in the Content Browser then use the assign icon [] to assign it. Then you can save the package and place the mesh in the level. Be sure to access its properties (F4) and under the Lighting turn off Cast Shadow and set the Lighting Channels tick on Skybox and uncheck Static , as shown in the next screenshot: You could scale the mesh in the scene to suit, and perhaps drop it down below Z=0 a little. You could also use an Exponential Height Fog to hide the horizon. Since there is a specific sun shown in the sky image, you will need to place a Dominant Directional light in the scene and rotate it so its arrow (representing its direction) approximates the direction the sunlight would be coming from. It would be appropriate to tint the light warmly for a sunset. Setting the preview player size reference object In UDK versions greater than April 2011, pressing the key in the editor Perspective view will show a mesh that represents the player height. By default this is just a cube. The mesh to display can be set in the configuration file UDKEditorUserSettings.INI and we'll look at how to adjust this. This is to help designers maintain proper level metrics. You'll be able to gauge how tall and wide to make doors so there's sufficient space for the player to move through without getting stuck. Getting ready Back up C:UDK~UDKGameConfigUDKEditorUserSettings.INI then open it in ConTEXT with UDK closed. How to do it... Press Ctrl + F and search for [EditorPreviewMesh] . Under it, we will change the entry PreviewMeshNames=" EditorMeshes.TexPropCube ". Note the we need to replace this with a StaticMesh, and a good place to put this to ensure loading would be the EngineContent package EditorMeshes . First, open UDK and in the Content Browser search using the type field for TexPropCube . When this appears, right-click on the asset and choose Find Package . The packages list will show us EngineContentEditorMeshes and in here right-click and choose Import . You'll be prompted to browse in Windows, so from the provided content folder, find SkinTail.ASE which is a character model and import this into EditorMeshes. There's no need to set a group name for this. Importing this file as a StaticMesh enables it to be used as a preview model. By contrast, the SkeletalMesh Packt.Mesh.Packt_SkinTail won't work for what we are trying to do. If you set up a SkeletalMesh for the preview model the log will return cannot find staticmesh Yourmodelname whenever you press in the editor. It is optional, but you can double click the imported StaticMesh and assign a Material to it after expanding the LOD_Info property to show the Material channel. For the SkinTail content, choose Packt.Material.Packt_CharMat . Then save the EditorMeshes package including SkinTail and quit UDK. Use ConTEXT to edit the file UDKEditorUserSettings.INI so that the line we were looking at in Step 1 is changed to: PreviewMeshNames=" EditorMeshes.SkinTail " Eventually you'll opt to use your own StaticMesh. Save, close, and restart UDK. Open a map, and press in the editor to see if SkinTail will display. If it doesn't, run UDK using the -log option and check for error warnings when is pressed. Note that PreviewMeshNames=" EditorMeshes.TexPropCube " can also be adjusted in these configuration files: C:UDK~EngineConfigBaseEditorUserSettings.INI or C:UDK~UDKGameConfigDefaultEditorUserSettings.INI.
Read more
  • 0
  • 0
  • 8544

article-image-introduction-enterprise-business-messages
Packt
27 Feb 2012
4 min read
Save for later

Introduction to Enterprise Business Messages

Packt
27 Feb 2012
4 min read
(For more resources on Oracle, see here.) Before we jump into the AIA Enterprise Business Message (EBM) standards, let us understand a little more about Business Messages. In general, Business Message is information shared between people, organizations, systems, or processes. Any information communicated to any object in a standard understandable format are called messages. In the application integration world, there are various information-sharing approaches that are followed. Therefore, we need not go through it again, but in a service-oriented environment, message-sharing between systems is the fundamental characteristic. There should be a standard approach followed across an enterprise, so that every existing or new business system could understand and follow the uniform method. XML technology is a widely-accepted message format by all the technologies and tools. Oracle AIA framework provides a standard messaging format to share the information between AIA components. Overview of Enterprise Business Message (EBM) Enterprise Business Messages (EBMs) are business information exchanged between enterprise business systems as messages. EBMs define the elements that are used to form the messages in service-oriented operations. EBM payloads represent specific content of an EBO that is required to perform a specific service. In an AIA infrastructure, EBMs are messages exchanged between all components in the Canonical Layer. Enterprise Business Services (EBS) accepts EBM as a request message and responds back to EBM as an output payload. However, in Application Business Connector Service (ABCS), the provider ABCS accepts messages in the EBM format and translates them into the application provider's Application Business Message (ABM) format. Alternatively, the requester ABCS receives ABM as a request message, transforms it into an EBS, and calls the EBS to submit the EBM message. Therefore, EBM has been a widely-accepted message standard within AIA components. The context-oriented EBMs are built using a set of common components and EBO business components. Some EBMs may require more than one EBO to fulfill the business integration needs. The following diagram describes the role of an EBM in the AIA architecture: EBM characteristics The fundamentals of EBM and its characteristics are as follows: Each business service request and response should be represented in an EBM format using a unique combination of an action and an EBO instance. One EBM can support only one action or verb. EBM component should import the common component to make use of metadata and data types across the EBM structure. EBMs are application interdependencies. Any requester application that invokes Enterprise Business Services (EBS) through ABCS should follow the EBM format standards to pass as payload in integration. The action that is embedded in the EBM is the only action that sender or requester application can execute to perform integration. The action in the EBM may also carry additional data that has to be done as part of service execution. For example, the update action may carry information about whether the system should notify after successful execution of update. The information that exists in the EBM header is common to all EBMs. However, information existing in the data area and corresponding actions are specific to only one EBM. EBM headers may carry tracking information, auditing information, source and target system information, and error-handling information. EBM components do not rely on the underlying transport protocol. Any service protocols such as HTTP, HTTPs, SMTP, SOAP, and JMS should carry EBM payload documents. Exploring AIA EBMs We explored the physical structure of the Oracle AIA EBO in the previous chapter; EBMs do not have a separate structure. EBMs are also part of the EBO's physical package structure. Every EBO is bound with an EBM. The following screenshot will show the physical structure of the EBM groups as directories: As EBOs are grouped as packages based on the business model, EBMs are also a part of that structure and can be located along with the EBO schema under the Core EBO package.
Read more
  • 0
  • 0
  • 10954
Modal Close icon
Modal Close icon