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-windows-phone-7-silverlight-location-services
Packt
02 Sep 2011
11 min read
Save for later

Windows Phone 7 Silverlight: Location Services

Packt
02 Sep 2011
11 min read
  (For more resources on this subject, see here.)   Introduction One of the most powerful features of smartphones today is location awareness. Windows Phone 7 is no exception. The wide consumerization of GPS around 10 years ago brought handheld GPS receivers for consumers on the go, but few individuals could justify the expense or pocket space. Now that smartphones have GPS built in, developers have built incredibly powerful applications that are location-aware. For example, apps that help users track their jogging route, get real-time navigation assistance while driving, and map/analyze their golf game. In this article, we will take a deep dive into the location API for Windows Phone 7 by building an application to help navigate during travel and another to map the user's location. Tracking latitude and longitude In this recipe, we will implement the most fundamental use of location services, tracking latitude and longitude. Our sample application will be a navigation helper which displays all the available location information. We will also review the different ways in which the phone gets its location information and their attributes. Getting ready We will be working in Visual Studio for this tutorial, so start by opening Studio and creating a new Windows Phone 7 application using the Windows Phone Application project template. All the location/GPS-related methods and classes are found in the System.Deviceassembly, so add this reference next: We will need some UI to start tracking and displaying the data, so go to the MainPage.xaml file, if it's not already open. Change the ContentPanel from a Grid to a StackPanel, then add a button to the designer, and set its Content property to Start Tracking. Next add four TextBlocks. Two of these will be Latitude and Longitude labels. We will use the others to display the latitude/longitude coordinates, so set their x:Name properties to txtLatitudeand txtLongitude respectively. You can also set the application and page titles if you like. The resulting page should look similar to the following screenshot: How to do it... The core class used for tracking location is the GeoCoordinateWatcher. We subscribe to the events on the watcher to be noticed when changes occur: Double-click on your button in the designer to go to the click event handler for the button in the code behind file. This is where we will start watching for location changes. Create a GeoCoordinateWatcher field variable named _watcher. Set this field variable inside your click event handler to a new GeoCoordinateWatcher. Next add a handler to the PositionChanged event named _watcher_PositionChanged. Then start watching for position changes by calling the Start method. Next add a handler to the PositionChanged event named _watcher_PositionChanged. Then start watching for position changes by calling the Start method. In order to use the position information, create the void handler method with parameters named sender of type object and e of type GeoPositionChangedEventArgs<GeoCoordinate>. Inside this method set the Text properties on the txtLatitude and txtLongitude text boxes to the coordinate values e.Position.Location.Latitude and e.Position.Location.Longitude respectively. Latitude and longitude as strings:Latitude and longitude are of type double and can be converted to strings using the ToString method for display. You should end up with a class that is similar to the following block of code: public partial class MainPage : PhoneApplicationPage{ private IGeoPositionWatcher<GeoCoordinate> _watcher; public MainPage() { InitializeComponent(); } private void butTrack_Click(object sender, RoutedEventArgs e) { _watcher = new GeoCoordinateWatcher(); _watcher.PositionChanged += _watcher_PositionChanged; _watcher.Start(); } void _watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e) { txtLatitude.Text = e.Position.Location.Latitude.ToString(); txtLongitude.Text = e.Position.Location.Longitude.ToString(); }} That's it. You can now deploy this app to your phone, start tracking, and see the latitude and longitude changes on your screen. How it works... The watcher starts a new background thread to watch for position changes. Each change is passed to your event handler(s) for processing. Window Phone 7 provides location services through the following three sources: GPS: Satellite based Wi-Fi: Known wireless network positions Cellular: Cellular tower triangulation Each of these position providers has their strengths and weaknesses, but the combination of the three covers nearly any possible use case: GPS is the most accurate, but you must have an unobstructed view of the sky Wi-Fi can be accurate depending on how close you are to the access point, but you must be in the range of a known wireless network Cellular is the least accurate and only needs cell signal So if you're in an urban area with tall buildings, GPS may be intermittent but Wi-Fi networks and cellular coverage should be plentiful. If you are in a rural area, GPS should work well and cellular triangulation might help where available. Tracking altitude, speed, and course In this section, we will discuss the different types of location information that are provided by the GeoCoordinateWatcher and how they might be used. A quick look at the Object Browser shows us that the GeoCoordinate object has several interesting properties: In addition to Latitude and Longitude, there is Altitude, Speed, and Course, among others. Altitude and Speed are pretty self-explanatory, but Course might not be as obvious. Course is your heading or the direction you are going, given two points. The following table shows each property and its unit of measurement: Horizontal and Vertical Accuracy specifies the accuracy of Latitude/Longitude and Altitude, respectively, in meters. For example, this means your actual Latitude position is between the reported Latitude minus the accuracy value and the reported Latitude plus the accuracy value. The smaller the accuracy value, the more accurate but the longer it may take to get a position. Getting ready Add three more sets of TextBlock controls under the longitude control for each of the following properties: Altitude, Speed, and Course. Set the speed label TextBlock Text property to Speed (mph). Name the TextBlock controls as you did for latitude/longitude so we can assign their Text properties from the code behind. The page should look similar to the following screenshot: How to do it... Perform the following steps to add altitude, speed, and course to the application: Open the code behind file for the page, and in the positionChanged handler, set Altitude in the same way as we did for latitude/longitude before; simply set the Text property of the txtAltitude TextBlock to the Altitude property as a string. For the Speed property, convert from meters per second to miles per hour. One meter/sec equals 2.2369363 miles per hour, so we can multiply the Speed property by 2.2369363 to get miles per hour. Display Course so that the normal users can understand it, using the name of the direction (that is, North, South, East, West). The Course value is a degree value from 0 to 360, where 0/360 is north and the degrees go clock-wise with a compass. Create a series of if statements that will provide the correct heading. Between 316 and 45 will be North, 46 and 135 will be East, 136 and 225 will be South, and between 226 and 315 will be West. Our _watcher_PositionChanged method is now as follows: void _watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e) { txtLatitude.Text = e.Position.Location.Latitude. ToString() txtLongitude.Text = e.Position.Location.Longitude. ToString(); txtAltitude.Text = e.Position.Location.Altitude. ToString(); txtSpeed.Text = (e.Position.Location.Speed * 2.2369363). ToString(); double course = e.Position.Location.Course; string heading = string.Empty; if (course >= 46 && course <= 135) heading = "East"; if (course >= 136 && course <= 225) heading = "South"; if (course >= 226 && course <= 315) heading = "West"; else heading = "North"; txtCourse.Text = heading; } How it works... If you deploy the application to your phone now, you will see Speed display NaN (Not a Number) , Altitude display zero, and Course is blank. This is because Altitude, Speed, and Course are only available when you specify that you want high accuracy location information. We do this by instantiating the GeoCoordinateWatcher with a GeoPositionAccuracy type of GeoPositionAccuracy.High in the constructor. By default, the accuracy is set to GeoPositionAccuracy.Default, which only uses cellular triangulation and is not accurate enough to calculate speed, altitude, or course. GeoPositionAccuracy.High uses GPS and Wi-Fi, when available, which provides more accurate positions. Although it is more accurate, it also uses more power and can take longer to get your position. This is why High is not the default. It is strongly recommended that you only use the higher accuracy when it is absolutely needed. In this case, we need the Altitude, Speed, and Course, so it is necessary. Set the accuracy level to high in the GeoCoordinateWatcher constructor , like so: _watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High); If you redeploy the application to the phone, you may notice it still shows NaN for Speed. This may be because you are indoors and have an obstructed view of the sky or it may just take a few moments to get a good signal. Once you have a good GPS signal, you should see valid Speed, Altitude, and Course values. The best way to test this application is in the passenger seat of a driving vehicle so you can compare the vehicles, speedometer to the speed in the application. There may be times, as well, when you lose GPS signal. When this occurs, the latitude and longitude values will also be set to NaN. In such cases, you may want to give the user a friendlier explanation of the problem. You can simply check the IsUnknown property in the position changed event and provide a better message. For example: void _watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e) { if (e.Position.Location.IsUnknown) { txtLatitude.Text = "Finding your position. Please wait ..."; txtLongitude.Text = ""; txtAltitude.Text = ""; txtSpeed.Text = ""; txtCourse.Text = ""; return; } txtLatitude.Text = e.Position.Location.Latitude. ToString(); txtLongitude.Text = e.Position.Location.Longitude. ToString(); txtAltitude.Text = e.Position.Location.Altitude. ToString(); txtSpeed.Text = (e.Position.Location.Speed * 2.2369363). ToString(); double course = e.Position.Location.Course; string heading = string.Empty; if (course >= 46 && course <= 135) heading = "East"; if (course >= 136 && course <= 225) heading = "South"; if (course >= 226 && course <= 315) heading = "West"; else heading = "North"; txtCourse.Text = heading; } The last property we will cover in this recipe is the Permission property on the GeoPositionWatcher. Before submitting your app to the marketplace, you must define which phone capabilities your app requires. One of those capabilities is location. Before a user installs an application, he/she is informed of the capabilities the app requires and must accept them to install. Even though the user has given the app permission to use location services of the phone, the user can still turn off location services for all apps from the settings menu. The Permission property will help us check for this and tell the user why the app isn't working. There is a slight trick though; the Permission property will be set to Granted when the watcher is first created, even if Location services are disabled in the Settings menu. It will be reset to Denied after the Start method is called. So we must check for a Denied permission value after calling the Start method. For instance: private void butTrack_Click(object sender, RoutedEventArgs e){ _watcher = newGeoCoordinateWatcher(GeoPositionAccuracy.High); _watcher.PositionChanged += _watcher_PositionChanged; _watcher.StatusChanged += _watcher_StatusChanged; _watcher.Start(); if (_watcher.Permission == GeoPositionPermission.Denied) tbLatitude.Text = "Please enable location services and retry";} We can test this by turning off location services. From the start screen, flick left to the App list, tap Settings, and then tap location. Swipe the switch left to the Off position. Redeploy the application to your phone, click the Start Tracking button, and you will see our new message. As mentioned previously, the user must accept the capabilities of the application before installing it. There may be future updates to the phone which allow the user to change the allowed capabilities of individual apps from the settings menu as well. The Permission property would also be useful in this scenario. There's more... You may have also noticed the CivicAddressResolver and CivicAddress classes in the System.Device.Location namespace . As its name implies, the CivicAddressResolver returns an address from a GeoCoordinate. Unfortunately, this is not yet implemented for Windows Phone. You can instantiate them and attempt to use them, but the returned CivicAddress will always be unknown. Hopefully, this will be implemented in the future updates of the operating system.
Read more
  • 0
  • 0
  • 2029

article-image-plone-4-development-creating-custom-workflow
Packt
30 Aug 2011
7 min read
Save for later

Plone 4 Development: Creating a Custom Workflow

Packt
30 Aug 2011
7 min read
Professional Plone 4 Development Build robust, content-centric web applications with Plone 4.        Keeping control with workflow As we have alluded to before, managing permissions directly anywhere other than the site root is usually a bad idea. Every content object in a Plone site is subject to security, and will in most cases inherit permission settings from its parent. If we start making special settings in particular folders, we will quickly lose control. However, if settings are always acquired, how can we restrict access to particular folders or prevent authors from editing published content whilst still giving them rights to work on items in a draft state? The answer to both of these problems is workflow. Workflows are managed by the portal_workflow tool. This controls a mapping of content types to workflows definitions, and sets a default workflow for types not explicitly mapped. The workflow tool allows a workflow chain of multiple workflows to be assigned to a content type. Each workflow is given its own state variable. Multiple workflows can manage permissions concurrently. Plone's user interface does not explicitly support more than one workflow, but can be used in combination with custom user interface elements to address complex security and workflow requirements. The workflow definitions themselves are objects found inside the portal_workflow tool, under the Contents tab. Each definition consists of states, such as private or published, and transitions between them. Transitions can be protected by permissions or restricted to particular roles. Although it is fairly common to protect workflow transitions by role, this is not actually a very good use of the security system. It would be much more sensible to use an appropriate permission. The exception is when custom roles are used solely for the purpose of defining roles in a workflow. Some transitions are automatic, which means that they will be invoked as soon as an object enters a state that has this transition as a possible exit (that is, provided the relevant guard conditions are met). More commonly, transitions are invoked following some user action, normally through the State drop-down menu in Plone's user interface. It is possible to execute code immediately before or after a transition is executed. States may be used simply for information purposes. For example, it is useful to be able to mark a content object as "published" and be able to search for all published content. More commonly, states are also used to control content item security. When an object enters a particular state, either its initial state, when it is first created, or a state that is the result of a workflow transition, the workflow tool can set a number of permissions according to a predefined permissions map associated with the target state. The permissions that are managed by a particular workflow are listed under the Permissions tab on the workflow definition: These permissions are used in a permission map for each state: If you change workflow security settings, your changes will not take effect immediately, since permissions are only modified upon workflow transitions. To synchronize permissions with the current workflow definitions, use the Update security settings button at the bottom of the Workflows tab of the portal_workflow tool. Note that this can take a long time on large sites, because it needs to find all content items using the old settings and update their permissions. If you use the Types control panel in Plone's Site Setup to change workflows, this reindexing happens automatically. Workflows can also be used to manage role-to-group assignments in the same way they can be used to manage role-to-permission assignments. This feature is rarely used in Plone, however. All workflows manage a number of workflow variables, whose values can change with transitions and be queried through the workflow tool. These are rarely changed, however, and Plone relies on a number of the default ones. These include the previous transition (action), the user ID of the person who performed that transition (actor), any associated comments (comments), the date/time of the last transition (time), and the full transition history (review_history). Finally, workflows can define work lists, which are used by Plone's Review list portlet to show pending tasks for the current user. A work list in effect performs a catalog search using the workflow's state variable. In Plone, the state variable is always called review_state. The workflow system is very powerful, and can be used to solve many kinds of problems where objects of the same type need to be in different states. Learning to use it effectively can pay off greatly in the long run. Interacting with workflow in code Interacting with workflow from our own code is usually straightforward. To get the workflow state of a particular object, we can do: from Products.CMFCore.utils import getToolByName wftool = getToolByName(context, 'portal_workflow') review_state = wftool.getInfoFor(context, 'review_state') However, if we are doing a search using the portal_catalog tool, the results it returns has the review state as metadata already: from Products.CMFCore.utils import getToolByName catalog = getToolByName(context, 'portal_catalog') for result in catalog(dict( portal_type=('Document', 'News Item',), review_state=('published', 'public', 'visible',), )): review_state = result.review_state # do something with the review_state To change the workflow state of an object, we can use the following line of code: wftool.doActionFor(context, action='publish') The action here is the name of a transition, which must be available to the current user, from current state of context. There is no (easy) way to directly specify the target state. This is by design: recall that transitions form the paths between states, and may involve additional security restrictions or the triggering of scripts. Again, the Doc tab for the portal_workflow tool and its sub-objects (the workflow definitions and their states and transitions) should be your first point of call if you need more detail. The workflow code can be found in Products.CMFCore.WorkflowTool and Products.DCWorkflow. Installing a custom workflow It is fairly common to create custom workflows when building a Plone website. Plone ships with several useful workflows, but security and approvals processes tend to differ from site to site, so we will often find ourselves creating our own workflows. Workflows are a form of customization. We should ensure they are installable using GenericSetup. However, the workflow XML syntax is quite verbose, so it is often easier to start from the ZMI and export the workflow definition to the filesystem. Designing a workflow for Optilux Cinemas It is important to get the design of a workflow policy right, considering the different roles that need to interact with the objects, and the permissions they should have in the various states. Draft content should be visible to cinema staff, but not customers, and should go through review before being published. The following diagram illustrates this workflow: This workflow will be made the default, and should therefore apply to most content. However, we will keep the standard Plone policy of omitting workflow for the File and Image types. This means that permissions for content items of these types will be acquired from the Folder in which they are contained, making them simpler to manage. In particular, this means it is not necessary to separately publish linked files and embedded images when publishing a Page. Because we need to distinguish between logged-in customers and staff members, we will introduce a new role called StaffMember. This role will be granted View permission by default for all items in the site, much like a Manager or Site Administrator user is by default (although workflow may override this). We will let the Site Administrator role represent site administrators, and the Reviewer role represent content reviewers, as they do in a default Plone installation. We will also create a new group, Staff, which is given the StaffMember role. Among other things, this will allow us to easily grant the Reader, Editor and Contributor role in particular folders to all staff from the Sharing screen. The preceding workflow is designed for content production and review. This is probably the most common use for workflow in Plone, but it is by no means the only use case. For example, the author once used workflows to control the payment status on an Invoice content type. As you become more proficient with the workflow engine, you will find that it is useful in a number of scenarios.
Read more
  • 0
  • 0
  • 2583

article-image-xcode-4-ios-displaying-notification-messages
Packt
30 Aug 2011
8 min read
Save for later

Xcode 4 ios: Displaying Notification Messages

Packt
30 Aug 2011
8 min read
  Xcode 4 iOS Development Beginner's Guide Use the powerful Xcode 4 suite of tools to build applications for the iPhone and iPad from scratch  The iPhone provides developers with many ways in which they can add informative messages to their applications to alert the user. We will be looking at the various types of notification methods, ranging from alerts, activity indicators, audio sounds, and vibrations. Exploring the notification methods The applications on the iPhone are user-centric, meaning that they don't operate without a user interface and don't perform any background operations. These types of applications enable users to work with data, play games, or communicate with other users. Despite these, at some point an application will need to communicate with the user. This can be as simple as a warning message, or providing feedback or even asking the user to provide some information. The iPhone and Cocoa-Touch use three special methods to gain your attention and are explained below: CLASS DESCRIPTION UIAlertView This class creates a simple modal alert window that presents the user with a message and a few options. Modal elements require the user to interact with them before they can proceed. These types of elements are displayed (layered) on top of other windows and block the underlying objects until the user responds to one of the actions presented. UIActionSheet These types of classes are similar to the UIAlertView class, except that they can be associated with a given view, tab bar, or toolbar and become animated when it appears on the screen. Action Sheets do not have an associated message property; they contain a single title property. System Sound Services This enables playback and vibration and supports various file formats (CAF, AIF, and WAV Files) and makes use of the AudioToolBox framework.   Generating alerts There is no doubt that you will need to incorporate alerts into your applications. These can be very useful to inform the user of when the application is running, and can be a simple message such as memory running low, or that an application or internal error has occurred. We can notify the user in a number of ways using the UIAlertView class, and it can be used to display a simple modal message or gather information from the user. Time for action – creating the GetUsersAttention application Before we can proceed with creating our GetUsersAttention application, we must first launch the Xcode development environment. Select the View-based application template from the project template dialog box. Ensure that you have selected iPhone from under the Device Family dropdown, as the type of view to create. Next, you will need to provide a name for your project. Enter GetUsersAttention and then choose a location where you would like to save the project. Once your project has been created, you will be presented with the Xcode interface, along with the project files that the template created for you within the Project Navigator Window. What just happened? In this section, we looked at the steps involved in creating a View-based application for our GetUsersAttention application. In the next section, we will take a look at how we can add the AudioToolbox Framework into our project to incorporate sound.   Time for action – adding the AudioToolbox Framework to our application Now that we have created our project, we need to add the AudioToolbox Framework to our project. This is an important framework which will provide us the ability to play sound and vibrate the phone. To add the new frameworks or additional frameworks into your project, select the Project Navigator Group, and then follow these simple steps as outlined below: Select your Project within the Project Navigator Window. Then select your project target from under the TARGETS group. Select the Build Phases tab. Expand the Link Library with Libraries disclosure triangle. Then finally, use the + button to add the library that you want to add; if you want to remove a framework, highlight it from the group and click on the - button. You can also search for the framework if you can't find it in the list shown. If you are still confused on how to go about adding these frameworks, refer to the following image, which highlights what parts you need to select (highlighted by a red rectangle): (Move the mouse over the image to enlarge.) What just happened? In the above section, we looked at how we are able to add frameworks to our application. We looked at the differences between the MediaPlayer and AudioToolbox frameworks, and the limitations of the two. Adding frameworks to your application allows you to extend your application and utilise those features in your application to avoid reinventing the wheel. When you add frameworks to your application, the system loads them into memory as needed and shares the one copy of the resource among all applications whenever possible. Now that we have added the AudioToolbox.framework to our project, our next step is to start creating our user interface. In the next section, we will be taking a look at how we start to build our user interface and create events. Building our user interface User interfaces provide a great way to communicate with the user in order to either obtain information or to display notifications. A good interface is one that provides a good consistent flow throughout your application as you navigate from screen to screen. This involves considering the screen size of your view. In the next section, we look at how to add some controls to our view to build our interface. To obtain further information about what constitutes a good user interface, Apple provides these iOS Human Interface Guidelines which can be obtained at the following location: http://developer.apple.com/library/ios/documentation/userexperience/conceptual/mobilehig/MobileHIG.pdf.   Time for action – adding controls to our View We will be adding five button (UIButton) controls which will be handling our actions to display alerts and Action Sheets, playing sounds, and vibrating the iPhone. From the Object Library, select and drag a (UIButton) Round Rect Button control onto our view. Modify the Object Attributes of the Round Rect Button control and set its title to read "Show Activity Indicator". From the Object Library, select and drag a (UIButton) Round Rect Button control onto our view. Modify the Object Attributes of the Round Rect Button control and set its title to read "Display Alert Dialog". From the Object Library, select and drag a (UIButton) Round Rect Button control onto our view. Modify the Object Attributes of the Round Rect Button control and set its title to read "Display Action Sheet". From the Object Library, select and drag a (UIButton) Round Rect Button control onto our view. Modify the Object Attributes of the Round Rect Button control and set its title to read "Play Alert Sound". From the Object Library, select and drag a (UIButton) Round Rect Button control onto our view. Modify the Object Attributes of the Round Rect Button control and set its title to read "Vibrate iPhone". If you have followed everything correctly, your view should look something like the following screenshot. If it doesn't look quite the same, feel free to adjust yours: What just happened? In the above section, we looked at how we are able to use the Object Library to add controls to our view and customize their properties in order to build our user interface. In the next section, we will take a look at how to create events to respond to button events. Creating events Now that we have created our user interface, we need to create the events that will respond when we click on each of the buttons. We first need to create an instance of our UIAlertView class, called baseAlert, which will be used by our Show Activity indicator event and will be used to dismiss the activity after a period of time has lapsed. Open the GetUsersAttentionViewController.h interface file and add the following highlighted code as shown in the code snippet below: #import <UIKit/UIKit.h> @interface GetUsersAttentionViewController : UIViewController <UIAlertViewDelegate, UIActionSheetDelegate>{ UIAlertView *baseAlert; } @end We could have declared this within our GetUsersAttentionViewController.m implementation file, but I prefer to declare it in this class as it can be referenced throughout your application. You will notice from the code snippet above that we have made reference to two delegate protocols within our GetUsersAttentionViewController.h interface file; this enables us to capture and respond to the button event presses used by our Action Sheet and Alert Views. This will become apparent when we start adding the code events for our Alert Views and Action Sheets.  
Read more
  • 0
  • 0
  • 2069

article-image-plone-4-development-understanding-zope-security
Packt
30 Aug 2011
6 min read
Save for later

Plone 4 Development: Understanding Zope Security

Packt
30 Aug 2011
6 min read
Security primitives Zope's security is declarative: views, actions, and attributes on content objects are declared to be protected by permissions. Zope takes care of verifying that the current user has the appropriate access rights for a resource. If not, an AccessControl.Unauthorized exception will be raised. This is caught by an error handler which will either redirect the user to a login screen or show an access denied error page. Permissions are not granted to users directly. Instead, they are assigned to roles. Users can be given any number of roles, either site-wide, or in the context of a particular folder, in which case they are referred to as local roles. Global and local roles can also be assigned to groups, in which case all users in that group will have the particular role. (In fact, Zope considers users and groups largely interchangeable, and refers to them more generally as principals.) This makes security settings much more flexible than if they were assigned to individual users. Users and groups Users and groups are kept in user folders, which are found in the ZMI with the name acl_users. There is one user folder at the root of the Zope instance, typically containing only the default Zope-wide administrator that is created by our development buildout the first time it is run. There is also an acl_users folder inside Plone, which manages Plone's users and groups. Plone employs the Pluggable Authentication Service (PAS), a particularly flexible kind of user folder. In PAS, users, groups, their roles, their properties, and other security-related policy are constructed using various interchangeable plugins. For example, an LDAP plugin could allow users to authenticate against an LDAP repository. In day-to-day administration, users and groups are normally managed from Plone's Users and Groups control panel. Permissions Plone relies on a large number of permissions to control various aspects of its functionality. Permissions can be viewed from the Security tab in the ZMI, which lets us assign permissions to roles at a particular object. Note that most permissions are set to Acquire—the default—meaning that they cascade down from the parent folder. Role assignments are additive when permissions are set to acquire. Sometimes, it is appropriate to change permission settings at the root of the Plone site (which can be done using the rolemap.xml GenericSetup import step—more on that follows), but managing permissions from the Security tab anywhere else is almost never a good idea. Keeping track of which security settings are made where in a complex site can be a nightmare. Permissions are the most granular piece of the security puzzle, and can be seen as a consequence of a user's roles in a particular context. Security-aware code should almost always check permissions, rather than roles, because roles can change depending on the current folder and security policy of the site, or even based on an external source such as an LDAP or Active Directory repository. Permissions can be logically divided into three main categories: Those that relate to basic content operations, such as View and Modify portal content. These are used by almost all content types, and defined as constants in the module Products.CMFCore.permissions. Core permissions are normally managed by workflow. Those that control the creation of particular types of content, such as ATContentTypes: Add Image. These are usually set at the Plone site root to apply to the whole site, but they may be managed by workflow on folders. Those that control site-wide policy. For example, the Portlets: Manage portlets permission is usually given to the Manager and Site Administrator roles, because this is typically an operation that only the site's administrator will need to perform. These permissions are usually set at the site root and acquired everywhere else. Occasionally, it may be appropriate to change them here. For example, the Add portal member permission controls whether anonymous users can add themselves (that is, "join" the site) or not. Note that there is a control panel setting for this, under Security in Site Setup. Developers can create new permissions when necessary, although they are encouraged to reuse the ones in Products.CMFCore.permissions if possible. The most commonly used permissions are: Permission Constant Zope Toolkit name Controls Access contents information AccessContents Information zope2.AccessContents Information Low-level Zope permission controlling access to objects View View zope2.View Access to the main view of a content object List folder contents ListFolderContents cmf.ListFolderContents Ability to view folder listings Modify portal content ModifyPortalContent cmf.ModifyPortalContent Edit operations on content Change portal events N/A N/A Modification of the Event content type (largely a historical accident) Manage portal ManagePortal cmf.ManagePortal Operations typically restricted to the Manager role. Request review RequestReview cmf.RequestReview Ability to submit content for review in many workflows. Review portal content ReviewPortalContent cmf.ReviewPortalContent Ability to approve or reject items submitted for review in many workflows. Add portal content AddPortalContent cmf.AddPortalContent add new content in a folder. Note that most content types have their own "add" permissions. In this case, both this permission and the type-specific permission are required. The Constant column in the preceding table refers to constants defined in Products. CMFCore.permissions. The Zope Toolkit name column lists the equivalent names found in ZCML files in packages such as Products.CMFCore, Products.Five and (at least from Zope 2.13), AccessControl. They contain directives such as: <permission id="zope2.View" title="View" /> This is how permissions are defined in the Zope Toolkit. Custom permissions can also be created in this way. Sometimes, we will use ZCML directives which expect a permission attribute, such as: <browser:page name="some-view" class=".someview.SomeView" for="*" permission="zope2.View" /> The permission attribute here must be a Zope Toolkit permission ID. The title of the <permission /> directive is used to map the Zope 2-style permissions (which are really just strings) to Zope Toolkit permission IDs. To declare that a particular view or other resource defined in ZCML should not be subject to security checks, we can use the special permission zope.Public.
Read more
  • 0
  • 0
  • 2263

article-image-professional-plone-4-development-developing-site-strategy
Packt
26 Aug 2011
9 min read
Save for later

Professional Plone 4 Development: Developing a Site Strategy

Packt
26 Aug 2011
9 min read
  Professional Plone 4 Development Build robust, content-centric web applications with Plone 4.         Read more about this book       (For more resources on Plone, see here.) Creating a policy package Our policy package is just a package that can be installed as a Plone add-on. We will use a GenericSetup extension profile in this package to turn a standard Plone installation into one that is configured to our client's needs. We could have used a full-site GenericSetup base profile instead, but by using a GenericSetup extension profile we can avoid replicating the majority of the configuration that is done by Plone. We will use ZopeSkel to create an initial skeleton for the package, which we will call optilux.policy, adopting the optilux.* namespace for all Optilux-specific packages. In your own code, you should of course use a different namespace. It is usually a good idea to base this on the owning organization's name, as we have done here. Note that package names should be all lowercase, without spaces, underscores, or other special characters. If you intend to release your code into the Plone Collective, you can use the collective.* namespace, although other namespaces are allowed too. The plone.* namespace is reserved for packages in the core Plone repository, where the copyright has been transferred to the Plone Foundation. You should normally not use this without first coordinating with the Plone Framework Team. We go into the src/ directory of the buildout and run the following command: $ ../bin/zopeskel plone optilux.policy This uses the plone ZopeSkel template to create a new package called optilux.policy. This will ask us a few questions. We will stick with "easy" mode for now, and answer True when asked whether to register a GenericSetup profile. Note that ZopeSkel will download some packages used by its local command support. This may mean the initial bin/zopeskel command takes a little while to complete, and assumes that we are currently connected to the internet. A local command is a feature of PasteScript, upon which ZopeSkel is built. ZopeSkel registers an addcontent command, which can be used to insert additional snippets of code, such as view registrations or new content types, into the initial skeleton generated by ZopeSkel. We will not use this feature, preferring instead to retain full control over the code we write and avoid the potential pitfalls of code generation. If you wish to use this feature, you will either need to install ZopeSkel and PasteScript into the global Python environment, or add PasteScript to the ${zopeskel:eggs} option in buildout.cfg, so that you get access to the bin/paster command. Run bin/zopeskel --help from the buildout root directory for more information about ZopeSkel and its options. Distribution details Let us now take a closer look at what ZopeSkel has generated for us. We will also consider which files should be added to version control, and which files should be ignored. Item Version control Purpose setup.py Yes Contains instructions for how Setuptools/Distribute (and thus Buildout) should manage the package's distribution. We will make a few modifications to this file later. optilux.policy.egg-info/ Yes Contains additional distribution configuration. In this case, ZopeSkel keeps track of which template was used to generate the initial skeleton using this file. *.egg No ZopeSkel downloads a few eggs that are used for its local command support (Paste, PasteScript, and PasteDeploy) into the distribution directory root. If you do not intend to use the local command support, you can delete these. You should not add these to version control. README.txt Yes If you intend to release your package to the public, you should document it here. PyPI requires that this file be present in the root of a distribution. It is also read into the long_description variable in setup.py. PyPI will attempt to render this as reStructuredText markup (see http://docutils.sourceforge.net/rst.html). docs/ Yes Contains additional documentation, including the software license (which should be the GNU General Public License, version 2, for any packages that import directly from any of Plone's GPL-licensed packages) and a change log. Changes to setup.py Before we can progress, we will make a few modifications to setup.py. Our revised file looks similar to the following code, with changes highlighted: from setuptools import setup, find_packagesimport osversion = '2.0'setup(name='optilux.policy', version=version, description="Policy package for the Optilux Cinemas project", long_description=open("README.txt").read() + "n" + open(os.path.join("docs", "HISTORY.txt")).read(), # Get more strings from # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ "Framework :: Plone", "Programming Language :: Python", ], keywords='', author='Martin Aspeli', author_email='optilude@gmail.com', url='http://optilux-cinemas.com', license='GPL', packages=find_packages(exclude=['ez_setup']), namespace_packages=['optilux'], include_package_data=True, zip_safe=False, install_requires=[ 'setuptools', 'Plone', ], extras_require={ 'test': ['plone.app.testing',] }, entry_points=""" # -*- Entry points: -*- [z3c.autoinclude.plugin] target = plone """,# setup_requires=["PasteScript"],# paster_plugins=["ZopeSkel"], ) The changes are as follows: We have added an author name, e-mail address, and updated project URL. These are used as metadata if the distribution is ever uploaded to PyPI. For internal projects, they are less important. We have declared an explicit dependency on the Plone distribution, that is, on Plone itself. This ensures that when our package is installed, so is Plone. We will shortly update our main working set to contain only the optilux. policy distribution. This dependency ensures that Plone is installed as part of our application policy. We have then added a [tests] extra, which adds a dependency on plone. app.testing. We will install this extra as part of the following test working set, making plone.app.testing available in the test runner (but not in the Zope runtime). Finally, we have commented out the setup_requires and paster_plugins options. These are used to support ZopeSkel local commands, which we have decided not to use. The main reason to comment them out is to avoid having Buildout download these additional dependencies into the distribution root directory, saving time, and reducing the number of files in the build. Also note that, unlike distributions downloaded by Buildout in general, there is no "offline" support for these options. Changes to configure.zcml We will also make a minor change to the generated configure.zcml file, removing the line: <five:registerPackage package="." initialize=".initialize" /> This directive is used to register the package as an old-style Zope 2 product. The main reason to do this is to ensure that the initialize() function is called on Zope startup. This may be a useful hook, but most of the time it is superfluous, and requires additional test setup that can make tests more brittle. We can also remove the (empty) initialize() function itself from the optilux/policy/__init__.py file, effectively leaving the file blank. Do not delete __init__.py, however, as it is needed to make this directory into a Python package. Updating the buildout Before we can use our new distribution, we need to add it to our development buildout. We will consider two scenarios: The distribution is under version control in a repository module separate to the development buildout itself. This is the recommended approach. The distribution is not under version control, or is kept inside the version control module of the buildout itself. The example source code that comes with this article is distributed as a simple archive, so it uses this approach. Given the approach we have taken to separating out our buildout configuration into multiple files, we must first update packages.cfg to add the new package. Under the [sources] section, we could add: [sources]optilux.policy = svn https://some-svn-server/optilux.policy/trunk Or, for distributions without a separate version control URL: [sources]optilux.policy = fs optilux.policy We must also update the main and test working sets in the same file: [eggs]main = optilux.policytest = optilux.policy [test] Finally, we must tell Buildout to automatically add this distribution as a develop egg when running the development buildout. This is done near the top of buildout.cfg: auto-checkout = optilux.policy We must rerun buildout to let the changes take effect: $ bin/buildout We can test that the package is now available for import using the zopepy interpreter: $ bin/zopepy>>> from optilux import policy>>> The absence of an ImportError tells us that this package will now be known to the Zope instance in the buildout. To be absolutely sure, you can also open the bin/instance script in a text editor (bin/instance-script.py on Windows) and look for a line in the sys.path mangling referencing the package. Working sets and component configuration It is worth deliberating a little more on how Plone and our new policy package are loaded and configured. At build time: Buildout installs the [instance] part, which will generate the bin/instance script. The plone.recipe.zope2instance recipe calculates a working set from its eggs option, which in our buildout references ${eggs:main}. This contains exactly one distribution: optilux.policy. This in turn depends on the Plone distribution which in turn causes Buildout to install all of Plone. Here, we have made a policy decision to depend on a "big" Plone distribution that includes some optional add-ons. We could also have depended on the smaller Products.CMFPlone distribution (which works for Plone 4.0.2 onwards), which includes only the core of Plone, perhaps adding specific dependencies for add-ons we are interested in. When declaring actual dependencies used by distributions that contain reusable code instead of just policy, you should always depend on the packages you import from or otherwise depend on, and no more. That is, if you import from Products.CMFPlone, you should depend on this, and not on the Plone meta-egg (which itself contains no code, but only declares dependencies on other distributions, including Products. CMFPlone). To learn more about the rationale behind the Products. CMFPlone distribution, see http://dev.plone.org/plone/ticket/10877. At runtime: The bin/instance script starts Zope. Zope loads the site.zcml file (parts/instance/etc/site.zcml) as part of its startup process. This automatically includes the ZCML configuration for packages in the Products.* namespace, including Products.CMFPlone, Plone's main package. Plone uses z3c.autoinclude to automatically load the ZCML configuration of packages that opt into this using the z3c.autoinclude.plugin entry point target = plone. The optilux.policy distribution contains such an entry point, so it will be configured, along with any packages or files it explicitly includes from its own configure.zcml file.
Read more
  • 0
  • 0
  • 1907

article-image-implementing-software-engineering-best-practices-and-techniques-apache-maven
Packt
24 Aug 2011
10 min read
Save for later

Implementing Software Engineering Best Practices and Techniques with Apache Maven

Packt
24 Aug 2011
10 min read
  Apache Maven 3 Cookbook Over 50 recipes towards optimal Java Software Engineering with Maven 3 These techniques have been around for more than a decade and are well-known by practitioners of software engineering. The benefits, trade-offs, and pros and cons of these practices are well-known and will only need little mentioning. These practices are not inter-dependent, but some of them are inter-related in the larger scheme of things. One such example would be the relation between project modularization and dependency management. While nothing stops either from being implemented in isolation, they are more beneficial when implemented together. These techniques can be further supplemented by the industry's best practices such as continuous integration, maintaining centralized repositories, source code integration, and so on. Our focus here will be on steadily understanding these software engineering techniques within the context of Maven projects and we will look at practical ways to implement and integrate them. Build automation Build automation is the scripting of tasks that software developers have to do on a day-to-day basis. These tasks include: Compilation of source code to binary code Packaging of binary code Running tests Deployment to remote systems Creation of documentation and release notes Build automation offers a range of benefits including speeding up of builds, elimination of bad builds, standardization in teams and organizations, increased efficiency, and improvements in product quality. Today, it is considered as an absolute essential for software engineering practitioners. Getting ready You need to have a Maven project ready. If you don't have one, run the following in the command line to create a simple Java project: $ mvn archetype:generate -DgroupId=net.srirangan.packt.maven -DartifactId=MySampleApp How to do it... The archetype:generate command would have generated a sample Apache Maven project for us. If we choose the maven-archetype-quickstart archetype from the list, our project structure would look similar to the following: └───src ├───main │ └───java │ └───net │ └───srirangan │ └───packt │ └───maven └───test └───java └───net └───srirangan └───packt └───maven In every Apache Maven project, including the one we just generated, the build is pre-automated following the default build lifecycle. Follow the steps given next to validate the same: Start the command-line terminal and navigate to the root of the Maven project. Try running the following commands in serial order: $ mvn validate ... $ mvn compile ... $ mvn package ... $ mvn test ... You just triggered some of the phases of the build life cycle by individual commands. Maven lets you automate the running of all the phases in the correct order. Just execute the following command, mvn install, and it will encapsulate much of the default build lifecycle including compiling, testing, packaging, and installing the artifact in the local repository. How it works... For every Apache Maven project, regardless of the packaging type, the default build lifecycle is applied and the build is automated. As we just witnessed, the default build lifecycle consists of phases that can be executed from the command-line terminal. These phases are: Validate: Validates that all project information is available and correct Compile: Compiles the source code Test: Runs unit tests within a suitable framework Package: Packages the compiled code in its distribution format Integration-test: Processes the package in the integration test environment Verify: Runs checks to verify if the package is valid Install: Installs the package in the local repository Deploy: Installs the final package in a remote repository Each of the build lifecycle phases is a Maven plugin. When you execute them for the first time, Apache Maven will download the plugin from the default online Maven Central Repository that can be found at http://repo1.maven.org/maven2 and will install it in your local Apache Maven repository. This ensures that build automation is always set up in a consistent manner for everyone in the team, while the specifics and internals of the build are abstracted out. Maven build automation also pushes for standardization among different projects within an organization, as the commands to execute build phases remain the same. Project modularization Considering that you're building a large enterprise application, it will need to interact with a legacy database, work with existing services, provide a modern web and device capable user interface, and expose APIs for other applications to consume. It does make sense to split this rather large project into subprojects or modules. Apache Maven provides impeccable support for such a project organization through Apache Maven Multi-modular projects. Multi-modular projects consist of a "Parent Project" which contains "Child Projects" or "Modules". The parent project's POM file contains references to all these sub-modules. Each module can be of a different type, with a different packaging value. Getting ready We begin by creating the parent project. Remember to set the value of packaging to pom, as highlighted in the following code: <?xml version="1.0" encoding="UTF-8"?> <project xsi_schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>net.srirangan.packt.maven</groupId> <artifactId>TestModularApp</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <name>MyLargeModularApp</name> </project> This is the base parent POM file for our project MyLargeModularApp. It doesn't contain any sub-modules for now. How to do it... To create your first sub-module, start the command-line terminal, navigate to the parent POM directory, and run the following command: $ mvn archetype:generate This will display a list of archetypes for you to select. You can pick archetype number 101, maven-archetype-quickstart, which generates a basic Java project. The archetype:generate command also requires you to fill in the Apache Maven project co-ordinates including the project groupId, artifactId, package, and version. After project generation, inspect the POM file of the original parent project. You will find the following block added: <modules> <module>moduleJar</module> </modules> The sub-module we created has been automatically added in the parent POM. It simply works—no intervention required! We now create another sub-module, this time a Maven web application by running the following in the command line: $ mvn archetype:generate -DarchetypeArtifactId=maven-archetype- webapp Let's have another look at the parent POM file; we should see both the sub-modules included: <modules> <module>moduleJar</module> <module>moduleWar</module> </modules> Our overall project structure should look like this: MyLargeModularApp ├───MyModuleJar │ └───src │ ├───main │ │ └───java │ │ └───net │ │ └───srirangan │ │ └───packt │ │ └───maven │ └───test │ └───java │ └───net │ └───srirangan │ └───packt │ └───maven └───MyModuleWar └───src └───main ├───resources └───webapp └───WEB-INF How it works... Compiling and installing both sub-modules (in the correct order in case sub-modules are interdependent) is essential. It can be done in the command line by navigating to the parent POM folder and running the following command: $ mvn clean install Thus, executing build phase on the parent project automatically gets executed for all its child projects in the correct order. You should get an output similar to: ------------------------------------------------------------------ [INFO] Reactor Summary: [INFO] MyLargeModularApp ........................ SUCCESS [0.439s] [INFO] MyModuleJar .............................. SUCCESS [3.047s] [INFO] MyModuleWar Maven Webapp ................. SUCCESS [0.947s] ------------------------------------------------------------------ [INFO] BUILD SUCCESS ------------------------------------------------------------------ Dependency management Dependency management can be universally acknowledged as one of the best features of Apache Maven. In Multi-modular projects, where dependencies can run into tens or even hundreds, Apache Maven excels in allowing you to retain a high degree of control and stability. Apache Maven dependencies are transient, which means Maven will automatically discover artifacts that your dependencies require. This feature has been available since Maven 2, and it especially comes in handy for many of the open source project dependencies we have in today's enterprise projects. Getting ready Maven dependencies have six possible scopes: Compile: This is the default scope. Compile dependencies are available in the classpaths. Provided: This scope assumes that the JDK or the environment provides dependencies at runtime. Runtime: Dependencies that are required at runtime and are specified in the runtime classpaths. Test: Dependencies required for test compilation and execution. System: Dependency is always available, but the JAR is provided nonetheless. Import: Imports dependencies specified in POM included via the <dependencyManagement/> element. How to do it... Dependencies for Apache Maven projects are described in project POM files. While we take a closer look at these in the How it works... section of this recipe, here we will explore the Apache Maven dependency plugin. According to http://maven.apache.org/plugins/maven-dependency-plugin/: "The dependency plugin provides the capability to manipulate artifacts. It can copy and/or unpack artifacts from local or remote repositories to a specified location." It's a decent little plugin and provides us with a number of very useful goals. They are as follows: $ mvn dependency:analyze Analyzes dependencies (used, unused, declared, undeclared) $ mvn dependency:analyze-duplicate Determines duplicate dependencies $ mvn dependency:resolve Resolves all dependencies $ mvn dependency:resolve-plugin Resolves all plugins $ mvn dependency:tree Displays dependency trees How it works... Most Apache Maven projects have dependencies to other artifacts (that is, other projects, libraries, and tools). Management of dependencies and their seamless integration is one of Apache Maven's strongest features. These dependencies for a Maven project are specified in the project's POM file. <dependencies> <dependency> <groupId>...</groupId> <artifactId>...</artifactId> <version>...</version> <scope>...</scope> </dependency> </dependencies> In Multi-modular projects, dependencies can be defined in the parent POM files and can be subsequently inherited by child POM files as and when required. Having a single source for all dependency definitions makes dependency versioning simpler, thus keeping large projects' dependencies organized and manageable over time. The following is an example to show a Multi-modular project having a MySQL dependency. The parent POM would contain the complete definition of the dependency: <dependencyManagement> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.2</version> </dependency> <dependencies> </dependencyManagement> All child modules that require MySQL would only include a stub dependency definition: <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> There will be no version conflicts between multiple child modules having the same dependencies. The dependencies scope and type are defaulted to compile and JAR. However, they can be overridden as required: <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> <scope>test</scope> </dependency> <dependency> <groupId>...</groupId> <artifactId>...</artifactId> <version>...</version> <type>war</type> </dependency> There's more... System dependencies are not looked for in the repository. For them, we need to specify the path to the JAR: <dependencies> <dependency> <groupId>sun.jdk</groupId> <artifactId>tools</artifactId> <version>1.5.0</version> <scope>system</scope> <systemPath>${java.home}/../lib/tools.jar</systemPath> </dependency> </dependencies> However, avoiding the use of system dependencies is strongly recommended because it kills the whole purpose of Apache Maven dependency management in the first place. Ideally, a developer should be able to clone code out of the SCM and run Apache Maven commands. After that, it should be the responsibility of Apache Maven to take care of including all dependencies. System dependencies would force the developer to take extra steps and that dilutes the effectiveness of Apache Maven in your team environment.
Read more
  • 0
  • 0
  • 44521
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-integrating-scala-groovy-and-flex-development-apache-maven
Packt
23 Aug 2011
8 min read
Save for later

Integrating Scala, Groovy, and Flex Development with Apache Maven

Packt
23 Aug 2011
8 min read
Apache Maven 3 Cookbook Over 50 recipes towards optimal Java Software Engineering with Maven 3         Java has been the dominant enterprise programming platform for over a decade and a half. In many ways, it has shaped the way the industry does business, especially with the advent of the Internet and followed by cloud computing. It is very evolved and mature, and has good infrastructure support. For all its successes, however, it has some serious problems competing with modern dynamic programming languages in the context of ease of programming, especially while getting started in the initial stages of a project. An advantage that Java traditionally enjoyed over the likes of Python, Ruby, and so on is that a lot of enterprises were committed to Java Virtual Machine (JVM) as their platform due to its inherent advantages. This always worked in favor of the Java programming language. However, all this has changed with modern languages such as Scala, Groovy, and so on supporting JVM bytecode, which made them compatible with existing enterprise infrastructure and assets. Furthermore, RIA (Rich Internet Applications) technology, such as Flex, never faced the JVM challenge in the first place due to the widespread adoption of the Flash Player. Apache Maven's flexible plugin-based architecture allows the tools to evolve with time and lends its benefits to developers and development teams that are keen to leverage this new breed of modern programming languages. Integrating Scala development with Maven Scala stands for "Scalable Language". It is defined as a multi-paradigm programming language and has integrated support for object-oriented programming and functional programming. It runs on the JVM and on Android. Furthermore, it can read existing Java libraries which give it a huge advantage in cases where there is a lot of existing code infrastructure in Java. The Scala bytecode is in many ways, identical to the Java bytecode. In many cases, Scala generates more optimal byte-code than Java. Twitter, Foursquare, and a whole bunch of exciting software startups have adopted Scala. Scala helped Twitter get over its scalability issues when the micro blogging pioneer first hit the mainstream and needed to scale-up as it served millions of new users each day This is, of course, not to say that scalable applications can't be built in pure Java. However, the Scala programming language features itself (such as pattern matching, concurrency, and Actors) and frameworks built on top of Scala (for example, Akka, GridGain, and so on.) allow application scalability with ease. Below is an example of a popular sorting algorithm implemented in Scala: def qsort: List[Int] => List[Int] = { case Nil => Nil case pivot :: tail => val (smaller, rest) = tail.partition(_ < pivot) qsort(smaller) ::: pivot :: qsort(rest) } The creator of Scala, Martin Odersky, has given a number of popular talks and presentations examining Scala's comparability. When Scala code is up against comparable code in other programming languages including Java, C#, Ruby, and so on, the conciseness of Scala really stands out. The Scala implementation of quicksort in the preceding code demonstrates this very conciseness of Scala code. While the Scala community recommends SBT (Simple Built Tool) for pure Scala projects, often you'll be implementing modules in Scala while other modules of the project would have been built with Java. This is one of the strongest cases for using Maven in a multi-modular project with Java and Scala-based modules. It is probably the reason why SBT is more or less compatible with Maven's conventions and even provides a feature for "Mavenizing" an existing SBT project. Getting ready You'll need Apache Maven installed. The Maven version preferably should be Maven 3 but Maven 2.0.7 or higher is supported. JDK 1.5 or higher is recommended. Do note, installation of Scala is not required. Apache Maven will take care of the Scala dependency. How to do it... Generate the Scala project archetype: $ mvn archetype:generate This will show a list of available archetypes in which you need to select the archetype for a simple Scala project, which is scala-archetype-simple. Maven interactive mode will also ask you for archetype version, groupId, artifactId, and other Maven project coordinates. This is the same step we've encountered in previous recipes. You can choose reasonable values for groupId, artifactId, and package. For me, the groupId was net.srirangan.packt.maven, artifactId was scalaexample, version was the default value, and package was the same as groupId. On completion, your terminal will look similar to the following lines: [INFO] ------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------ [INFO] Total time: 1:38.142s [INFO] Final Memory: 10M/114M [INFO] ------------------------------------------------------------ The completion of this operation has created a project folder with the same name as the project artifact ID. The project directory tree structure would look similar to this: Folder PATH listing for volume OS Volume serial number is 7C69-DF5D C:. └───src ├───main │ └───scala │ └───net │ └───srirangan │ └───packt │ └───maven │ └───App.scala └───test └───scala └───samples └───junit.scala └───scalatest.scala └───specs.scala Also generated is a simple Hello World! Scala application–App.scala: package net.srirangan.packt.maven object App { def foo(x : Array[String]) = x.foldLeft("")((a,b) => a + b) def main(args : Array[String]) { println( "Hello World!" ) println("concat arguments = " + foo(args)) } } The pom.xml file is configured in a way that integrated the build lifecycle with the Maven Scala plugin: <build> <plugins> <plugin> <groupId>org.scala-tools</groupId> <artifactId>maven-scala-plugin</artifactId> <executions> <execution> <goals> <goal>compile</goal> <goal>testCompile</goal> </goals> </execution> </executions> ... </plugin> </plugins> </build> To compile the project, run: $ mvn compile To run the tests, use the default project lifecycle command: $ mvn test How it works… If you inspect the Scala project pom.xml file that was generated, you would see dependencies defined for Scala: library, testing, specs, and scalatest. <dependencies> <dependency> <groupId>org.scala-lang</groupId> <artifactId>scala-library</artifactId> <version>2.9.0-1 </version> </dependency> <dependency> <groupId>org.scala-tools.testing</groupId> <artifactId>specs_2.9.0-1</artifactId> <version>1.6.5</version> <scope>test</scope> </dependency> <dependency> <groupId>org.scalatest</groupId> <artifactId>scalatest</artifactId> <version>1.2</version> <scope>test</scope> </dependency> </dependencies> The first dependency listed here is the Scala programming language itself, that is, org. scala-lang.scala-library. The other two dependencies are for running Scala tests. There may also be a fourth dependency which is not listed in the preceding code for I. It is unrelated to Scala. Looking at the build settings and plugin configuration hereafter, we see that the source and test directories are being set to src/main/scala and src/test/scala respectively. The plugin execution is being bound to the compile and testCompile build phases. <build> <sourceDirectory>src/main/scala</sourceDirectory> <testSourceDirectory>src/test/scala</testSourceDirectory> <plugins> <plugin> <groupId>org.scala-tools</groupId> <artifactId>maven-scala-plugin</artifactId> <version>2.15.0</version> <executions> <execution> <goals> <goal>compile</goal> <goal>testCompile</goal> </goals> <configuration> <args> <arg>-make:transitive</arg> <arg>-dependencyfile</arg> <arg>${project.build.directory}/.scala_dependencies</ arg> </args> </configuration> </execution> </executions> </plugin> ... </plugins> </build> There's more… In addition to what was described up to now, the Maven Scala plugin has more features which meet the needs of most developers and development situations. The following table lists all goals made available by the Maven Scala plugin, their respective Apache Maven console commands, and brief explanations:   Goal Maven command Details scala:compile $ mvn scala:compile Compiles the Scala source directory scala:console $ mvn scala:console Launches the Scala REPL with all project dependencies made available scala:doc $ mvn scala:doc Generates the documentation for all Scala sources scala:help $ mvn scala:help Displays the Scala compiler help scala:run $ mvn scala:run Executes a Scala class scala:script $ mvn scala:script Executes a Scala script scala:testCompile $mvn scala:testCompile Compiles the Scala test sources
Read more
  • 0
  • 0
  • 2526

article-image-oracle-e-business-suite-entering-and-reconciling-bank-statements
Packt
23 Aug 2011
4 min read
Save for later

Oracle E-Business Suite: Entering and Reconciling Bank Statements

Packt
23 Aug 2011
4 min read
Oracle E-Business Suite 12 Financials Cookbook Take the hard work out of your daily interactions with E-Business Suite financials by using the 50+ recipes from this cookbook. Entering bank statements Bank statements are downloaded from the bank to a local directory. Once the file is received, the bank account balance and statement information can be loaded into the bank statement open interface tables, using the bank statement loader program or a custom loader program. The files can also be loaded automatically using an interface program or using the XML Gateway. Bank statements can also be entered manually. In this recipe, we will look at how to enter bank statements. Getting ready The bank statement shown next has been loaded into the open interface table: Let's review the transactions in the open interface: Select the Cash Management responsibility. Navigate to Bank Statements | Bank Statement Interface Lines. Select 95-6891-3074 in the Account field. Click on the Lines button to view the transactions in the interface tables. How to do it... Let's list the steps required to automatically enter the bank statements from the import and AutoReconciliation program: Select the Cash Management responsibility. Navigate to Other | Programs | Run, or select View | Requests from the menu. Click on the Submit a New Request button. Select Single Request from the Options. Click on the OK button. In the Submit Request form, select Bank Statement Import & AutoReconciliation from the list of values. Please note that we could run the Bank Statement Import program, to run only the import. Select the Parameters field, and select Kings Cross as the Bank Branch Name, select 95-6891-3074 as the Bank Account Number, and select 20110314-0001 as the parameter for the Statement Number From and the Statement Number To fields. Accept the default values for the remaining fields. Click on the OK button. We can schedule the program to run periodically, for example, every day. Click on the Submit button to submit the request. Let's review the imported bank statements: Navigate to Bank Statement | Bank Statements and Reconciliation. The imported statement is displayed. Click on the Review button. (Move the mouse over the image to enlarge it.) In the Bank Statement window, select the Lines button. The imported lines are displayed. How it works... Bank statements can be imported automatically, using a SQL*Loader script against the bank file to populate the bank statement open interface. The bank statement information is then imported into the Bank Statement windows using the Bank Statement Import program. There's more... Now, let's look at how to enter statements manually. Entering bank statements manually Let's enter the bank statement for the 15th of March manually. The lines on the statement are as follows: Payment of 213.80. Receipt of 3,389.89 from A.C. Networks. Credit of 7,500.00 for Non Sufficient Funds for the receipt from Advantage Corp. Bank Transfer payment of 1,000.00. Select the Cash Management responsibility. Navigate to Bank Statement | Bank Statements and Reconciliation. (Move the mouse over the image to enlarge it.) In the Reconcile Bank Statements window, click on the New button. In the Account Number field, enter 95-6891-3074, the other details are automatically entered. In the Date field enter 15-MAR-2011. In the Statement Number field enter 20110314-0002. In the Control Totals region, let's enter control totals based on our bank statement. The Opening Balance of 125,727.21 is entered based on the previous opening balance. In the Receipts field, enter 3,389.89 and 1 in the Lines field. In the Payments field, enter 8,713.80 and 3 in the Lines field. The Closing Balance of 98,495.56 is entered automatically. Let's enter the bank statement lines: Click on the Lines button. (Move the mouse over the image to enlarge it.) In the Bank Statements Lines form, enter 1 in the Line field. Select Payment as the Type. Enter 100 as the code. In the Transaction Date field, enter 15-MAR-2011. In the Amount field, enter 213.80. Select the next line, and enter 2 in the Line field. Select Receipt as the Type. Enter 200 as the code. In the Transaction Date field, enter 15-MAR-2011. In the Amount field, enter 3,389.89. Select the Reference tab, and enter A.C. Networks. Select the next line, and enter 3 in the Line field. Select NSF as the Type. Enter 500 as the code. In the Transaction Date field, enter 15-MAR-2011. In the Amount field, enter 7,500.00. Select the Reference tab, and enter Advantage Corp. Select the next line, and enter 4 in the Line field. Select Payment as the Type. Enter 140 as the code. In the Transaction Date field, enter 15-MAR-2011. In the Amount field, enter 1,000.00. Save the record.
Read more
  • 0
  • 0
  • 5218

article-image-magento-14-theming-making-our-theme-shine
Packt
23 Aug 2011
8 min read
Save for later

Magento 1.4 Theming: Making Our Theme Shine

Packt
23 Aug 2011
8 min read
  Magento 1.4 Theming Cookbook Over 40 recipes to create a fully functional, feature rich, customized Magento theme         Read more about this book       (For more resources on this subject, see here.) Looks quite interesting, doesn't it? Let's get started! Introduction You will find all the necessary code in the code bundle; however, some JavaScript libraries won't be included. Don't worry, they are very easy to find and download! Using Cufón to include any font we like in our theme This technique, which allows us to use any font we like in our site, is quite common these days, and is very, very useful. Years ago, if we wanted to include some uncommon font in our design, we could only do it by using a substitutive image. Nowadays, we have many options, such as some PHP extensions, @font-face, Flash (sIFR), and, of course, Cufón. And that last option is the one we are about to use. Getting ready If you would like to copy the code, instead of writing it, remember you can find all the necessary code in the code bundle in Chapter 5, recipe 1. How to do it... Ready to start this first recipe? Let's go: First we have to decide which font to use; this is totally up to you. In this example I'm going to use this one: http://www.dafont.com/aldo.font. It's a free font, and looks very good! Thanks to Sacha Rein. Just download it or find any other font of your liking. Now we need to use the Cufón generator in order to create the font package. We will go to this URL: http://cufon.shoqolate.com/generate/. There we will be able to see something similar to the following screenshot: On that screen we only have to follow all the instructions and click on the Let's do this button: This will create a file called Aldo_600.font.js, which will be the one we will be using in this example. But we also need something more, the Cufón library. Download it by clicking the Download button: After downloading the Cufón library, we will download a file called cufon-yui.js. We now have all the necessary tools. It's time to make use of them. First place cufon-yui.js and Aldo_600.font.js inside skin/frontend/default/rafael/js. Now we need to edit our layout file. Let's open: app/design/frontend/default/rafael/layout/page.xml. Once we have this file opened we are going to look for this piece of code: <action method="addCss"><stylesheet>css/960_24_col.css</stylesheet></action> <action method="addCss"><stylesheet>css/styles.css</stylesheet></action> And just below it we are going to add the following: <action method="addJs"><script>../skin/frontend/default/rafael/js/cufon-yui.js</script></action> <action method="addJs"><script>../skin/frontend/default/rafael/js/Aldo_600.font.js</script></action> See, we are adding our two JavaScript files. The path is relative to Magento's root JavaScript folder. With this done, our theme will load these two JS files. Now we are going to make use of them. Just open app/design/frontend/default/rafael/template/page/2columns-right.phtml. At the bottom of this file we are going to add the following code: <script type="text/javascript"> Cufon.replace('h1'); </script></body></html> And that's all we need. Check the difference! Before we had something like the following: And now we have this: Every h1 tag of our site will now use our Aldo font, or any other font of your liking. The possibilities are endless! How it works... This recipe was quite easy, but full of possibilities. We first downloaded the necessary JavaScript files, and then made use of them with Magento's add JS layout tag. Later we were able to use the libraries in our template as in any other HTML file. SlideDeck content slider Sometimes our home page is crowded with info, and we still need to place more and more things. A great way of doing so is using sliders. And the SlideDeck one offers a very configurable one. In this recipe we are going to see how to add it to our Magento theme. You shouldn't miss this recipe! How to do it... Making use of the slider in our theme is quite simple, let's see: First we need to go to http://www.slidedeck.com/ and download SlideDeck Lite, as we will be using the Lite version in this recipe. Once downloaded we will end up with a file called slidedeck-1.2.1-litewordpress-1.3.6.zip. Unzip it. Go to skin/frontend/default/rafael/css and place the following files in it: slidedeck.skin.css slidedeck.skin.ie.css back.png corner.png slides.png spines.png Next, place the following files in skin/frontend/default/rafael/js: jquery-1.3.2.min.js slidedeck.jquery.lite.pack.js Good, now everything is in place. Next, open: app/design/frontend/default/rafael/layout/page.xml. Now look for the following piece of code: <block type="page/html_head" name="head" as="head"> <action method="addJs"><script>prototype/prototype.js</script></action> <action method="addJs" ifconfig="dev/js/deprecation"><script>prototype/deprecation.js</script></action> <action method="addJs"><script>lib/ccard.js</script></action> Place the jQuery load tag just before the prototype one, so we have no conflict between libraries: <block type="page/html_head" name="head" as="head"> <action method="addJs"><script>../skin/frontend/default/rafael/js/jquery-1.3.2.min.js</script></action> <action method="addJs"><script>prototype/prototype.js</script></action> <action method="addJs" ifconfig="dev/js/deprecation"><script>prototype/deprecation.js</script></action> Also add the following code before the closing of the block: <action method="addCss"><stylesheet>css/slidedeck.skin.css</stylesheet></action><action method="addCss"><stylesheet>css/slidedeck.skin.ie.css</stylesheet></action><action method="addJs"><script>../skin/frontend/default/rafael/js/slidedeck.jquery.lite.pack.js</script></action> The following steps require us to log in to the administrator panel. Just go to: http://127.0.0.1/magento/index.php/admin. Now to CMS/Pages, open the home page one: Once inside, go to the Content tab. Click on Show/Hide editor. Find the following code: <div class="grid_18"> <a href="#"><img src="{{skin url='img_products/big_banner.jpg'}}" alt="Big banner" title="Big banner" /></a> </div><!-- Big banner → And replace it with the following: <div class="grid_18"> <style type="text/css"> #slidedeck_frame { width: 610px; height: 300px; } </style> <div id="slidedeck_frame" class="skin-slidedeck"> <dl class="slidedeck"> <dt>Slide 1</dt> <dd>Sample slide content</dd> <dt>Slide 2</dt> <dd>Sample slide content</dd> </dl> </div> <script type="text/javascript"> jQuery(document).ready(function($) { $('.slidedeck').slidedeck(); }); </script> <!-- Help support SlideDeck! Place this noscript tag onyour page when you deploy a SlideDeck to provide a link back! --> <noscript> <p>Powered By <a href="http://www.slidedeck.com"title="Visit SlideDeck.com">SlideDeck</a></p> </noscript></div><!-- Big banner → Save the page and reload the frontend. Our front page should have a slider just like the one seen in the following screenshot: And we are done! Remember you can place any content you want inside these tags: <dl class="slidedeck"> <dt>Slide 1</dt> <dd>Sample slide content</dd> <dt>Slide 2</dt> <dd>Sample slide content</dd> </dl> How it works... This recipe is also quite easy. We only need to load the necessary JavaScript files and edit the content of the home page, in order to add the necessary code.
Read more
  • 0
  • 0
  • 2274

article-image-oracle-e-business-suite-adjusting-items-inventory-and-classifying-items
Packt
19 Aug 2011
4 min read
Save for later

Oracle E-Business Suite: Adjusting Items in Inventory and Classifying Items

Packt
19 Aug 2011
4 min read
Oracle E-Business Suite 12 Financials Cookbook Adjusting Items in Inventory Item quantities can be adjusted in Inventory. In this recipe, we will use miscellaneous transactions to adjust Items. Let's try to enter transactions on some of the controls we have set up. We will try and enter a Miscellaneous Transaction for five paper widgets into Inventory. How to do it... Navigate to Transactions | Miscellaneous Transactions. In the Type field, select Miscellaneous receipt from the list of values. Click on the Transaction Lines button to enter the receipt. Search for the PRD20001 Item in the Item field. Select the Subinventory list of values and the field should be automatically populated with ACME-FG. In the Locator field, enter A1.1.2. The system should display an Error message to indicate that an invalid locator has been entered. Click on OK and enter A1.1.1–the system should accept this value. Enter a value of 5 in the Quantity field. In the account field, enter 01-000-1410-0000-000. This is the account that will be charged for the Inventory transaction. Select the Lot / Serial button. Enter the Lot number–LN10001. The expiration date is generated based on the setting in the Item definition. Enter the quantity of 5. Click on the Serial button. Enter SN10001 in the Start Serial Number field and press Tab on the keyboard. The SN10005 should be automatically populated in the End Serial Number field. Click on the Done button. Click on the Done button again in the next screen. Save the record. There's more... Let's search for the Items in Inventory. Searching for Items We will use the material workbench to search for the Items: Navigate to On-hand | Availability | On-hand Quantity. Enter PRD20001 in the Item / Revision field. Click on the Find button. Expand the Organizations tree to show LN10001. Review the Item details. Close the form. Classifying Items Items are grouped into logical classifications through categories. Categories can be further grouped into category sets. A default category set can be assigned to a functional area. When an Item is created, it is automatically added to the default category set. The groupings are mainly used for reporting purposes. Let's look at how to classify Items using categories. How to do it... Let's list the steps required to create category codes: Navigate to Setup | Items | Categories | Category Codes. Click on the New button to enter the Category. In the Structure Name, select Item Categories. In the Category field, enter BOOKS.MISC. In the Description field, enter Other Books. Save the record. Let's now create the Category Set, add the Category Codes to a new set called ACME Books, and assign it to the PRD20001 Item: Navigate to Setup | Items | Categories | Category Sets. Click on the New button to enter the category set. In the Name field, enter ACME Books. Enter a description, for example, ACME Paper Books. Select Item Categories for Flex Structure. Select Controlled At as the Org level. Enter BOOKS.MISC as the Default Category. Select the checkbox Allow Multiple Item Category Assignments. Add the following Category Codes to the list: BOOKS.MISC BOOKS.NEW BOOKS.USED Save the record. Let's now assign the categories to the PRD20001 Item: Navigate to Items | Organization Items. From the Menu, select Tools and then Categories. Select ACME Books in the Category Set. Enter BOOKS.NEW in the Category field. Save the record. How it works... The structure of the Item category is defined in the Item Flexfield structure and the values are held in the individual Value Sets. The combination of the individual values forms the category code. For example, the structure we used previously is made of two segments, defined in the Flexfield structure. The segments are Family and Class. BOOKS is a value in Family and MISC, NEW, and USED are individual values in Class.
Read more
  • 0
  • 0
  • 8920
article-image-oracle-e-business-suite-creating-bank-accounts-and-cash-forecasts
Packt
19 Aug 2011
3 min read
Save for later

Oracle E-Business Suite: Creating Bank Accounts and Cash Forecasts

Packt
19 Aug 2011
3 min read
  Oracle E-Business Suite 12 Financials Cookbook Take the hard work out of your daily interactions with E-Business Suite financials by using the 50+ recipes from this cookbook   Introduction Oracle E-business suite The liquidity of an organization is managed in Oracle Cash Management; this includes the reconciliation of the cashbook to the bank statements, and forecasting future cash requirements. In this article, we will look at how to create bank accounts and cash forecasts. Cash management integrates with Payables, Receivables, Payroll, Treasury, and General Ledger. Let's start by looking at the cash management process: The Bank generates statements. The statements are sent to the organization electronically or by post. The Treasury Administrator loads and verifies the bank statement into cash management. The statements can also be manually entered into cash management. The loaded statements are reconciled to the cash book transactions. The results are reviewed, and amended if required. The Treasury Administrator creates the journals for transactions in the General Ledger. Creating bank accounts Oracle Cash Management provides us with the functionality to create bank accounts. In this recipe, we will create a bank account for a bank called Shepherd Bank, for one of their branches called Kings Cross branch. Getting ready Log in to Oracle E-Business Suite R12 with the username and password assigned to you by the system administrator. If you are working on the Vision demonstration database, you can use OPERATIONS/WELCOME as the USERNAME/PASSWORD. We also need to create a bank before we can create the bank account. Let's look at how to create a bank and the branch: Select the Cash Management responsibility. Navigate to Setup | Banks | Banks.(Move the mouse over the image to enlarge it.) In the Banks tab, click on the Create button. Select the Create new bank option. In the Country field, enter United States. In the Bank Name field, enter Shepherds Bank. In the Bank Number field, enter JN316. Click on the Finish button. Let's create the branch and the address: (Move the mouse over the image to enlarge it.) Click the Create Branch icon: The Country and the Bank Name are automatically entered. Click on the Continue button.(Move the mouse over the image to enlarge it.) In the Branch Name field, enter Kings Cross. Select ABA as the Branch Type. Click on the Save and Next button to create the Branch address.(Move the mouse over the image to enlarge it.) In the Branch Address form, click on the create button. In the Country field, enter United States. In the Address Line 1 field, enter 4234 Red Eagle Road. In the City field, enter Sacred Heart. In the County field, enter Renville. In the State field, enter MN. In the Postal Code field, enter 56285. Ensure that the Status field is Active. Click on the Apply button. Click on the Finish button.
Read more
  • 0
  • 0
  • 6802

article-image-flash-player-applications-html-template-facebook-integration
Packt
18 Aug 2011
6 min read
Save for later

Flash Player Application's HTML Template for Facebook Integration

Packt
18 Aug 2011
6 min read
  Flash Facebook Cookbook Over 100 recipes for integrating the Flash Platform applications with the Graph API and Facebook.         Read more about this book       (For more resources on this subject, see here.) The reader will be benefit from referring the previous article on Getting Started with Flash and Facebook. The Facebook JavaScript SDK is what makes it possible for our Flash Player application to obtain details of any active Facebook sessions, and it allows our application to perform actions such as prompting for authentication or requesting additional permissions. Getting ready For our Flash Player application to integrate with Facebook, we will need some form of HTTP server, so that we can run our application from an http://-based URL, rather than simply launching a file from a local folder on your computer. Ideally we need a live, publicly-accessible domain under our control, and we'll configure our Facebook Application to use pages on that domain as the basis for our Canvas and Tab applications. In addition, if we can, it would be most efficient (but not essential) to have an HTTP server set up on our local machine—allowing us to test and debug our Flash Player applications locally, without having to re-upload files to a remote site every time we need to test new functionality. How to do it... The first thing we'll need is a web-based Flash Player application, which we can get by specifying Web (runs in Adobe Flash Player) when we create our Flex project: Open the folder in your project named html-template. If that folder doesn't exist, open your project settings, and make sure that the option Generate HTML wrapper file under the Flex compiler section is checked. The first change we're going to make to our file is to import the Facebook JavaScript SDK. Into the head section of the HTML page (between the opening <head> and closing </head> tags) add the following code: <script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script> This script tag imports the JavaScript SDK into our HTML page, but to activate it we need to add a specific HTML element—a div element with a specific ID. Jump to the bottom of the page, before the penultimate closing tag, </body>, and add a new DIV element, with the ID of fb-root: <div id="fb-root"></div> With these additions, our final HTML code for the entire page template should be similar to this (with our additions to the HTML highlighted): <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><!-- saved from url=(0014)about:internet --><html lang="en" xml:lang="en"> <head> <title>${title}</title> <style type="text/css" media="screen"> html, body { height:100%; } body { margin:0; padding:0; overflow:auto; text-align:center; background-color: ${bgcolor}; } #flashContent { display:none; } </style> <script type="text/javascript" src="swfobject.js"></script> <script type="text/javascript"> var swfVersionStr = "${version_major}.${version_minor}.${version_revision}"; var xiSwfUrlStr = "${expressInstallSwf}"; var flashvars = {}; var params = {}; params.quality = "high"; params.bgcolor = "${bgcolor}"; params.allowscriptaccess = "sameDomain"; params.allowfullscreen = "true"; var attributes = {}; attributes.id = "${application}"; attributes.name = "${application}"; attributes.align = "middle"; swfobject.embedSWF( "${swf}.swf", "flashContent", "${width}", "${height}", swfVersionStr, xiSwfUrlStr, flashvars, params, attributes); swfobject.createCSS("#flashContent", "display:block;text-align:left;"); </script> <script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script> </head> <body> <div id="flashContent"> <p>To view this page ensure that Adobe Flash Player version ${version_major}.${version_minor}.${version_revision} or greater is installed.</p> </div> <div id="fb-root"> </div> </body></html> These additions are all we need to attempt communication with the Graph API from a technical point of view, but before our API requests are successful, we must make sure that our application is configured correctly on Facebook.com. Open the Facebook Developer center, from the URL: http://www.facebook.com/developers/apps.php Edit our existing application, and switch the Web Site tab, which contains two key fields—Site URL and Site Domain: Our Site URL will be the location of our application when we upload it to a publicly-accessible HTTP server, and should be expressed as an URL (starting with http://). The Site Domain (expressed without the http:// prefix) allows us to control the domain and subdomains that are allowed to access the Graph API, while identifying as our application. Once this property is set, only requests that appear to come from that specified URL (or part URL) will be allowed to make requests, and all others will be summarily rejected by the Graph API with the error message: Given URL is not allowed by the Application configuration. Change the Site URL property to point at our Flash application's live location, such as: http://facebook.psyked.co.uk/packt/. Change the Site Domain property so that it lists the main domain of our application's live location, for example: psyked.co.uk. Now, with the Site's URL and Domain settings established, our next step should be to upload our application and its HTML files to the location we've specified in the Site URL field. Once those files are uploaded and available from the domain we specified in the Site Domain field, we should see no more of those Given URL is not allowed... errors. Finally, to test our application we will need to upload our HTML and SWF files to a live web server—one that is able to serve up our application's HTML file from within the domain that we specified in the Site Domain setting in the Facebook Developer center. For example, http://psyked.co.uk/packt/Facebook.html.  
Read more
  • 0
  • 0
  • 1460

article-image-getting-started-flash-and-facebook
Packt
18 Aug 2011
10 min read
Save for later

Getting Started with Flash and Facebook

Packt
18 Aug 2011
10 min read
  Flash Facebook Cookbook Over 100 recipes for integrating the Flash Platform applications with the Graph API and Facebook. Introduction All third-party systems that work with data from Facebook do so through the Facebook API, which is a combination of REST-style techniques, OAuth 2.0, and an ever-evolving combination of web technologies, collectively titled by Facebook as the Graph API. Facebook provides developers with a number of different code libraries through its developer portal, and of these the only one that's completely client-side is the JavaScript SDK. But anything that JavaScript can do can be done by both ActionScript 3 and the Flash Platform, more or less. You might think, having looked at the SDKs officially listed by Facebook in their developer portal, that you'd need to build a code library yourself but luckily for us, there's already an existing, officially supported, ActionScript 3 library for working with the Graph API. This library, the Facebook ActionScript 3 SDK, is supported by both Adobe and Facebook, so you can be assured that it will be kept up-to-date and fully functional, even if there is a significant overhaul of the Facebook APIs—after all, who better to support this SDK than Adobe and Facebook themselves? There's no sense in recreating the wheel, as they say, so the examples in this article will be using the existing Facebook ActionScript 3 SDK almost exclusively for its recipes. We'll also be using the Flex SDK 4.0 for our examples, as it's a quick and easy way to construct user interfaces and put together working prototypes for our recipes. However, using Flex isn't a requirement for the Facebook ActionScript 3 SDK to work—it's just for the examples in this article. Integrating the Facebook SDK with a normal ActionScript-only project or a Flash Professional-based project is entirely possible—it will just inevitably require a little more time creating the interface, but the ActionScript 3 code behind it all will work pretty much the same. Setting up a new application on Facebook To access the full range of data available from the Facebook API, you need an API key, and for that, you need to set up an application on Facebook itself. To do this you need to set up an account on Facebook, and use that account to join the Facebook developer program. Every Facebook application, whether it's based on server-side languages (like PHP), or client-side technologies (like JavaScript or ActionScript), needs an API key to send and receive data through the Facebook API. Alongside the API key, the application also gets a unique Application ID that makes it possible for Facebook to keep track of what actions a user has allowed your application to perform with their data, and an Application Secret, which is used for authentication. As well as giving you the ability to use more features of the API, setting up your Flash project as an application and promoting it through Facebook greatly improves the chance that users will discover your application organically through the social network. For example, status updates created by your application will all link back to the application's Fan Page. In this section, we're going to go through the necessary steps to register a new application on Facebook, and what we actually need is the API Key, Application ID, and an Application Secret for Flash. Getting ready You can set up your application as soon as you're registered as a developer with Facebook. To register as a developer you first need a Facebook profile. You've probably already got one, but you'll probably want to create at least one other Facebook account for development or testing purposes. I'm sure your existing Facebook friends won't appreciate a wave of "test message" spam in the near future. Once you've logged in with the Facebook account you want to use for development, go to URL: http://www.facebook.com/developers/ to add the Facebook Developer application to your profile. From the Facebook Developer center you can see the latest news from the Facebook developer blog, as well as useful links for developers (Documentation, Privacy Polices, Rules, and so on). Click on the link + Set Up New App or go to the following website address: http://www.facebook.com/developers/createapp.php to start the application setup process. How to do it... If you just want to get up and run as fast as possible, the minimal amount of data that's needed to register a new application is its name. Your application name does not need to be unique—even for yourself. It's acceptable to name two (or more!) of your applications exactly the same, as Facebook assigns every application its own unique Application ID. Good thing to, really—otherwise all the good names would likely be taken in a frantic bout of application name-squatting. There's far more information you can add, such as application icons, description, contact e-mail addresses, and support URLs—all pretty simple stuff, and you can always return to the settings screen to change or update things later on. Once you've entered your application name (and any other information you wish) save your changes and you'll get a screen containing the following information: Now that we've got ourselves an API Key, we can start using it in requests to the Facebook Graph API. We'll also need the Application ID, so make a note of that, but the Application Secret is something we don't actually need for any of the recipes covered in this article. How it works... All applications that integrate with Facebook aren't actually part of Facebook; they're an external application, and that's true for every third-party application that you might have seen appear within the Facebook interface (these are known as Canvas or Tab applications, depending on whether they're on their own page, or a Tab on another page). Technically, they are external websites that are loaded into the Facebook interface using an iframe element in HTML. Without the API Key an application can't do anything other than retrieve the information that is publicly available. All other actions—such as requesting news feeds or publishing information to Facebook—require the end user to give your application the explicit permission to perform that action, with the API Key being what the Graph API relies upon when generating access tokens and authorizing requests. Our application can request new permissions at any point, and similarly the end user can modify or reject our application permissions at any point, so generating an access token and passing it in all data requests is an easy way for Facebook to maintain the user's control over their data access. There's more... To get a broader overview of the settings that can be changed for a Facebook application, the best place to look is the Developer Documentation, which is available online on the Facebook Developer center: http://developers.facebook.com/docs/. There's no single page which gives a description of the settings, but rather the information is distributed around the pages where it's actually relevant. When we set up an application on Facebook, it also sets up a Profile Page specifically for that application—similar to a Facebook page (but not exactly the same)—and devoted to our new application. Downloading the Facebook ActionScript 3 SDK There are two ways to get the source code for the Facebook ActionScript SDK—one is simply download a precompiled version of the source code, and for that all you need is an Internet connection. The other way to obtain the source code is to download the very latest version directly from a source control repository. There are in fact two main versions of the Facebook ActionScript 3 SDK. One is the 'Official' version of the SDK, hosted in a Subversion repository on Google code, maintained and updated by teams associated with Adobe and Facebook; and the other is more of a community-driven effort, stored in a Git repository and hosted on GitHub. In this recipe and all of the recipes in this article, we will be working with a branch of the community-driven version of the Facebook ActionScript 3 SDK, rather than the 'Official' version of the SDK. Getting ready To download the SDK from Git, we need to have Git installed on your computer, which can be downloaded and installed from the URL: http://git-scm.com/. How to do it... If you have no desire to work with code which includes version-control information, both the precompiled SWC files and the raw ActionScript source code for the Facebook ActionScript 3 SDK can be downloaded from the following URLs: https://github.com/psyked/facebook-actionscript-api https://github.com/psyked/facebook-air-api Within the pages at these URLs, select the Downloads button that appears in the top-left of the page, and you'll get popup containing the download options: To download the raw ActionScript files, select the Download .zip option—listed under the DOWNLOAD SOURCE heading—or to download the precompiled SWC file, select the Facebook Web SDK.swc (or the Facebook Desktop SDK.swc) file—listed under the DOWNLOAD PACKAGES heading. Alternatively, if you have Git installed, you can clone the entire repository, including its past history and references to its original source location, with the following command-line statement:git clone git@github.com:psyked/facebook-actionscript-api.git or git clone git@github.com:psyked/facebook-air-api.git This command will create a new folder with the name 'facebook-actionscript-api' and within that, create three key folders—docs, examples, and src. Unsurprisingly, these folders contain the source code for the library, the documentation for the library, and several sample applications, respectively. How it works... The download locations for this recipe, and the source code for the Facebook SDKs which form the backbone of the recipes in this cookbook, point to Git repositories which are hosted by GitHub. The source code for this repository is itself originally based on the official version of the SDK which is hosted on Google code, but it has been extended and expanded by other developers, (primarily Mark Walters, of http://yourpalmark.com/). The advantage of using our community-driven version of the SDK over the official one is that the source code is traditionally updated much more frequently, and includes a wide array of value-object classes, which the official version of the SDK does not yet include. There's more... Not sure which version of the SDK is best for your project? The Flash Player version, or the AIR version of the SDK? In addition to the different download options, there are also two different versions of the Facebook ActionScript 3 SDK, and the one which we will use depends on whether we're building desktop applications that run in Adobe AIR, or browser-based applications that use the Flash Player. Both versions of the SDK are available for download from GitHub, but you can only use the Adobe AIR libraries with an Adobe AIR project, and the web-based libraries will only work properly with a web-based Flash Builder project that has the Facebook JavaScript SDK included in the HTML template, which is what we'll look at in the next article, Preparing your Flash Player application's HTML template for Facebook integration. What if I want to build my own Facebook library? There's nothing 'magical' about this Facebook ActionScript API—everything it can do is built on standard capabilities of ActionScript 3 and the Flash Player. If you wanted to, it's entirely possible to write your own code that works with Facebook without using this library, but why, as mentioned in the introduction, should you re-invent the wheel? That doesn't mean that the official API isn't subject to an occasional change—the move by Facebook to the 'Open Graph' in 2010 is evidence of that—but it does mean that there's always going to be someone maintaining the project and making sure it works with the latest version of the Facebook API.
Read more
  • 0
  • 0
  • 2483
article-image-oracle-e-business-suite-creating-items-inventory
Packt
18 Aug 2011
7 min read
Save for later

Oracle E-Business Suite: Creating Items in Inventory

Packt
18 Aug 2011
7 min read
  Oracle E-Business Suite 12 Financials Cookbook Take the hard work out of your daily interactions with E-Business Suite financials by using the 50+ recipes from this cookbook         Read more about this book       Oracle E-Business Suite 12 Financials is a solution that provides out-of-the-box features to meet global financial reporting and tax requirements with one accounting, tax, banking, and payments model, and makes it easy to operate shared services across businesses and regions. In this article by Yemi Onigbode, author of Oracle E-Business Suite 12 Financials Cookbook, we will start with recipes for creating Items. We will cover: Creating Items Exploring Item attributes Creating Item templates Exploring Item controls (For more resources on Oracle, see here.) Introduction An organization's operations include the buying and selling of products and services. Items can represent the products and services that are purchased and sold in an organization. Let's start by looking at the Item creation process. The following diagram details the process for creating Items: The Item Requester (the person who requests an Item) completes an Item Creation Form, which should contain information such as: Costing information Pricing Information Item and Product Categories Details of some of the Item attributes The inventory organization details Once complete, a message is sent to the Master Data Manager (the person who maintains the master data) to create the Item. The message could be sent by fax, e-mail, and so on. The Master Data Manager reviews the form and enters the details of the Item into Oracle E-Business Suite by creating the Item. Once complete, a message is sent to the Item Requester. The Item Requester reviews the Item setup on the system. Let's look at how Items are created and explore the underlying concepts concerning the creation of Items. Creating Items Oracle Inventory provides us with the functionality to create Items. Sets of attributes are assigned to an Item. The attributes define the characteristics of the Item. A group of attributes values defines a template, and a template can be assigned to an Item to automatically define the set of attribute values. An Item template defines the Item Type. For example, a Finished Good template will identify certain characteristics that define the Item as a finished good, with attributes such as "Inventory Item" and "Stockable" with a value of "Yes". Let's look at how to create an Item in Oracle Inventory. We will also assign a Finished Good template to the Item. Getting ready Log in to Oracle E-Business Suite R12 with the username and password assigned to you by the System Administrator. If you are working on the Vision demonstration database, you can use OPERATIONS/WELCOME as the USERNAME/PASSWORD: Select the Inventory Responsibility. Select the V1 Inventory Organization. How to do it... Let's list the steps required to create an Item: Navigate to Items | Master Items. Please note that Items are defined in the Master Organization. Enter the Item code, for example, PRD20001. Enter a description for the Item: Select Copy From from the tools menu (or press Alt+T). We are going to copy the attributes from the Finished Good template: We can also copy attributes from an existing Item. Enter Finished Good and click on the Apply button (or press Alt+A) and click on the Done button. Save the Item definition by clicking on the Save icon (or press Ctrl+S). How it works... Items contain attributes and attributes contain information about an Item. Attributes can be controlled centrally at the Master Organization level or at the Inventory Organization level. There's more... Once the Item is created, we need to assign it to a category and an inventory organization. Assigning Items to inventory organizations For us to be able to perform transactions with the Item in the inventory, we need to assign the Item to an inventory organization. We can also use the organization Item form to change the attributes at the organization level. For example, an Item may be classified as raw materials in one organization and finished goods in another organization. From the Tools menu, select Organization Assignment. Select the inventory organization for the Item. For example, A1–ACME Corporation. Click on the Assigned checkbox. Save the assignment. Assigning Items to categories When an Item is created, it is assigned to a default category. However, you may want to perform transactions with the Item in more than one functional area, such as Inventory, Purchasing, Cost Management, Service, Engineering, and so on. You need to assign the Item to the relevant functional area. A category within a functional area is a logical classification of Items with similar characteristics. From the Tools menu, select Categories. Select the Categories Set, Control Level, and the Category combination to assign to the Item: Save the assignment. Exploring Item attributes There are more than 250 Item attributes grouped into 17 main attribute groups. In this recipe, we will explore the main groups that are used within the financial modules. How to do it... Let's explore some Item attributes: Search for the Finished Good Item by navigating to Items | Master Items: Click on the Find icon. You then enter the Item code and click on the Find button to search for the Item. Select the tabs to review each of the attributes group: In the Main tab, check that the Item Status is Active. We can also enter a long description in the Long Description field. The default value of the primary Unit of Measure (UOM) can be defined in the INV: Default Primary Unit of Measure profile option. The value can be overwritten when creating the Item. The Primary UOM is the default UOM used in other modules. For example, in Receivables it is used for invoices and credit memos. In the Inventory tab, check that the following are enabled: Inventory Item: It enables the Item to be transacted in Inventory. The default Inventory Item category is automatically assigned to the Item, if enabled. Stockable: It enables the Item to be stocked in Inventory. Transactable: Order Management uses this flag to determine how returns are transacted in Inventory. Reservable: It enables the reservation of Items during transactions. For example, during order entry in Order Management. In the Costing tab, check that the following are enabled: Costing: Enables the accounting for Item costs. It can be overridden in the Cost Management module, if average costing is used. Cost of Goods Sold Account: The cost of goods sold account is entered. This is a general ledger account. The value defaults from the Organization parameters. In the Purchasing tab, enter a Default Buyer for the purchase orders, a List Price, and an Expense Account. Check that the following are enabled: Purchased: It enables us to purchase and receive the Item. Purchasable: It enables us to create a Purchase Order for the Item. Allow Description Update: It enables us to change the description of the Item when raising the Purchase Order. RFQ Required: Set this value to Yes to enable us to require a quotation for this Item. Taxable: Set this value to Yes with the Input Tax Classification Code as VAT–15%. This can be used with the default rules in E-Tax. Invoice Matching: Receipt Required–Yes. This is to allow for three-way matching. In the Receiving tab, review the controls. In the Order Management tab, check that the following are enabled: Customer Ordered: This enables us to define prices for an Item assigned to a price list. Customer Orders Enabled: This enables us to sell the Item. Shippable: This enables us to ship the Item to the Customer. Internal Ordered: This enables us to order an Item via internal requisitions. Internal Orders Enabled: This enables us to temporarily exclude an Item from internal requisitions. OE Transactable: This is used for demand management of an Item. In the Invoicing tab, enter values for the Accounting Rule, Invoicing Rule, Output Tax Classification Code, and Payment Terms. Enter the Sales Account code and check that the Invoiceable Item and Invoice Enabled checkboxes are enabled.
Read more
  • 0
  • 0
  • 16621

article-image-magento-exploring-themes
Packt
16 Aug 2011
6 min read
Save for later

Magento: Exploring Themes

Packt
16 Aug 2011
6 min read
  Magento 1.4 Themes Design Magento terminology Before you look at Magento themes, it's beneficial to know the difference between what Magento calls interfaces and what Magento calls themes, and the distinguishing factors of websites and stores. Magento websites and Magento stores To add to this, the terms websites and stores have a slightly different meaning in Magento than in general and in other systems. For example, if your business is called M2, you might have three Magento stores (managed through the same installation of Magento) called: Blue Store Red Store Yellow Store In this case, Magento refers to M2 as the website and the stores are Blue Store, Red Store, and Yellow Store. Each store then has one or more store views associated with it too. The simplest Magento website consists of a store and store view (usually of the same name): A slightly more complex Magento store may just have one store view for each store. This is a useful technique if you want to manage more than one store in the same Magento installation, with each store selling different products (for example, the Blue Store sells blue products and the Yellow Store sells yellow products). If a store were to make use of more than one Magento store view, it might be, to present customers with a bi-lingual website. For example, our Blue Store may have an English, French, and Japanese store view associated with it: Magento interfaces An interface consists of one or more Magento themes that comprise how your stores look and function for your customers. Interfaces can be assigned at two levels in Magento: At the website level At the store view level If you assign an interface at the website level of your Magento installation, all stores associated with the interface inherit the interface. For example, imagine your website is known as M2 in Magento and it contains three stores called: Blue Store Red Store Yellow Store If you assign an interface at the website level (that is, M2), then the subsequent stores, Blue Store, Red Store, and Yellow Store, inherit this interface: If you assigned the interface at the store view level of Magento, then each store view can retain a different interface: Magento packages A Magento package typically contains a base theme, which contains all of the templates, and other files that Magento needs to run successfully, and a custom theme. Let's take a typical example of a Magento store, M2. This may have two packages: the base package, located in the app/design/frontend/base/ directory and another package which itself consists of two themes: The base theme is in the app/design/frontend/base/ directory. The second package contains the custom theme's default theme in the app/design/frontend/ default/ directory, which acts as a base theme within the package. The custom theme itself, which is the non-default theme, is in the app/design/frontend/our-custom- theme/default/ and app/design/frontend/our-custom-theme/custom-theme/ directories. By default, Magento will look for a required file in the following order: Custom theme directory: app/design/frontend/our-custom-theme/ custom-theme/ Custom theme's default directory: app/design/frontend/our-custom-theme/ default/ Base directory: app/design/frontend/base/ Magento themes A Magento theme fits in to the Magento hierarchy in a number of positions: it can act as an interface or as a store view. There's more to discover about Magento themes yet, though there are two types of Magento theme: a base theme (this was called a default theme in Magento 1.3) and a non-default theme. Base theme A base theme provides all conceivable files that a Magento store requires to run without error, so that non-default themes built to customize a Magento store will not cause errors if a file does not exist within it. The base theme does not contain all of the CSS and images required to style your store, as you'll be doing this with our non-default theme. Don't change the base package! It is important that you do not edit any files in the base package and that you do not attempt to create a custom theme in the base package, as this will make upgrading Magento fully difficult. Make sure any custom themes you are working on are within their own design package; for example, your theme's files should be located at app/design/ frontend/your-package-name/default and skin/frontend/ your-package-name/default. Default themes A default theme in Magento 1.4 changes aspects of your store but does not need to include every file required by Magento as a base theme does, though it must just contain at least one file for at least one aspect of a theme (that is, locales, skins, templates, layout): Default themes in Magento 1.3 In Magento 1.3, the default theme acted the way the base theme did in Magento 1.4, providing every file that your Magento store required to operate. Non-default themes A non-default theme changes aspects of a Magento store but does not need to include every file required by Magento as the base theme does; it must just contain at least one file for at least one aspect of a theme (that is, locales, skins, templates, layout): In this way, non-default themes are similar to a default theme in Magento. Non-default themes can be used to alter your Magento store for different seasonal events such as Christmas, Easter, Eid, Passover, and other religious festivals, as well as events in your industry's corporate calendar such as annual exhibitions and conferences. Blocks in Magento Magento uses blocks to differentiate between the various components of its functionality, with the idea that this makes it easier for Magento developers and Magento theme designers to customize the functionality of Magento and the look and feel of Magento respectively. There are two types of blocks in Magento: Content blocks Structural blocks Content blocks A content block displays the generated XHTML provided by Magento for any given feature. Content blocks are used within Magento structural blocks. Examples of content blocks in Magento include the following: The search feature Product listings The mini cart Category listings Site navigation links Callouts (advertising blocks) The following diagram illustrates how a Magento store might have content blocks positioned within its structural blocks: Simply, content blocks are the what of a Magento theme: they define what type of content appears within any given page or view within Magento. Structural blocks In Magento, a structural block exists only to maintain a visual hierarchy to a page. Typical structural blocks in a Magento theme include: Header Primary area Left column Right column Footer
Read more
  • 0
  • 0
  • 2551
Modal Close icon
Modal Close icon